1
Fork 0

Compare commits

..

1 commit

Author SHA1 Message Date
196334fc93
*Beginning of feature/detach-parse branch* 2024-11-14 00:34:53 +01:00
48 changed files with 735 additions and 2861 deletions

3
.gitignore vendored
View file

@ -15,6 +15,3 @@ Cargo.lock
# Environment
.env.local
# IntelliJ IDEA thing, mostly broken versioning
.idea/misc.xml

6
.idea/.gitignore vendored
View file

@ -1,6 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/acrate-inbox/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" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View file

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="acrate" uuid="8258414e-095d-430b-a0a5-b48e72af23a9">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql:///acrate</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<svg height="100%" id="emblematic-background" version="1.1" viewBox="0 0 512 512" width="100%" xmlns="http://www.w3.org/2000/svg">
<rect fill="#d14224" height="512" stroke-width="1.0016" width="512"/>
</svg>
<svg height="63%" id="emblematic-icon" preserveAspectRatio="xMidYMid meet" viewBox="0 0 640 512" width="63%" x="94.72" xmlns="http://www.w3.org/2000/svg" y="94.72">
<!--! Font Awesome Pro 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2024 Fonticons, Inc. -->
<path d="M58.9 42.1c3-6.1 9.6-9.6 16.3-8.7L320 64 564.8 33.4c6.7-.8 13.3 2.7 16.3 8.7l41.7 83.4c9 17.9-.6 39.6-19.8 45.1L439.6 217.3c-13.9 4-28.8-1.9-36.2-14.3L320 64 236.6 203c-7.4 12.4-22.3 18.3-36.2 14.3L37.1 170.6c-19.3-5.5-28.8-27.2-19.8-45.1L58.9 42.1zM321.1 128l54.9 91.4c14.9 24.8 44.6 36.6 72.5 28.6L576 211.6v167c0 22-15 41.2-36.4 46.6l-204.1 51c-10.2 2.6-20.9 2.6-31 0l-204.1-51C79 419.7 64 400.5 64 378.5v-167L191.6 248c27.8 8 57.6-3.8 72.5-28.6L318.9 128h2.2z" fill="#ffffff"/>
</svg>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -1,17 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="FunctionName" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="SillyAssignmentJS" enabled="true" level="WEAK WARNING" enabled_by_default="true" editorAttributes="INFO_ATTRIBUTES" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
<inspection_tool class="UnnecessaryLocalVariableJS" enabled="true" level="WEAK WARNING" enabled_by_default="true" editorAttributes="INFO_ATTRIBUTES">
<option name="m_ignoreImmediatelyReturnedVariables" value="false" />
<option name="m_ignoreAnnotatedVariables" value="false" />
</inspection_tool>
</profile>
</component>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/acrate.iml" filepath="$PROJECT_DIR$/.idea/acrate.iml" />
</modules>
</component>
</project>

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/acrate_database/migrations/2024-11-14-031744_meta/up.sql" dialect="GenericSQL" />
</component>
</project>

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View file

@ -1,3 +1,3 @@
[workspace]
resolver = "2"
members = ["acrate_database", "acrate_rd", "acrate_nodeinfo", "acrate_rdserver"]
members = ["acrate-core", "acrate-hostmeta", "acrate-inbox", "acrate-nodeinfo"]

View file

@ -1,287 +0,0 @@
EUROPEAN UNION PUBLIC LICENCE v. 1.2
EUPL © the European Union 2007, 2016
This European Union Public Licence (the EUPL) applies to the Work (as defined
below) which is provided under the terms of this Licence. Any use of the Work,
other than as authorised under this Licence is prohibited (to the extent such
use is covered by a right of the copyright holder of the Work).
The Work is provided under the terms of this Licence when the Licensor (as
defined below) has placed the following notice immediately following the
copyright notice for the Work:
Licensed under the EUPL
or has expressed by any other means his willingness to license under the EUPL.
1. Definitions
In this Licence, the following terms have the following meaning:
- The Licence: this Licence.
- The Original Work: the work or software distributed or communicated by the
Licensor under this Licence, available as Source Code and also as Executable
Code as the case may be.
- Derivative Works: the works or software that could be created by the
Licensee, based upon the Original Work or modifications thereof. This Licence
does not define the extent of modification or dependence on the Original Work
required in order to classify a work as a Derivative Work; this extent is
determined by copyright law applicable in the country mentioned in Article 15.
- The Work: the Original Work or its Derivative Works.
- The Source Code: the human-readable form of the Work which is the most
convenient for people to study and modify.
- The Executable Code: any code which has generally been compiled and which is
meant to be interpreted by a computer as a program.
- The Licensor: the natural or legal person that distributes or communicates
the Work under the Licence.
- Contributor(s): any natural or legal person who modifies the Work under the
Licence, or otherwise contributes to the creation of a Derivative Work.
- The Licensee or You: any natural or legal person who makes any usage of
the Work under the terms of the Licence.
- Distribution or Communication: any act of selling, giving, lending,
renting, distributing, communicating, transmitting, or otherwise making
available, online or offline, copies of the Work or providing access to its
essential functionalities at the disposal of any other natural or legal
person.
2. Scope of the rights granted by the Licence
The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
sublicensable licence to do the following, for the duration of copyright vested
in the Original Work:
- use the Work in any circumstance and for all usage,
- reproduce the Work,
- modify the Work, and make Derivative Works based upon the Work,
- communicate to the public, including the right to make available or display
the Work or copies thereof to the public and perform publicly, as the case may
be, the Work,
- distribute the Work or copies thereof,
- lend and rent the Work or copies thereof,
- sublicense rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now
known or later invented, as far as the applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to
exercise his moral right to the extent allowed by law in order to make effective
the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to
any patents held by the Licensor, to the extent necessary to make use of the
rights granted on the Work under this Licence.
3. Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as
Executable Code. If the Work is provided as Executable Code, the Licensor
provides in addition a machine-readable copy of the Source Code of the Work
along with each copy of the Work that the Licensor distributes or indicates, in
a notice following the copyright notice attached to the Work, a repository where
the Source Code is easily and freely accessible for as long as the Licensor
continues to distribute or communicate the Work.
4. Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits from
any exception or limitation to the exclusive rights of the rights owners in the
Work, of the exhaustion of those rights or of other applicable limitations
thereto.
5. Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and
obligations imposed on the Licensee. Those obligations are the following:
Attribution right: The Licensee shall keep intact all copyright, patent or
trademarks notices and all notices that refer to the Licence and to the
disclaimer of warranties. The Licensee must include a copy of such notices and a
copy of the Licence with every copy of the Work he/she distributes or
communicates. The Licensee must cause any Derivative Work to carry prominent
notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes or communicates copies of the
Original Works or Derivative Works, this Distribution or Communication will be
done under the terms of this Licence or of a later version of this Licence
unless the Original Work is expressly distributed only under this version of the
Licence — for example by communicating EUPL v. 1.2 only. The Licensee
(becoming Licensor) cannot offer or impose any additional terms or conditions on
the Work or Derivative Work that alter or restrict the terms of the Licence.
Compatibility clause: If the Licensee Distributes or Communicates Derivative
Works or copies thereof based upon both the Work and another work licensed under
a Compatible Licence, this Distribution or Communication can be done under the
terms of this Compatible Licence. For the sake of this clause, Compatible
Licence refers to the licences listed in the appendix attached to this Licence.
Should the Licensee's obligations under the Compatible Licence conflict with
his/her obligations under this Licence, the obligations of the Compatible
Licence shall prevail.
Provision of Source Code: When distributing or communicating copies of the Work,
the Licensee will provide a machine-readable copy of the Source Code or indicate
a repository where this Source will be easily and freely available for as long
as the Licensee continues to distribute or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade names,
trademarks, service marks, or names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
6. Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted
hereunder is owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she brings
to the Work are owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent
Contributors grant You a licence to their contributions to the Work, under the
terms of this Licence.
7. Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous
Contributors. It is not a finished work and may therefore contain defects or
bugs inherent to this type of development.
For the above reason, the Work is provided under the Licence on an as is basis
and without warranties of any kind concerning the Work, including without
limitation merchantability, fitness for a particular purpose, absence of defects
or errors, accuracy, non-infringement of intellectual property rights other than
copyright as stated in Article 6 of this Licence.
This disclaimer of warranty is an essential part of the Licence and a condition
for the grant of any rights to the Work.
8. Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural
persons, the Licensor will in no event be liable for any direct or indirect,
material or moral, damages of any kind, arising out of the Licence or of the use
of the Work, including without limitation, damages for loss of goodwill, work
stoppage, computer failure or malfunction, loss of data or any commercial
damage, even if the Licensor has been advised of the possibility of such damage.
However, the Licensor will be liable under statutory product liability laws as
far such laws apply to the Work.
9. Additional agreements
While distributing the Work, You may choose to conclude an additional agreement,
defining obligations or services consistent with this Licence. However, if
accepting obligations, You may act only on your own behalf and on your sole
responsibility, not on behalf of the original Licensor or any other Contributor,
and only if You agree to indemnify, defend, and hold each Contributor harmless
for any liability incurred by, or claims asserted against such Contributor by
the fact You have accepted any warranty or additional liability.
10. Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon I agree
placed under the bottom of a window displaying the text of this Licence or by
affirming consent in any other similar way, in accordance with the rules of
applicable law. Clicking on that icon indicates your clear and irrevocable
acceptance of this Licence and all of its terms and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and
conditions by exercising any rights granted to You by Article 2 of this Licence,
such as the use of the Work, the creation by You of a Derivative Work or the
Distribution or Communication by You of the Work or copies thereof.
11. Information to the public
In case of any Distribution or Communication of the Work by means of electronic
communication by You (for example, by offering to download the Work from a
remote location) the distribution channel or media (for example, a website) must
at least provide to the public the information requested by the applicable law
regarding the Licensor, the Licence and the way it may be accessible, concluded,
stored and reproduced by the Licensee.
12. Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon
any breach by the Licensee of the terms of the Licence.
Such a termination will not terminate the licences of any person who has
received the Work from the Licensee under the Licence, provided such persons
remain in full compliance with the Licence.
13. Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete
agreement between the Parties as to the Work.
If any provision of the Licence is invalid or unenforceable under applicable
law, this will not affect the validity or enforceability of the Licence as a
whole. Such provision will be construed or reformed so as necessary to make it
valid and enforceable.
The European Commission may publish other linguistic versions or new versions of
this Licence or updated versions of the Appendix, so far this is required and
reasonable, without reducing the scope of the rights granted by the Licence. New
versions of the Licence will be published with a unique version number.
All linguistic versions of this Licence, approved by the European Commission,
have identical value. Parties can take advantage of the linguistic version of
their choice.
14. Jurisdiction
Without prejudice to specific agreement between parties,
- any litigation resulting from the interpretation of this License, arising
between the European Union institutions, bodies, offices or agencies, as a
Licensor, and any Licensee, will be subject to the jurisdiction of the Court
of Justice of the European Union, as laid down in article 272 of the Treaty on
the Functioning of the European Union,
- any litigation arising between other parties and resulting from the
interpretation of this License, will be subject to the exclusive jurisdiction
of the competent court where the Licensor resides or conducts its primary
business.
15. Applicable Law
Without prejudice to specific agreement between parties,
- this Licence shall be governed by the law of the European Union Member State
where the Licensor has his seat, resides or has his registered office,
- this licence shall be governed by Belgian law if the Licensor has no seat,
residence or registered office inside a European Union Member State.
Appendix
Compatible Licences according to Article 5 EUPL are:
- GNU General Public License (GPL) v. 2, v. 3
- GNU Affero General Public License (AGPL) v. 3
- Open Software License (OSL) v. 2.1, v. 3.0
- Eclipse Public License (EPL) v. 1.0
- CeCILL v. 2.0, v. 2.1
- Mozilla Public Licence (MPL) v. 2
- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
works other than software
- European Union Public Licence (EUPL) v. 1.1, v. 1.2
- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
Reciprocity (LiLiQ-R+).
The European Commission may update this Appendix to later versions of the above
licences without producing a new version of the EUPL, as long as they provide
the rights granted in Article 2 of this Licence and protect the covered Source
Code from exclusive appropriation.
All other changes or additions to this Appendix require the production of a new
EUPL version.

View file

@ -11,19 +11,3 @@ Federation database
> [!Caution]
>
> 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_rd`: Rust typing and utilities for the JSON and XML resource descriptior formats
### Binaries
- `acrate_rdserver`: Resource descriptor web server

13
acrate-core/Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "acrate-core"
version = "0.1.0"
edition = "2021"
[dependencies]
diesel = "2.2.4"
diesel_migrations = "2.2.0"
acrate-hostmeta = { path = "../acrate-hostmeta" }
acrate-nodeinfo = { path = "../acrate-nodeinfo" }
[lints.clippy]
tabs-in-doc-comments = "allow"

4
acrate-core/src/lib.rs Normal file
View file

@ -0,0 +1,4 @@
//! Core crate of the `acrate` project.
pub use acrate_nodeinfo as nodeinfo;
pub use acrate_hostmeta as hostmeta;

View file

@ -1,17 +1,10 @@
[package]
name = "acrate_rd"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
name = "acrate-hostmeta"
version = "0.1.0"
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"]
categories = ["web-programming"]
[dependencies]
log = "0.4.22"
mediatype = { version = "0.19.18", features = ["serde"] }
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"] }

568
acrate-hostmeta/src/lib.rs Normal file
View file

@ -0,0 +1,568 @@
//! Resource descriptior deserializer.
//!
//! # Specification
//!
//! - <https://datatracker.ietf.org/doc/html/rfc6415>
//! - <https://datatracker.ietf.org/doc/html/rfc7033>
use std::collections::HashMap;
use serde::Deserialize;
use thiserror::Error;
/// A resource descriptor object.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
///
#[derive(Debug, Clone, Deserialize)]
pub struct ResourceDescriptor {
/// The resource this document refers to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.1>
///
#[serde(alias = "Subject")]
pub subject: Option<String>,
/// Other names the resource described by this document can be referred to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.2>
///
#[serde(alias = "Alias")]
pub aliases: Option<Vec<String>>,
/// Additional information about the resource described by this document.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.3>
///
#[serde(alias = "Property")]
pub properties: Option<Vec<ResourceDescriptorProperty>>,
/// Links established between the [`Self::subject`] and other resources.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4>
///
#[serde(alias = "Link")]
pub links: Option<Vec<ResourceDescriptorLink>>,
}
/// A link element, which puts the subject resource in relation with another.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
///
#[derive(Debug, Clone, Deserialize)]
pub struct ResourceDescriptorLink {
/// The kind of relation established by the subject with the attached resource.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.1>
///
#[serde(alias = "@rel")]
pub rel: String,
/// The media type of the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
///
#[serde(alias = "@type")]
pub r#type: Option<String>,
/// URI to the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.3>
///
#[serde(alias = "@href")]
pub href: Option<String>,
/// Titles of the resource put in relation in various languages.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
///
pub titles: Option<Vec<HashMap<String, String>>>,
/// Additional information about the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.5>
///
pub properties: Option<Vec<ResourceDescriptorProperty>>,
/// Template to fill to get the URL to resource-specific information.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-4.2>
///
#[serde(alias = "@template")]
pub template: Option<String>,
}
/// A property element, which describes a certain aspect of the subject resource.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.3>
///
#[derive(Debug, Clone, Deserialize)]
pub struct ResourceDescriptorProperty {
/// The property identifier, or type.
#[serde(alias = "@type")]
pub r#type: String,
/// The property value.
pub value: Option<String>,
}
impl ResourceDescriptor {
/// Get a JRD (JSON [`ResourceDescriptor`]).
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/nodeinfo".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptor::get_jrd(&client, url)
/// .await
/// .expect("JRD to be processed correctly");
/// # })
/// ```
///
pub async fn get_jrd(client: &reqwest::Client, url: reqwest::Url) -> Result<Self, GetJRDError> {
use GetJRDError::*;
log::debug!("Getting JRD document at: {url}");
log::trace!("Building request...");
let request = {
log::trace!("Creating new request...");
let mut request = reqwest::Request::new(reqwest::Method::GET, url);
log::trace!("Setting request headers...");
let headers = request.headers_mut();
log::trace!("Setting `Accept: application/json`...");
let _ = headers.insert(reqwest::header::ACCEPT, "application/json".parse().unwrap());
request
};
log::trace!("Sending request...");
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
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!("Ensuring MIME type is acceptable for JRD parsing...");
if !(mime_type == "application/json" || mime_type == "application/jrd+json") {
log::error!("MIME type `{mime_type}` is not acceptable for JRD parsing.");
return Err(ContentTypeInvalid)
}
log::trace!("Attempting to parse response as JSON...");
let data = response.json::<Self>()
.await
.map_err(Parse)?;
Ok(data)
}
/// Get a XRD (Extensible [`ResourceDescriptor`]).
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptor::get_xrd(&client, url)
/// .await
/// .expect("XRD to be processed correctly");
/// # })
/// ```
///
pub async fn get_xrd(client: &reqwest::Client, url: reqwest::Url) -> Result<Self, GetXRDError> {
use GetXRDError::*;
log::debug!("Getting host-meta XRD document at: {url}");
log::trace!("Building request...");
let request = {
log::trace!("Creating new request...");
let mut request = reqwest::Request::new(reqwest::Method::GET, url);
log::trace!("Setting request headers...");
let headers = request.headers_mut();
log::trace!("Setting `Accept: application/xrd+xml`...");
let _ = headers.insert(reqwest::header::ACCEPT, "application/xrd+xml".parse().unwrap());
request
};
log::trace!("Sending request...");
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
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!("Ensuring MIME type is acceptable for XRD parsing...");
if mime_type != "application/xrd+xml" {
log::error!("MIME type `{mime_type}` is not acceptable for XRD parsing.");
return Err(ContentTypeInvalid)
}
log::trace!("Attempting to parse response as text...");
let data = response.text()
.await
.map_err(Decode)?;
log::trace!("Parsing response as XML...");
let data = quick_xml::de::from_str::<Self>(&data)
.map_err(Parse)?;
Ok(data)
}
/// Attempt to discover a [`ResourceDescriptor`] at the given URL in various ways.
///
/// In order, this method attempts:
///
/// 1. HTTPS [XRD](Self::get_xrd)
/// 2. HTTPS [JRD](Self::get_jrd)
/// 3. HTTPS [JRD](Self::get_jrd) with .json path extension
/// 4. HTTP [XRD](Self::get_xrd)
/// 5. HTTP [JRD](Self::get_jrd)
/// 6. HTTP [JRD](Self::get_jrd) with .json path extension
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptor::discover(&client, url)
/// .await
/// .expect("resource descriptor to be discovered correctly");
/// # })
/// ```
///
pub async fn discover(client: &reqwest::Client, mut url: reqwest::Url) -> Result<Self, ResourceDescriptorDiscoveryError> {
use ResourceDescriptorDiscoveryError::*;
log::debug!("Discovering resource descriptor document at: {url}");
log::trace!("Unsetting URL query...");
url.set_query(None);
log::trace!("Unsetting URL fragment...");
url.set_fragment(None);
log::trace!("Setting URL scheme to HTTPS...");
url.set_scheme("https")
.map_err(UrlManipulation)?;
log::trace!("Cloning URL for HTTPS XRD retrieval...");
let https_xrd_url = url.clone();
log::trace!("Attempting HTTPS XRD retrieval...");
let https_xrd = match Self::get_xrd(client, https_xrd_url).await {
Ok(data) => {
log::trace!("HTTPS XRD retrieval was successful, returning...");
return Ok(data)
}
Err(err) => {
log::warn!("HTTPS XRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTPS JRD retrieval...");
let https_jrd_url = url.clone();
log::trace!("Attempting HTTPS JRD retrieval...");
let https_jrd = match Self::get_jrd(client, https_jrd_url).await {
Ok(data) => {
log::trace!("HTTPS JRD retrieval was successful, returning...");
return Ok(data)
}
Err(err) => {
log::warn!("HTTPS JRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTPS JRD .json retrieval...");
let mut https_jrdj_url = url.clone();
log::trace!("Altering URL path for HTTPS JRD .json retrieval...");
https_jrdj_url.set_path(
&format!("{}.json", https_jrdj_url.path())
);
log::trace!("Attempting HTTPS JRD .json retrieval...");
let https_jrdj = match Self::get_jrd(client, https_jrdj_url).await {
Ok(data) => {
log::trace!("HTTPS JRD .json retrieval was successful, returning...");
return Ok(data)
}
Err(err) => {
log::warn!("HTTPS JRD .json retrieval failed.");
err
}
};
log::trace!("Setting URL scheme to HTTP...");
url.set_scheme("http")
.map_err(UrlManipulation)?;
log::trace!("Cloning URL for HTTP XRD retrieval...");
let http_xrd_url = url.clone();
log::trace!("Attempting HTTP XRD retrieval...");
let http_xrd = match Self::get_xrd(client, http_xrd_url).await {
Ok(data) => {
log::trace!("HTTP XRD retrieval was successful, returning...");
return Ok(data)
}
Err(err) => {
log::warn!("HTTP XRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTP JRD retrieval...");
let http_jrd_url = url.clone();
log::trace!("Attempting HTTP JRD retrieval...");
let http_jrd = match Self::get_jrd(client, http_jrd_url).await {
Ok(data) => {
log::trace!("HTTP JRD retrieval was successful, returning...");
return Ok(data)
}
Err(err) => {
log::warn!("HTTP JRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTP JRD .json retrieval...");
let mut http_jrdj_url = url.clone();
log::trace!("Altering URL path for HTTPS JRD .json retrieval...");
http_jrdj_url.set_path(
&format!("{}.json", http_jrdj_url.path())
);
log::trace!("Attempting HTTP JRD .json retrieval...");
let http_jrdj = match Self::get_jrd(client, http_jrdj_url).await {
Ok(data) => {
log::trace!("HTTP JRD .json retrieval was successful, returning...");
return Ok(data)
}
Err(err) => {
log::warn!("HTTP JRD .json retrieval failed.");
err
}
};
Err(
ResourceDescriptorDiscoveryError::Fetch(
ResourceDescriptorDiscoveryFailures {
https_xrd,
https_jrd,
https_jrdj,
http_xrd,
http_jrd,
http_jrdj,
}
)
)
}
/// Well-known path for host-meta documents.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-2>
///
pub const WELLKNOWN_HOSTMETA_PATH: &str = "/.well-known/host-meta";
/// Attempt to discover a host-meta document at the given base URL.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let base: reqwest::Url = "https://junimo.party".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptor::discover_hostmeta(&client, base)
/// .await
/// .expect("host-meta to be discovered correctly");
/// })
/// ```
///
pub async fn discover_hostmeta(client: &reqwest::Client, mut base: reqwest::Url) -> Result<Self, ResourceDescriptorDiscoveryError> {
base.set_path(Self::WELLKNOWN_HOSTMETA_PATH);
Self::discover(client, base)
.await
}
}
/// Error occurred during [`ResourceDescriptor::discover`].
#[derive(Debug, Error)]
pub enum ResourceDescriptorDiscoveryError {
/// Manipulation of the provided base [`reqwest::Url`] failed.
///
/// See [reqwest::Url::set_scheme] for possible causes.
#[error("manipulation of the provided URL failed")]
UrlManipulation(()),
/// All attempts of fetching a resource descriptor document failed.
#[error("fetchign the resource descriptor document failed")]
Fetch(ResourceDescriptorDiscoveryFailures),
}
/// Request errors occurred during [`ResourceDescriptor::discover`].
#[derive(Debug, Error)]
#[error("all attempts of fetching the resource descriptor document failed")]
pub struct ResourceDescriptorDiscoveryFailures {
/// HTTPS XRD retrieval.
pub https_xrd: GetXRDError,
/// HTTPS JRD retrieval.
pub https_jrd: GetJRDError,
/// HTTPS JRD with .json extension retrieval.
pub https_jrdj: GetJRDError,
/// HTTPS XRD retrieval.
pub http_xrd: GetXRDError,
/// HTTP JRD retrieval.
pub http_jrd: GetJRDError,
/// HTTP JRD with .json extension retrieval.
pub http_jrdj: GetJRDError,
}
/// Error occurred during [`ResourceDescriptor::get_xrd`].
#[derive(Debug, Error)]
pub enum GetXRDError {
/// The HTTP request failed.
#[error("the HTTP request failed")]
Request(reqwest::Error),
/// The `Content-Type` header of the response is missing.
#[error("the Content-Type header of the response is missing")]
ContentTypeMissing,
/// 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 decoded as text.
#[error("the document failed to be decoded as text")]
Decode(reqwest::Error),
/// The document failed to be parsed as XML by [`quick_xml`].
#[error("the document failed to be parsed as XML")]
Parse(quick_xml::DeError),
}
/// Error occurred during [`ResourceDescriptor::get_jrd`].
#[derive(Debug, Error)]
pub enum GetJRDError {
/// The HTTP request failed.
#[error("the HTTP request failed")]
Request(reqwest::Error),
/// The `Content-Type` header of the response is missing.
#[error("the Content-Type header of the response is missing")]
ContentTypeMissing,
/// 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")]
Parse(reqwest::Error),
}
/// 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()),
}
}

View file

@ -0,0 +1,62 @@
const CARGO_PKG_NAME: &str = env!("CARGO_PKG_NAME");
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const CARGO_PKG_REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
fn init_log() {
let mut builder = pretty_env_logger::formatted_builder();
builder.target(pretty_env_logger::env_logger::Target::Stdout);
builder.filter_level(log::LevelFilter::max());
builder.is_test(true);
if builder.try_init().is_ok() {
log::debug!("Initialized logging!");
}
}
fn make_client() -> reqwest::Client {
let user_agent = format!("{CARGO_PKG_NAME}/{CARGO_PKG_VERSION} ({CARGO_PKG_REPOSITORY})");
reqwest::Client::builder()
.user_agent(user_agent)
.build()
.expect("reqwest client to build")
}
macro_rules! test_discover_hostmeta {
($id:ident, $url:literal) => {
test_discover_hostmeta!($id, $url,);
};
($id:ident, $url:literal, $($tag:meta),*) => {
mod $id {
use acrate_hostmeta::*;
use super::*;
#[tokio::test]
$(#[$tag])*
async fn test() {
init_log();
let client = make_client();
let base: reqwest::Url = $url.parse()
.expect("a valid URL");
let doc = ResourceDescriptor::discover_hostmeta(&client, base)
.await
.expect("host-meta discovery to succeed");
log::info!("Parsed host-meta document: {doc:#?}");
}
}
};
}
test_discover_hostmeta!(akkoma, "https://junimo.party");
test_discover_hostmeta!(mastodon, "https://mastodon.social");
test_discover_hostmeta!(misskey, "https://misskey.io");
test_discover_hostmeta!(iceshrimpnet, "https://ice.frieren.quest");
test_discover_hostmeta!(gotosocial, "https://alpha.polymaths.social");
test_discover_hostmeta!(bridgyfed, "https://fed.brid.gy");
test_discover_hostmeta!(threads, "https://threads.net", ignore = "does not support host-meta");
test_discover_hostmeta!(snac, "https://ngoa.giao.loan", ignore = "does not support host-meta");
test_discover_hostmeta!(hollo, "https://hollo.social", ignore = "does not support host-meta");

12
acrate-inbox/Cargo.toml Normal file
View file

@ -0,0 +1,12 @@
[package]
name = "acrate-inbox"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.93"
axum = "0.7.7"
log = "0.4.22"
micronfig = "0.3.0"
pretty_env_logger = "0.5.0"
tokio = { version = "1.41.1", features = ["macros", "net", "rt-multi-thread"] }

View file

@ -0,0 +1,3 @@
micronfig::config!(
ACRATE_INBOX_BIND_ADDRESS: String,
);

View file

@ -1,6 +1,4 @@
use std::sync::Arc;
use anyhow::Context;
use axum::Extension;
mod config;
mod route;
@ -11,21 +9,13 @@ async fn main() -> anyhow::Result<std::convert::Infallible> {
pretty_env_logger::init();
log::debug!("Logging initialized!");
log::trace!("Creating Minijinja environment...");
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");
log::trace!("Creating Axum router...");
let app = axum::Router::new()
.route("/*path", axum::routing::get(route::webfinger_handler))
.layer(Extension(Arc::new(mj)));
.route("/inbox", axum::routing::post(route::inbox_handler));
log::trace!("Axum router created successfully!");
log::trace!("Creating Tokio listener...");
let bind_address = config::ACRATE_WEBFINGER_BIND_ADDRESS();
let bind_address = config::ACRATE_INBOX_BIND_ADDRESS();
let listener = tokio::net::TcpListener::bind(bind_address)
.await
.context("failed to bind listener to address")?;

View file

@ -0,0 +1,8 @@
#[allow(unreachable_code)]
pub async fn inbox_handler() {
todo!("pre-validation hook");
todo!("validate signature");
todo!("post-validation hook");
todo!("database storage");
todo!("post-storage hook");
}

View file

@ -0,0 +1,20 @@
[package]
name = "acrate-nodeinfo"
version = "0.1.0"
edition = "2021"
[dependencies]
acrate-hostmeta = { version = "0.1.0", 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"

View file

@ -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),
@ -175,7 +172,7 @@ impl NodeInfo {
/// # Specification
///
/// - <https://github.com/jhass/nodeinfo/blob/main/PROTOCOL.md#discovery>
pub const WELLKNOWN_NODEINFO_PATH: &'static str = "/.well-known/nodeinfo";
pub const WELLKNOWN_NODEINFO_PATH: &str = "/.well-known/nodeinfo";
/// Discover and get the latest NodeInfo version available given a certain base URL.
///
@ -209,13 +206,12 @@ 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::ResourceDescriptor::discover(client, base)
.await
.map_err(Get)?
.jrd();
.map_err(Discovery)?;
log::trace!("Getting a list of NodeInfo document links...");
let mut links = discovery.links;
let mut links = discovery.links.unwrap_or_default();
links.sort_unstable_by_key(|o| o.rel.clone()); // TODO: Performance can be improved.
links.reverse();
@ -318,7 +314,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),
Discovery(acrate_hostmeta::ResourceDescriptorDiscoveryError),
/// No compatible NodeInfo documents were detected at the given URL.
#[error("no compatible NodeInfo documents were detected at the given URL")]
Unsupported,
@ -356,21 +352,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 +424,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 +459,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 +471,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()),
}
}

View file

@ -1,34 +0,0 @@
[package]
name = "acrate_database"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
edition = "2021"
description = "Database schema and migrations for the acrate project"
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
license = "EUPL-1.2"
keywords = ["fediverse", "diesel", "database", "postgresql", "database-migrations"]
categories = ["database"]
[dependencies]
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 }
uuid = "1.11.0"
[features]
bin = ["diesel_migrations", "micronfig", "pretty_env_logger"]
[lib]
name = "acrate_database"
[[bin]]
name = "acrate_database_migrate"
required-features = ["bin"]
[lints.clippy]
tabs-in-doc-comments = "allow"

View file

@ -1,6 +0,0 @@
DROP TABLE IF EXISTS meta_properties CASCADE;
DROP TABLE IF EXISTS meta_link_properties CASCADE;
DROP TABLE IF EXISTS meta_link_titles CASCADE;
DROP TABLE IF EXISTS meta_links CASCADE;
DROP TABLE IF EXISTS meta_aliases CASCADE;
DROP TABLE IF EXISTS meta_subjects CASCADE;

View file

@ -1,69 +0,0 @@
CREATE TABLE IF NOT EXISTS meta_subjects (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
subject BPCHAR,
redirect BPCHAR,
CONSTRAINT either_subject_or_redirect_not_null CHECK (
(subject IS NOT NULL AND redirect IS NULL)
OR
(subject IS NULL AND redirect IS NOT NULL)
),
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_aliases (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
alias BPCHAR NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_links (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
rel BPCHAR NOT NULL,
type BPCHAR,
href BPCHAR,
template BPCHAR,
CONSTRAINT either_href_or_template_not_null CHECK (
(href IS NOT NULL AND template IS NULL)
OR
(href IS NULL AND template IS NOT NULL)
),
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_link_properties (
id UUID DEFAULT gen_random_uuid(),
meta_link_id UUID REFERENCES meta_links (id) NOT NULL,
rel BPCHAR NOT NULL,
value BPCHAR,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_properties (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
rel BPCHAR NOT NULL,
value BPCHAR,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_link_titles (
id UUID DEFAULT gen_random_uuid(),
meta_link_id UUID REFERENCES meta_links (id) NOT NULL,
language BPCHAR NOT NULL DEFAULT 'und',
value BPCHAR NOT NULL,
CONSTRAINT unique_languages UNIQUE (meta_link_id, language),
PRIMARY KEY(id)
);

View file

@ -1,10 +0,0 @@
UPDATE meta_subjects SET subject = 'invalid:subject.null' WHERE subject IS NULL;
ALTER TABLE meta_subjects ALTER subject SET NOT NULL;
ALTER TABLE meta_subjects ADD CONSTRAINT either_subject_or_redirect_not_null
CHECK (
(subject IS NOT NULL AND redirect IS NULL)
OR
(subject IS NULL AND redirect IS NOT NULL)
);

View file

@ -1,5 +0,0 @@
ALTER TABLE meta_subjects DROP CONSTRAINT either_subject_or_redirect_not_null;
ALTER TABLE meta_subjects ALTER subject DROP NOT NULL;
UPDATE meta_subjects SET subject = NULL WHERE subject = 'invalid:subject.null';

View file

@ -1,50 +0,0 @@
//! Run all migrations defined by [`acrate_database`].
//!
//! This uses the configuration defined in [`acrate_database::config`].
//!
//! ## Exit codes
//!
//! | Code | Meaning |
//! |-----:|---------|
//! | `0` | Migrations applied successfully |
//! | `1` | Couldn't connect to the database |
//! | `2` | Couldn't apply migrations |
//! | `101` | Configuration is invalid |
//!
use std::process::exit;
use diesel::{Connection, PgConnection};
use diesel_migrations::{EmbeddedMigrations, MigrationHarness};
mod config {
micronfig::config! {
ACRATE_DATABASE_DATABASE_URL: String,
}
}
pub const MIGRATIONS: EmbeddedMigrations = diesel_migrations::embed_migrations!();
fn main() {
pretty_env_logger::init();
log::info!("Logging initialized successfully!");
log::trace!("Determining database URL...");
let db = config::ACRATE_DATABASE_DATABASE_URL();
log::debug!("Connecting to: {db:?}");
let mut db = match PgConnection::establish(db) {
Err(e) => {
log::error!("Failed to connect to the PostgreSQL database: {e:#?}");
exit(1);
}
Ok(db) => db,
};
log::debug!("Running migrations...");
if let Err(e) = db.run_pending_migrations(MIGRATIONS) {
log::error!("Failed to perform migration: {e:#?}");
exit(2);
};
log::info!("Migrations applied successfully!")
}

View file

@ -1,11 +0,0 @@
//! Database schema, migrations, and high level database-reliant structures for the [`acrate`] project.
/// Database schema information automatically generated by [`diesel`].
///
/// Configured by `diesel.toml`.
mod schema;
pub mod meta;
pub use diesel;
pub use diesel_async;

View file

@ -1,560 +0,0 @@
//! Tables related to web page metadata, XRD and JRD, `host-meta`, `WebFinger`, and so on.
//!
//! # Intended usage
//!
//! 1. An user agent requests an application for the descriptor for a given resource;
//! 2. **The application queries the database using these structures to:**
//! 1. [Determine if a descriptor should be returned, or if it should be handled by another application](MetaSubject);
//! 2. [Determine which aliases the resource has](MetaAlias);
//! 3. [Determine which properties the resource has](MetaProperty);
//! 4. [Determine which links the resource has](MetaLink);
//! 5. [Determine the titles of each link](MetaLinkTitle);
//! 6. [Determine the properties of each link](MetaLinkProperty);
//! 3. The application compiles the data in a single structure that the user agent supports
//! 4. The application returns the data to the user agent
//!
//! # Matching
//!
//! Matching is performed for each single record separately, allowing for example a system administrator to define many separate subjects while globally defining a property for all the resources served.
//!
//! # Reference
//!
//! See [`acrate_rd`] for more information on the specification these structures are based on.
//!
//! # Used by
//!
//! - [`acrate_rdserver`]
//!
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;
/// 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);
/// A matchable record denoting the existence of a resource descriptor.
///
/// # See also
///
/// - [`MetaSubjectInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_subjects)]
#[diesel(check_for_backend(Pg))]
pub struct MetaSubject {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The value the `subject` property should take when this record is matched.
///
/// If [`None`], its value is up for specification by the querying application.
pub subject: Option<String>,
/// Where the querying application should redirect the user agent to when this record is matched.
///
/// If [`Some`], should always override everything else.
pub redirect: Option<String>,
}
/// An [`Insertable`] version of [`MetaSubject`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_subjects)]
#[diesel(check_for_backend(Pg))]
pub struct MetaSubjectInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The value the `subject` property should take when this record is matched.
///
/// If [`None`], its value is up for specification by the querying application.
pub subject: Option<String>,
/// Where the querying application should redirect the user agent to when this record is matched.
///
/// If [`Some`], should always override everything else.
pub redirect: Option<String>,
}
/// A matchable record denoting an alias belonging to a subject.
///
/// # See also
///
/// - [`MetaAliasInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_aliases)]
#[diesel(check_for_backend(Pg))]
pub struct MetaAlias {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The alias to **add** to the list of aliases of the resource.
pub alias: String,
}
/// An [`Insertable`] version of [`MetaAlias`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_aliases)]
#[diesel(check_for_backend(Pg))]
pub struct MetaAliasInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The alias to **add** to the list of aliases of the resource.
pub alias: String,
}
/// A matchable record denoting a link towards another resource someway related with the subject.
///
/// # See also
///
/// - [`MetaLinkInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_links)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLink {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the link establishes between itself and the value of the link.
pub rel: String,
/// The media type of the value of the link.
///
/// Can be [`None`] if it shouldn't be specified.
pub type_: Option<MediaTypeDatabase>,
/// The URI to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::template`] is [`Some`].
pub href: Option<String>,
/// The template to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::href`] is [`Some`].
pub template: Option<String>,
}
/// An [`Insertable`] version of [`MetaLink`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_links)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the link establishes between itself and the value of the link.
pub rel: String,
/// The media type of the value of the link.
///
/// Can be [`None`] if it shouldn't be specified.
pub type_: Option<MediaTypeDatabase>,
/// The URI to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::template`] is [`Some`].
pub href: Option<String>,
/// The template to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::href`] is [`Some`].
pub template: Option<String>,
}
/// A property that a [`MetaLink`] has.
///
/// # See also
///
/// - [`MetaLinkPropertyInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable, Associations)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkProperty {
/// The identity column of the record.
pub id: Uuid,
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The relationship the property establishes between the [`MetaLink`] and the [`MetaLinkProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// An [`Insertable`] version of [`MetaLinkProperty`].
#[derive(Debug, Insertable)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkPropertyInsert {
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The relationship the property establishes between the [`MetaLink`] and the [`MetaLinkProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// A title that a [`MetaLink`] has in a certain language.
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable, Associations)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_titles)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkTitle {
/// The identity column of the record.
pub id: Uuid,
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The language of the title.
pub language: String,
/// The actual contents of the title.
pub value: String,
}
/// An [`Insertable`] version of [`MetaLinkTitle`].
#[derive(Debug, Insertable)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_titles)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkTitleInsert {
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The language of the title.
pub language: String,
/// The actual contents of the title.
pub value: String,
}
/// A matchable record denoting a property that a subject has.
///
/// # See also
///
/// - [`MetaPropertyInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaProperty {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the property establishes between the [`MetaSubject`] and the [`MetaProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// An [`Insertable`] version of [`MetaLinkTitle`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaPropertyInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the property establishes between the [`MetaSubject`] and the [`MetaProperty::value`].
pub rel: String,
/// The value that the property has.
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
where
DB: diesel::backend::Backend,
String: FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(bytes: <DB as diesel::backend::Backend>::RawValue<'_>) -> diesel::deserialize::Result<Self> {
log::trace!("Reading TEXT from the database...");
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()?;
log::trace!("Successfully parsed media type: {mt:?}");
Ok(Self(mt))
}
}
/// Allow [`diesel::sql_types::Text`] values to be written to with [`MediaTypeDatabase`].
impl<DB> ToSql<diesel::sql_types::Text, DB> for MediaTypeDatabase
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();
log::trace!("Serializing media type as TEXT: {mt:?}");
<str as ToSql<diesel::sql_types::Text, DB>>::to_sql(mt, out)
}
}
impl MetaSubject {
/// Synchronously query the records matching the given document and resource.
pub fn query_matching(conn: &mut PgConnection, doc: &str, resource: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_subjects::dsl::*;
let document_is_equal = document.eq(doc);
let resource_matches_pattern = resource.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_subjects
.filter(document_is_equal)
.filter(resource_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, resource: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_subjects::dsl::*;
let document_is_equal = document.eq(doc);
let resource_matches_pattern = resource.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_subjects
.filter(document_is_equal)
.filter(resource_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}
impl MetaAlias {
/// Synchronously query the records matching the given document and resource.
pub fn query_matching(conn: &mut PgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_aliases::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_aliases
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_aliases::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_aliases
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}
impl MetaLink {
/// Synchronously query the records matching the given document and resource.
pub async fn query_matching(conn: &mut PgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_links::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_links
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_links::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_links
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}
impl MetaLinkProperty {
/// Synchronously query the records belonging to the given [`MetaLink`]s.
pub fn query_by_link(conn: &mut PgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
}
/// Asynchronously query the records belonging to the given [`MetaLink`]s.
pub async fn aquery_by_link(conn: &mut AsyncPgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel_async::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
.await
}
}
impl MetaLinkTitle {
/// Synchronously query the records belonging to the given [`MetaLink`]s.
pub fn query_by_link(conn: &mut PgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
}
/// Asynchronously query the records belonging to the given [`MetaLink`]s.
pub async fn aquery_by_link(conn: &mut AsyncPgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel_async::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
.await
}
}
impl MetaProperty {
/// Synchronously query the records matching the given document and resource.
pub fn query_matching(conn: &mut PgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_properties::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_properties
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_properties::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_properties
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}

View file

@ -1,73 +0,0 @@
// @generated automatically by Diesel CLI.
diesel::table! {
meta_aliases (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
alias -> Bpchar,
}
}
diesel::table! {
meta_link_properties (id) {
id -> Uuid,
meta_link_id -> Uuid,
rel -> Bpchar,
value -> Nullable<Bpchar>,
}
}
diesel::table! {
meta_link_titles (id) {
id -> Uuid,
meta_link_id -> Uuid,
language -> Bpchar,
value -> Bpchar,
}
}
diesel::table! {
meta_links (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
rel -> Bpchar,
#[sql_name = "type"]
type_ -> Nullable<Bpchar>,
href -> Nullable<Bpchar>,
template -> Nullable<Bpchar>,
}
}
diesel::table! {
meta_properties (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
rel -> Bpchar,
value -> Nullable<Bpchar>,
}
}
diesel::table! {
meta_subjects (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
subject -> Nullable<Bpchar>,
redirect -> Nullable<Bpchar>,
}
}
diesel::joinable!(meta_link_properties -> meta_links (meta_link_id));
diesel::joinable!(meta_link_titles -> meta_links (meta_link_id));
diesel::allow_tables_to_appear_in_same_query!(
meta_aliases,
meta_link_properties,
meta_link_titles,
meta_links,
meta_properties,
meta_subjects,
);

View file

@ -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"

View file

@ -1,286 +0,0 @@
use thiserror::Error;
use crate::jrd::{GetJRDError, ResourceDescriptorJRD};
use crate::xrd::{GetXRDError, ResourceDescriptorXRD};
#[derive(Debug, Clone)]
pub enum ResourceDescriptor {
/// The resource descriptor is in JRD format.
JRD(ResourceDescriptorJRD),
/// The resource descriptor is in XRD format.
XRD(ResourceDescriptorXRD),
}
impl ResourceDescriptor {
/// Attempt to get a [`ResourceDescriptor`] at the given URL in various ways.
///
/// In order, this method attempts:
///
/// 1. HTTPS [XRD](ResourceDescriptorJRD::get)
/// 2. HTTPS [JRD](ResourceDescriptorJRD::get)
/// 3. HTTPS [JRD](ResourceDescriptorJRD::get) with .json path suffix
/// 4. HTTP [XRD](ResourceDescriptorJRD::get)
/// 5. HTTP [JRD](ResourceDescriptorJRD::get)
/// 6. HTTP [JRD](ResourceDescriptorJRD::get) with .json path suffix
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_rd::any::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptor::get(&client, url)
/// .await
/// .expect("resource descriptor to be discovered correctly");
/// # })
/// ```
///
pub async fn get(client: &reqwest::Client, mut url: reqwest::Url) -> Result<Self, GetError> {
use GetError::*;
log::debug!("Discovering resource descriptor document at: {url}");
log::trace!("Unsetting URL query...");
url.set_query(None);
log::trace!("Unsetting URL fragment...");
url.set_fragment(None);
log::trace!("Setting URL scheme to HTTPS...");
url.set_scheme("https")
.map_err(UrlManipulation)?;
log::trace!("Cloning URL for HTTPS XRD retrieval...");
let https_xrd_url = url.clone();
log::trace!("Attempting HTTPS XRD retrieval...");
let https_xrd = match ResourceDescriptorXRD::get(client, https_xrd_url).await {
Ok(data) => {
log::trace!("HTTPS XRD retrieval was successful, returning...");
return Ok(Self::XRD(data))
}
Err(err) => {
log::warn!("HTTPS XRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTPS JRD retrieval...");
let https_jrd_url = url.clone();
log::trace!("Attempting HTTPS JRD retrieval...");
let https_jrd = match ResourceDescriptorJRD::get(client, https_jrd_url).await {
Ok(data) => {
log::trace!("HTTPS JRD retrieval was successful, returning...");
return Ok(Self::JRD(data))
}
Err(err) => {
log::warn!("HTTPS JRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTPS JRD .json retrieval...");
let mut https_jrdj_url = url.clone();
log::trace!("Altering URL path for HTTPS JRD .json retrieval...");
https_jrdj_url.set_path(
&format!("{}.json", https_jrdj_url.path())
);
log::trace!("Attempting HTTPS JRD .json retrieval...");
let https_jrdj = match ResourceDescriptorJRD::get(client, https_jrdj_url).await {
Ok(data) => {
log::trace!("HTTPS JRD .json retrieval was successful, returning...");
return Ok(Self::JRD(data))
}
Err(err) => {
log::warn!("HTTPS JRD .json retrieval failed.");
err
}
};
log::trace!("Setting URL scheme to HTTP...");
url.set_scheme("http")
.map_err(UrlManipulation)?;
log::trace!("Cloning URL for HTTP XRD retrieval...");
let http_xrd_url = url.clone();
log::trace!("Attempting HTTP XRD retrieval...");
let http_xrd = match ResourceDescriptorXRD::get(client, http_xrd_url).await {
Ok(data) => {
log::trace!("HTTP XRD retrieval was successful, returning...");
return Ok(Self::XRD(data))
}
Err(err) => {
log::warn!("HTTP XRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTP JRD retrieval...");
let http_jrd_url = url.clone();
log::trace!("Attempting HTTP JRD retrieval...");
let http_jrd = match ResourceDescriptorJRD::get(client, http_jrd_url).await {
Ok(data) => {
log::trace!("HTTP JRD retrieval was successful, returning...");
return Ok(Self::JRD(data))
}
Err(err) => {
log::warn!("HTTP JRD retrieval failed.");
err
}
};
log::trace!("Cloning URL for HTTP JRD .json retrieval...");
let mut http_jrdj_url = url.clone();
log::trace!("Altering URL path for HTTPS JRD .json retrieval...");
http_jrdj_url.set_path(
&format!("{}.json", http_jrdj_url.path())
);
log::trace!("Attempting HTTP JRD .json retrieval...");
let http_jrdj = match ResourceDescriptorJRD::get(client, http_jrdj_url).await {
Ok(data) => {
log::trace!("HTTP JRD .json retrieval was successful, returning...");
return Ok(Self::JRD(data))
}
Err(err) => {
log::warn!("HTTP JRD .json retrieval failed.");
err
}
};
Err(Fetch(GetFetchFailures {
https_xrd,
https_jrd,
https_jrdj,
http_xrd,
http_jrd,
http_jrdj,
}))
}
/// Well-known path for host-meta documents.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-2>
///
pub const WELLKNOWN_HOSTMETA_PATH: &'static str = "/.well-known/host-meta";
/// Attempt to discover a host-meta document at the given base URL.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_rd::any::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let base: reqwest::Url = "https://junimo.party".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptor::discover_hostmeta(&client, base)
/// .await
/// .expect("host-meta to be discovered correctly");
/// })
/// ```
///
pub async fn discover_hostmeta(client: &reqwest::Client, mut base: reqwest::Url) -> Result<Self, GetError> {
log::debug!("Attempting discovery of host-meta document of: {base}");
log::trace!("Adding well-known path to the given base URL: {}", Self::WELLKNOWN_HOSTMETA_PATH);
base.set_path(Self::WELLKNOWN_HOSTMETA_PATH);
log::trace!("Starting discovery at: {base}");
Self::get(client, base)
.await
}
pub fn jrd(self) -> ResourceDescriptorJRD {
self.into()
}
pub fn xrd(self) -> ResourceDescriptorXRD {
self.into()
}
}
impl From<ResourceDescriptorJRD> for ResourceDescriptor {
fn from(value: ResourceDescriptorJRD) -> Self {
Self::JRD(value)
}
}
impl From<ResourceDescriptorXRD> for ResourceDescriptor {
fn from(value: ResourceDescriptorXRD) -> Self {
Self::XRD(value)
}
}
impl From<ResourceDescriptor> for ResourceDescriptorJRD {
fn from(value: ResourceDescriptor) -> Self {
match value {
ResourceDescriptor::JRD(jrd) => jrd,
ResourceDescriptor::XRD(xrd) => xrd.into(),
}
}
}
impl From<ResourceDescriptor> for ResourceDescriptorXRD {
fn from(value: ResourceDescriptor) -> Self {
match value {
ResourceDescriptor::JRD(jrd) => jrd.into(),
ResourceDescriptor::XRD(xrd) => xrd,
}
}
}
/// Error occurred during [`ResourceDescriptor::discover`].
#[derive(Debug, Error)]
pub enum GetError {
/// Manipulation of the provided base [`reqwest::Url`] failed.
///
/// See [reqwest::Url::set_scheme] for possible causes.
#[error("manipulation of the provided URL failed")]
UrlManipulation(()),
/// All attempts of fetching a resource descriptor document failed.
#[error("fetchign the resource descriptor document failed")]
Fetch(GetFetchFailures),
}
/// Request errors occurred during [`ResourceDescriptor::discover`].
#[derive(Debug, Error)]
#[error("all attempts of fetching the resource descriptor document failed")]
pub struct GetFetchFailures {
/// HTTPS XRD retrieval.
pub https_xrd: GetXRDError,
/// HTTPS JRD retrieval.
pub https_jrd: GetJRDError,
/// HTTPS JRD with .json extension retrieval.
pub https_jrdj: GetJRDError,
/// HTTPS XRD retrieval.
pub http_xrd: GetXRDError,
/// HTTP JRD retrieval.
pub http_jrd: GetJRDError,
/// HTTP JRD with .json extension retrieval.
pub http_jrdj: GetJRDError,
}

View file

@ -1,277 +0,0 @@
//! Definition and implementation of [`ResourceDescriptorJRD`].
use std::collections::HashMap;
use mediatype::MediaTypeBuf;
use serde::{Serialize, Deserialize};
use thiserror::Error;
use crate::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD, ResourceDescriptorXRD};
/// A resource descriptor in JRD format.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceDescriptorJRD {
/// The resource this document refers to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.1>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
/// Other names the resource described by this document can be referred to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.2>
///
#[serde(default)]
pub aliases: Vec<String>,
/// Additional information about the resource described by this document.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.3>
///
#[serde(default)]
pub properties: HashMap<String, Option<String>>,
/// Links established between the [`Self::subject`] and other resources.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4>
///
#[serde(default)]
pub links: Vec<ResourceDescriptorLinkJRD>,
}
/// A link element, which puts the subject resource in relation with another.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceDescriptorLinkJRD {
/// The kind of relation established by the subject with the attached resource.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.1>
///
pub rel: String,
/// The media type of the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<MediaTypeBuf>,
/// URI to the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.3>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
/// Titles of the resource put in relation in various languages.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
///
#[serde(default)]
pub titles: HashMap<String, String>,
/// Additional information about the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.5>
///
#[serde(default)]
pub properties: HashMap<String, Option<String>>,
/// Template to fill to get the URL to resource-specific information.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-4.2>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
}
impl ResourceDescriptorJRD {
/// Get a [`ResourceDescriptorJRD`] from an URL.
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_rd::jrd::ResourceDescriptorJRD;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/nodeinfo".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptorJRD::get(&client, url)
/// .await
/// .expect("JRD to be processed correctly");
/// # })
/// ```
///
pub async fn get(client: &reqwest::Client, url: reqwest::Url) -> Result<Self, GetJRDError> {
use GetJRDError::*;
log::debug!("Getting JRD document at: {url}");
log::trace!("Building request...");
let request = {
log::trace!("Creating new request...");
let mut request = reqwest::Request::new(reqwest::Method::GET, url);
log::trace!("Setting request headers...");
let headers = request.headers_mut();
log::trace!("Setting `Accept: application/jrd+json, application/json`...");
let _ = headers.insert(
reqwest::header::ACCEPT,
"application/jrd+json, application/json".parse().unwrap()
);
request
};
log::trace!("Sending request...");
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.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!("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:?}");
if !(mime_is_json || mime_is_jrd) {
log::error!("Media type `{media_type}` is not acceptable for JRD parsing.");
return Err(ContentTypeUnsupported);
}
log::trace!("Attempting to parse response as JSON...");
let data = response.json::<Self>()
.await
.map_err(Parse)?;
Ok(data)
}
}
impl From<ResourceDescriptorXRD> for ResourceDescriptorJRD {
fn from(value: ResourceDescriptorXRD) -> Self {
Self {
subject: value.subject,
aliases: value.aliases,
properties: value.properties.into_iter()
.map(From::from)
.collect(),
links: value.links.into_iter()
.map(From::from)
.collect(),
}
}
}
impl From<ResourceDescriptorLinkXRD> for ResourceDescriptorLinkJRD {
fn from(value: ResourceDescriptorLinkXRD) -> Self {
Self {
rel: value.rel,
r#type: value.r#type,
href: value.href,
titles: HashMap::from_iter(
value.titles.into_iter()
.map(From::from)
),
properties: HashMap::from_iter(
value.properties.into_iter()
.map(From::from)
),
template: value.template,
}
}
}
impl From<ResourceDescriptorPropertyXRD> for (String, Option<String>) {
fn from(value: ResourceDescriptorPropertyXRD) -> Self {
(value.rel, value.value)
}
}
impl From<ResourceDescriptorTitleXRD> for (String, String) {
fn from(value: ResourceDescriptorTitleXRD) -> Self {
(value.language, value.value)
}
}
/// Error occurred during [`ResourceDescriptor::get_jrd`].
#[derive(Debug, Error)]
pub enum GetJRDError {
/// The HTTP request failed.
#[error("the HTTP request failed")]
Request(reqwest::Error),
/// The `Content-Type` header of the response is missing.
#[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 document failed to be parsed as JSON by [`reqwest`].
#[error("the document failed to be parsed as JSON")]
Parse(reqwest::Error),
}

View file

@ -1,10 +0,0 @@
//! Rust typing and utilities for the JSON and XML resource descriptior formats.
//!
//! # Specification
//!
//! - <https://datatracker.ietf.org/doc/html/rfc6415>
//! - <https://datatracker.ietf.org/doc/html/rfc7033>
pub mod jrd;
pub mod xrd;
pub mod any;

View file

@ -1,322 +0,0 @@
//! Definition and implementation of [`ResourceDescriptorXRD`].
use mediatype::MediaTypeBuf;
use serde::{Serialize, Deserialize};
use thiserror::Error;
use crate::jrd::{ResourceDescriptorJRD, ResourceDescriptorLinkJRD};
/// A resource descriptor object in XRD format.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "XRD")]
pub struct ResourceDescriptorXRD {
/// The resource this document refers to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.1>
///
#[serde(rename = "Subject")]
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
/// Other names the resource described by this document can be referred to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.2>
///
#[serde(rename = "Alias")]
#[serde(default)]
pub aliases: Vec<String>,
/// Additional information about the resource described by this document.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.3>
///
#[serde(rename = "Property")]
#[serde(default)]
pub properties: Vec<ResourceDescriptorPropertyXRD>,
/// Links established between the [`Self::subject`] and other resources.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4>
///
#[serde(rename = "Link")]
#[serde(default)]
pub links: Vec<ResourceDescriptorLinkXRD>,
}
/// A link element, which puts the subject resource in relation with another.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
///
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Link")]
pub struct ResourceDescriptorLinkXRD {
/// The kind of relation established by the subject with the attached resource.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.1>
///
#[serde(rename = "@rel")]
pub rel: String,
/// The media type of the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
///
#[serde(rename = "@type")]
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<MediaTypeBuf>,
/// URI to the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.3>
///
#[serde(rename = "@href")]
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
/// Titles of the resource put in relation in various languages.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
///
#[serde(default)]
#[serde(rename = "Title")]
pub titles: Vec<ResourceDescriptorTitleXRD>,
/// Additional information about the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.5>
///
#[serde(default)]
#[serde(rename = "Property")]
pub properties: Vec<ResourceDescriptorPropertyXRD>,
/// Template to fill to get the URL to resource-specific information.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-4.2>
///
#[serde(rename = "@template")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
}
/// A title of the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Title")]
pub struct ResourceDescriptorTitleXRD {
/// The language of the title.
#[serde(rename = "@lang")]
pub language: String,
/// The title itself.
#[serde(rename = "$text")]
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Property")]
pub struct ResourceDescriptorPropertyXRD {
/// The property identifier, or type.
#[serde(rename = "@rel")]
pub rel: String,
/// The property value.
#[serde(rename = "$text")]
pub value: Option<String>,
}
impl ResourceDescriptorXRD {
/// Get a [`ResourceDescriptorXRD`] from an URL.
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_rd::xrd::ResourceDescriptorXRD;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptorXRD::get(&client, url)
/// .await
/// .expect("XRD to be processed correctly");
/// # })
/// ```
///
pub async fn get(client: &reqwest::Client, url: reqwest::Url) -> Result<Self, GetXRDError> {
use GetXRDError::*;
log::debug!("Getting host-meta XRD document at: {url}");
log::trace!("Building request...");
let request = {
log::trace!("Creating new request...");
let mut request = reqwest::Request::new(reqwest::Method::GET, url);
log::trace!("Setting request headers...");
let headers = request.headers_mut();
log::trace!("Setting `Accept: application/xrd+xml`...");
let _ = headers.insert(reqwest::header::ACCEPT, "application/xrd+xml".parse().unwrap());
request
};
log::trace!("Sending request...");
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.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!("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:?}");
if !mime_is_xrd {
log::error!("MIME type `{media_type}` is not acceptable for XRD parsing.");
return Err(ContentTypeUnsupported);
}
log::trace!("Attempting to parse response as text...");
let data = response.text()
.await
.map_err(Decode)?;
log::trace!("Parsing response as XML...");
let data = quick_xml::de::from_str::<Self>(&data)
.map_err(Parse)?;
Ok(data)
}
}
impl From<ResourceDescriptorJRD> for ResourceDescriptorXRD {
fn from(value: ResourceDescriptorJRD) -> Self {
Self {
subject: value.subject,
aliases: value.aliases,
properties: value.properties.into_iter()
.map(From::from)
.collect(),
links: value.links.into_iter()
.map(From::from)
.collect(),
}
}
}
impl From<(String, Option<String>)> for ResourceDescriptorPropertyXRD {
fn from(value: (String, Option<String>)) -> Self {
Self {
rel: value.0,
value: value.1,
}
}
}
impl From<ResourceDescriptorLinkJRD> for ResourceDescriptorLinkXRD {
fn from(value: ResourceDescriptorLinkJRD) -> Self {
Self {
rel: value.rel,
r#type: value.r#type,
href: value.href,
titles: value.titles.into_iter()
.map(From::from)
.collect(),
properties: value.properties.into_iter()
.map(From::from)
.collect(),
template: value.template,
}
}
}
impl From<(String, String)> for ResourceDescriptorTitleXRD {
fn from(value: (String, String)) -> Self {
Self {
language: value.0,
value: value.1,
}
}
}
/// Error occurred during [`ResourceDescriptor::get_xrd`].
#[derive(Debug, Error)]
pub enum GetXRDError {
/// The HTTP request failed.
#[error("the HTTP request failed")]
Request(reqwest::Error),
/// The `Content-Type` header of the response is missing.
#[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 document failed to be decoded as text.
#[error("the document failed to be decoded as text")]
Decode(reqwest::Error),
/// The document failed to be parsed as XML by [`quick_xml`].
#[error("the document failed to be parsed as XML")]
Parse(quick_xml::DeError),
}

View file

@ -1,116 +0,0 @@
const CARGO_PKG_NAME: &str = env!("CARGO_PKG_NAME");
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const CARGO_PKG_REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
fn init_log() {
let mut builder = pretty_env_logger::formatted_builder();
builder.target(pretty_env_logger::env_logger::Target::Stdout);
builder.filter_level(log::LevelFilter::max());
builder.is_test(true);
if builder.try_init().is_ok() {
log::debug!("Initialized logging!");
}
}
fn make_client() -> reqwest::Client {
let user_agent = format!("{CARGO_PKG_NAME}/{CARGO_PKG_VERSION} ({CARGO_PKG_REPOSITORY})");
reqwest::Client::builder()
.user_agent(user_agent)
.build()
.expect("reqwest client to build")
}
macro_rules! test_discover_hostmeta {
($id:ident, $url:literal) => {
test_discover_hostmeta!($id, $url,);
};
($id:ident, $url:literal, $($tag:meta),*) => {
#[tokio::test]
$(#[$tag])*
async fn $id() {
init_log();
let client = make_client();
let base: reqwest::Url = $url.parse()
.expect("a valid URL");
let doc = acrate_rd::any::ResourceDescriptor::discover_hostmeta(&client, base)
.await
.expect("host-meta discovery to succeed");
log::info!("Parsed host-meta document: {doc:#?}");
}
};
}
macro_rules! test_de_ser_jrd {
($id:ident, $file:literal) => {
test_de_ser_jrd!($id, $file,);
};
($id:ident, $file:literal, $($tag:meta),*) => {
const JRD_DOCUMENT: &'static str = include_str!($file);
#[test]
$(#[$tag])*
fn $id() {
init_log();
log::info!("Starting document: {:#?}", JRD_DOCUMENT);
let de: acrate_rd::jrd::ResourceDescriptorJRD = serde_json::from_str(JRD_DOCUMENT)
.expect("document to be deserialized successfully");
log::info!("Serialized document: {de:#?}");
let ser = serde_json::to_string(&de)
.expect("document to be serialized successfully");
log::info!("Deserialized document: {ser:#?}");
}
};
}
macro_rules! test_de_ser_xrd {
($id:ident, $file:literal) => {
test_de_ser_xrd!($id, $file,);
};
($id:ident, $file:literal, $($tag:meta),*) => {
const XRD_DOCUMENT: &'static str = include_str!($file);
#[test]
$(#[$tag])*
fn $id() {
init_log();
log::info!("Starting document: {:#?}", XRD_DOCUMENT);
let de: acrate_rd::xrd::ResourceDescriptorXRD = quick_xml::de::from_str(XRD_DOCUMENT)
.expect("document to be deserialized successfully");
log::info!("Serialized document: {de:#?}");
let ser = quick_xml::se::to_string(&de)
.expect("document to be serialized successfully");
log::info!("Deserialized document: {ser:#?}");
}
};
}
test_discover_hostmeta!(test_discover_hostmeta_junimo_party, "https://junimo.party");
test_discover_hostmeta!(test_discover_hostmeta_mastodon_social, "https://mastodon.social");
test_discover_hostmeta!(test_discover_hostmeta_misskey_io, "https://misskey.io");
test_discover_hostmeta!(test_discover_hostmeta_ice_frieren_quest, "https://ice.frieren.quest");
test_discover_hostmeta!(test_discover_hostmeta_alpha_polymaths_social, "https://alpha.polymaths.social");
test_discover_hostmeta!(test_discover_hostmeta_fed_brid_gy, "https://fed.brid.gy");
test_discover_hostmeta!(test_discover_hostmeta_threads_net, "https://threads.net", ignore = "does not support host-meta");
test_discover_hostmeta!(test_discover_hostmeta_ngoa_giao_loan, "https://ngoa.giao.loan", ignore = "does not support host-meta");
test_discover_hostmeta!(test_discover_hostmeta_hollo_social, "https://hollo.social", ignore = "does not support host-meta");
test_de_ser_jrd!(test_de_ser_jrd_sample_junimo_party, "samples/junimo_party.nodeinfo.jrd.json");
test_de_ser_xrd!(test_de_ser_xrd_sample_junimo_party, "samples/junimo_party.host-meta.xrd.xml");

View file

@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><Link type="application/xrd+xml" template="https://junimo.party/.well-known/webfinger?resource={uri}" rel="lrdd" /></XRD>

View file

@ -1,12 +0,0 @@
{
"links": [
{
"rel": "http://nodeinfo.diaspora.software/ns/schema/2.0",
"href": "https://junimo.party/nodeinfo/2.0.json"
},
{
"rel": "http://nodeinfo.diaspora.software/ns/schema/2.1",
"href": "https://junimo.party/nodeinfo/2.1.json"
}
]
}

View file

@ -1,29 +0,0 @@
[package]
name = "acrate_rdserver"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
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" }
anyhow = "1.0.93"
axum = { version = "0.7.7", features = ["macros"] }
axum-extra = { version = "0.9.4", features = ["query"] }
log = "0.4.22"
micronfig = "0.3.0"
minijinja = "2.5.0"
pretty_env_logger = "0.5.0"
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"

View file

@ -1,4 +0,0 @@
micronfig::config!(
ACRATE_WEBFINGER_DATABASE_URL: String,
ACRATE_WEBFINGER_BIND_ADDRESS: String,
);

View file

@ -1,192 +0,0 @@
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>{{ subject }} · Acrate RDServer</title>
<style>
:root {
--wf-yellow: #e2bb03;
--wf-brown: #3b351d;
--link-color: #0094b9;
}
body {
font-family: sans-serif;
}
h1, h2 {
text-align: center;
}
main {
max-width: 800px;
padding: 8px;
margin: 0 auto;
border: 2px solid currentColor;
border-radius: 8px;
}
a {
color: var(--link-color);
}
hr {
margin: 8px -8px;
border: 1px solid currentColor;
opacity: 1;
}
small span {
font-family: monospace;
}
@media screen {
main {
box-shadow: 4px 4px 10px currentColor;
}
}
@media screen and (prefers-color-scheme: dark) {
body {
background-color: black;
color: var(--wf-yellow);
}
main {
background-color: var(--wf-brown);
}
main, hr {
border-color: var(--wf-yellow);
}
}
@media screen and (prefers-color-scheme: light) {
body {
background-color: var(--wf-yellow);
color: var(--wf-brown);
}
main {
background-color: white;
}
main, hr {
border-color: var(--wf-brown);
}
}
</style>
</head>
<body>
<header>
<h1>
<span id="path">{{ path }}</span>
</h1>
</header>
<main>
<h2 id="section-subject">
<span id="subject">{{ subject }}</span>
</h2>
{% if aliases %}
<hr>
<section id="section-aliases">
<h3>
Aliases
</h3>
<ul>
{% for alias in aliases %}
<li><a href="{{ alias }}">{{ alias }}</a></li>
{% endfor %}
</ul>
</section>
{% endif %}
{% if properties %}
<hr>
<section id="section-properties">
<h3>
Properties
</h3>
<dl>
{% for property in properties %}
<dt>
<a href="{{ property[0] }}">{{ property[0] }}</a>
</dt>
<dd>
<span>{{ property[1] }}</span>
</dd>
{% endfor %}
</dl>
</section>
{% endif %}
{% if links %}
<hr>
<section id="section-links">
<h3>
Links
</h3>
<dl>
{% for link in links %}
<dt>
<h4>
{% if link[0] != "self" %}
<a href="{{ link[0] }}">{{ link[0] }}</a>
{% else %}
<span>{{ link[0] }}</span>
{% endif %}
{% if link[1] is not none %}
<small>
(<span>{{ link[1] }}</span>)
</small>
{% endif %}
</h4>
</dt>
<dd>
{% if link[2] is not none %}
<h5>
Link destination
</h5>
<a href="{{ link[2] }}">{{ link[2] }}</a>
{% endif %}
{% if link[3] is not none %}
<h5>
Link template
</h5>
<span>{{ link[3] }}</span>
{% endif %}
{% if link[4] %}
<h5>
Link properties
</h5>
<dl>
{% for property in link[4] %}
<dt>
<a href="{{ property[0] }}">{{ property[0] }}</a>
</dt>
<dd>
<span>{{ property[1] }}</span>
</dd>
{% endfor %}
</dl>
{% endif %}
{% if link[5] %}
<h5>
Link titles
</h5>
<dl>
{% for title in link[5] %}
<dt>
<span>{{ title[0] }}</span>
</dt>
<dd>
<span>{{ title[1] }}</span>
</dd>
{% endfor %}
</dl>
{% endif %}
</dd>
{% endfor %}
</dl>
</section>
{% endif %}
</main>
</body>

View file

@ -1,298 +0,0 @@
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 crate::config;
#[derive(Debug, Clone, Deserialize)]
pub struct WebfingerQuery {
pub resource: Option<String>,
#[serde(default)]
pub rel: Vec<String>,
}
pub async fn webfinger_handler(
Path(path): Path<String>,
Query(WebfingerQuery {resource, rel}): Query<WebfingerQuery>,
headers: HeaderMap,
Extension(mj): Extension<Arc<minijinja::Environment<'static>>>,
) -> Result<Response<String>, StatusCode> {
log::info!("Handling a WebFinger request!");
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");
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());
let mut conn = AsyncPgConnection::establish(config::ACRATE_WEBFINGER_DATABASE_URL())
.await
.map_err(|_| StatusCode::BAD_GATEWAY)?;
let subjects = MetaSubject::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let subject = subjects.first()
.ok_or(StatusCode::NOT_FOUND)?;
if subject.redirect.is_some() {
{
let headers = response.headers_mut();
headers.insert(
"Location",
subject.redirect
.as_ref()
.expect("redirect not to have become suddenly None")
.parse()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
);
}
{
let status = response.status_mut();
*status = StatusCode::FOUND;
}
return Ok(response);
}
let subject = subject.subject.clone();
let aliases = MetaAlias::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let properties = MetaProperty::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let links = MetaLink::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let link_properties = MetaLinkProperty::aquery_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)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.grouped_by(&links);
let links_full: Vec<(MetaLink, Vec<MetaLinkProperty>, Vec<MetaLinkTitle>)> = links
.into_iter()
.zip(link_properties)
.zip(link_titles)
.map(|((link, properties), titles)| (link, properties, titles))
.collect();
{
let headers = response.headers_mut();
headers.insert(
"Access-Control-Allow-Origin",
"*".parse().unwrap()
);
}
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
};
{
let headers = response.headers_mut();
headers.insert(
"Content-Type",
media_type.to_string()
.parse()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
);
}
match media_type.essence().to_string().to_ascii_lowercase().as_str() {
"*/*" | "application/json" | "application/jrd+json" => {
let aliases = aliases
.into_iter()
.map(|alias| alias.alias)
.collect();
let properties = properties
.into_iter()
.map(|prop| (prop.rel, prop.value))
.collect();
let links = links_full
.into_iter()
.map(|(link, properties, titles)| ResourceDescriptorLinkJRD {
rel: link.rel,
r#type: link.type_.map(|m| m.0),
href: link.href,
template: link.template,
properties: properties
.into_iter()
.map(|property| (property.rel, property.value))
.collect(),
titles: titles
.into_iter()
.map(|title| (title.language, title.value))
.collect(),
})
.collect::<Vec<ResourceDescriptorLinkJRD>>();
let rd = acrate_rd::jrd::ResourceDescriptorJRD {
subject,
aliases,
properties,
links,
};
let json = serde_json::to_string_pretty(&rd)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
{
let body = response.body_mut();
body.push_str(&json);
}
return Ok(response);
},
"application/xml" | "application/xrd+xml" => {
let aliases = aliases
.into_iter()
.map(|alias| alias.alias)
.collect();
let properties: Vec<ResourceDescriptorPropertyXRD> = properties
.into_iter()
.map(|prop| ResourceDescriptorPropertyXRD {
rel: prop.rel,
value: prop.value,
})
.collect();
let links = links_full
.into_iter()
.map(|(link, properties, titles)| ResourceDescriptorLinkXRD {
rel: link.rel,
r#type: link.type_.map(|m| m.0),
href: link.href,
template: link.template,
properties: properties
.into_iter()
.map(|property| ResourceDescriptorPropertyXRD {
rel: property.rel,
value: property.value,
})
.collect(),
titles: titles
.into_iter()
.map(|title| ResourceDescriptorTitleXRD {
language: title.language,
value: title.value,
})
.collect(),
})
.collect::<Vec<ResourceDescriptorLinkXRD>>();
let rd = acrate_rd::xrd::ResourceDescriptorXRD {
subject,
aliases,
properties,
links,
};
let xml = quick_xml::se::to_string(&rd)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
{
let body = response.body_mut();
body.push_str(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
body.push_str(&xml);
}
return Ok(response);
},
"text/html" => {
let aliases: Vec<String> = aliases.into_iter()
.map(|alias| alias.alias)
.collect();
let properties: Vec<(String, Option<String>)> = properties.into_iter()
.map(|prop| {
(prop.rel, prop.value)
})
.collect();
let links: Vec<(String, Option<MediaTypeBuf>, 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.href,
link.template,
properties.into_iter()
.map(|prop| (prop.rel, prop.value))
.collect::<Vec<(String, Option<String>)>>(),
titles.into_iter()
.map(|title| (title.language, title.value))
.collect::<Vec<(String, String)>>()
)
})
.collect();
let html = mj.get_template("rd.html.j2")
.expect("rd.html.j2 to exist")
.render(
minijinja::context!(
path => path,
subject => subject,
aliases => aliases,
properties => properties,
links => links,
)
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
{
let body = response.body_mut();
body.push_str(&html);
}
return Ok(response);
},
_ => {
continue;
},
}
}
Err(StatusCode::NOT_ACCEPTABLE)
}