2023-03-01 23:19:10 +00:00
|
|
|
use crate::{
|
2023-03-16 01:11:48 +00:00
|
|
|
config::Data,
|
2023-12-11 21:48:32 +00:00
|
|
|
error::Error,
|
2023-07-18 20:17:21 +00:00
|
|
|
fetch::{fetch_object_http_with_accept, object_id::ObjectId},
|
2023-03-16 20:41:29 +00:00
|
|
|
traits::{Actor, Object},
|
|
|
|
FEDERATION_CONTENT_TYPE,
|
2023-03-01 23:19:10 +00:00
|
|
|
};
|
2024-03-04 11:47:42 +00:00
|
|
|
use http::HeaderValue;
|
2023-03-01 23:19:10 +00:00
|
|
|
use itertools::Itertools;
|
2023-12-11 21:48:32 +00:00
|
|
|
use once_cell::sync::Lazy;
|
2023-03-01 23:19:10 +00:00
|
|
|
use regex::Regex;
|
|
|
|
use serde::{Deserialize, Serialize};
|
2023-12-11 21:48:32 +00:00
|
|
|
use std::{collections::HashMap, fmt::Display};
|
2023-03-01 23:19:10 +00:00
|
|
|
use tracing::debug;
|
|
|
|
use url::Url;
|
|
|
|
|
2023-12-11 21:48:32 +00:00
|
|
|
/// Errors relative to webfinger handling
|
|
|
|
#[derive(thiserror::Error, Debug)]
|
|
|
|
pub enum WebFingerError {
|
|
|
|
/// The webfinger identifier is invalid
|
|
|
|
#[error("The webfinger identifier is invalid")]
|
|
|
|
WrongFormat,
|
|
|
|
/// The webfinger identifier doesn't match the expected instance domain name
|
|
|
|
#[error("The webfinger identifier doesn't match the expected instance domain name")]
|
|
|
|
WrongDomain,
|
|
|
|
/// The wefinger object did not contain any link to an activitypub item
|
|
|
|
#[error("The webfinger object did not contain any link to an activitypub item")]
|
|
|
|
NoValidLink,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WebFingerError {
|
|
|
|
fn into_crate_error(self) -> Error {
|
|
|
|
self.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-04 11:47:42 +00:00
|
|
|
/// The content-type for webfinger responses.
|
|
|
|
pub static WEBFINGER_CONTENT_TYPE: HeaderValue = HeaderValue::from_static("application/jrd+json");
|
|
|
|
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Takes an identifier of the form `name@example.com`, and returns an object of `Kind`.
|
|
|
|
///
|
|
|
|
/// For this the identifier is first resolved via webfinger protocol to an Activitypub ID. This ID
|
|
|
|
/// is then fetched using [ObjectId::dereference], and the result returned.
|
2023-03-01 23:19:10 +00:00
|
|
|
pub async fn webfinger_resolve_actor<T: Clone, Kind>(
|
|
|
|
identifier: &str,
|
2023-03-16 01:11:48 +00:00
|
|
|
data: &Data<T>,
|
2023-03-16 20:41:29 +00:00
|
|
|
) -> Result<Kind, <Kind as Object>::Error>
|
2023-03-01 23:19:10 +00:00
|
|
|
where
|
2023-03-16 20:41:29 +00:00
|
|
|
Kind: Object + Actor + Send + 'static + Object<DataType = T>,
|
|
|
|
for<'de2> <Kind as Object>::Kind: serde::Deserialize<'de2>,
|
2023-12-11 21:48:32 +00:00
|
|
|
<Kind as Object>::Error: From<crate::error::Error> + Send + Sync + Display,
|
2023-03-01 23:19:10 +00:00
|
|
|
{
|
|
|
|
let (_, domain) = identifier
|
|
|
|
.splitn(2, '@')
|
|
|
|
.collect_tuple()
|
2023-12-11 21:48:32 +00:00
|
|
|
.ok_or(WebFingerError::WrongFormat.into_crate_error())?;
|
2023-03-01 23:19:10 +00:00
|
|
|
let protocol = if data.config.debug { "http" } else { "https" };
|
|
|
|
let fetch_url =
|
|
|
|
format!("{protocol}://{domain}/.well-known/webfinger?resource=acct:{identifier}");
|
|
|
|
debug!("Fetching webfinger url: {}", &fetch_url);
|
|
|
|
|
2023-11-20 10:42:47 +00:00
|
|
|
let res: Webfinger = fetch_object_http_with_accept(
|
|
|
|
&Url::parse(&fetch_url).map_err(Error::UrlParse)?,
|
|
|
|
data,
|
2024-03-04 11:47:42 +00:00
|
|
|
&WEBFINGER_CONTENT_TYPE,
|
2023-11-20 10:42:47 +00:00
|
|
|
)
|
|
|
|
.await?
|
|
|
|
.object;
|
2023-03-01 23:19:10 +00:00
|
|
|
|
2023-03-02 14:18:06 +00:00
|
|
|
debug_assert_eq!(res.subject, format!("acct:{identifier}"));
|
2023-03-01 23:19:10 +00:00
|
|
|
let links: Vec<Url> = res
|
|
|
|
.links
|
|
|
|
.iter()
|
|
|
|
.filter(|link| {
|
|
|
|
if let Some(type_) = &link.kind {
|
|
|
|
type_.starts_with("application/")
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.filter_map(|l| l.href.clone())
|
|
|
|
.collect();
|
2023-12-11 21:48:32 +00:00
|
|
|
|
2023-03-01 23:19:10 +00:00
|
|
|
for l in links {
|
|
|
|
let object = ObjectId::<Kind>::from(l).dereference(data).await;
|
2023-12-11 21:48:32 +00:00
|
|
|
match object {
|
|
|
|
Ok(obj) => return Ok(obj),
|
|
|
|
Err(error) => debug!(%error, "Failed to dereference link"),
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
|
|
|
}
|
2023-12-11 21:48:32 +00:00
|
|
|
Err(WebFingerError::NoValidLink.into_crate_error().into())
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Extracts username from a webfinger resource parameter.
|
|
|
|
///
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Use this method for your HTTP handler at `.well-known/webfinger` to handle incoming webfinger
|
|
|
|
/// request. For a parameter of the form `acct:gargron@mastodon.social` it returns `gargron`.
|
2023-03-01 23:19:10 +00:00
|
|
|
///
|
|
|
|
/// Returns an error if query doesn't match local domain.
|
2023-07-03 13:05:18 +00:00
|
|
|
///
|
|
|
|
///```
|
|
|
|
/// # use activitypub_federation::config::FederationConfig;
|
|
|
|
/// # use activitypub_federation::traits::tests::DbConnection;
|
|
|
|
/// # use activitypub_federation::fetch::webfinger::extract_webfinger_name;
|
|
|
|
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
|
|
|
|
/// # let db_connection = DbConnection;
|
|
|
|
/// let config = FederationConfig::builder()
|
|
|
|
/// .domain("example.com")
|
|
|
|
/// .app_data(db_connection)
|
|
|
|
/// .build()
|
|
|
|
/// .await
|
|
|
|
/// .unwrap();
|
|
|
|
/// let data = config.to_request_data();
|
|
|
|
/// let res = extract_webfinger_name("acct:test_user@example.com", &data).unwrap();
|
|
|
|
/// assert_eq!(res, "test_user");
|
|
|
|
/// # Ok::<(), anyhow::Error>(())
|
|
|
|
/// }).unwrap();
|
|
|
|
///```
|
2023-12-11 21:48:32 +00:00
|
|
|
pub fn extract_webfinger_name<'i, T>(query: &'i str, data: &Data<T>) -> Result<&'i str, Error>
|
2023-03-01 23:19:10 +00:00
|
|
|
where
|
|
|
|
T: Clone,
|
|
|
|
{
|
2023-12-11 21:48:32 +00:00
|
|
|
static WEBFINGER_REGEX: Lazy<Regex> =
|
|
|
|
Lazy::new(|| Regex::new(r"^acct:([\p{L}0-9_]+)@(.*)$").expect("compile regex"));
|
2023-10-24 09:08:55 +00:00
|
|
|
// Regex to extract usernames from webfinger query. Supports different alphabets using `\p{L}`.
|
2023-12-11 21:48:32 +00:00
|
|
|
// TODO: This should use a URL parser
|
|
|
|
let captures = WEBFINGER_REGEX
|
|
|
|
.captures(query)
|
|
|
|
.ok_or(WebFingerError::WrongFormat)?;
|
2023-11-20 10:42:47 +00:00
|
|
|
|
2023-12-11 21:48:32 +00:00
|
|
|
let account_name = captures.get(1).ok_or(WebFingerError::WrongFormat)?;
|
|
|
|
|
|
|
|
if captures.get(2).map(|m| m.as_str()) != Some(data.domain()) {
|
|
|
|
return Err(WebFingerError::WrongDomain.into());
|
|
|
|
}
|
|
|
|
Ok(account_name.as_str())
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
|
|
|
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Builds a basic webfinger response for the actor.
|
|
|
|
///
|
|
|
|
/// It assumes that the given URL is valid both to the view the actor in a browser as HTML, and
|
|
|
|
/// for fetching it over Activitypub with `activity+json`. This setup is commonly used for ease
|
|
|
|
/// of discovery.
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use url::Url;
|
2023-03-06 01:17:34 +00:00
|
|
|
/// # use activitypub_federation::fetch::webfinger::build_webfinger_response;
|
2023-03-02 14:18:06 +00:00
|
|
|
/// let subject = "acct:nutomic@lemmy.ml".to_string();
|
|
|
|
/// let url = Url::parse("https://lemmy.ml/u/nutomic")?;
|
|
|
|
/// build_webfinger_response(subject, url);
|
|
|
|
/// # Ok::<(), anyhow::Error>(())
|
|
|
|
/// ```
|
|
|
|
pub fn build_webfinger_response(subject: String, url: Url) -> Webfinger {
|
2023-04-04 19:56:34 +00:00
|
|
|
build_webfinger_response_with_type(subject, vec![(url, None)])
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Builds a webfinger response similar to `build_webfinger_response`. Use this when you want to
|
|
|
|
/// return multiple actors who share the same namespace and to specify the type of the actor.
|
|
|
|
///
|
|
|
|
/// `urls` takes a vector of tuples. The first item of the tuple is the URL while the second
|
|
|
|
/// item is the type, such as `"Person"` or `"Group"`. If `None` is passed for the type, the field
|
|
|
|
/// will be empty.
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use url::Url;
|
|
|
|
/// # use activitypub_federation::fetch::webfinger::build_webfinger_response_with_type;
|
|
|
|
/// let subject = "acct:nutomic@lemmy.ml".to_string();
|
|
|
|
/// let user = Url::parse("https://lemmy.ml/u/nutomic")?;
|
|
|
|
/// let group = Url::parse("https://lemmy.ml/c/asklemmy")?;
|
|
|
|
/// build_webfinger_response_with_type(subject, vec![
|
|
|
|
/// (user, Some("Person")),
|
|
|
|
/// (group, Some("Group"))]);
|
|
|
|
/// # Ok::<(), anyhow::Error>(())
|
|
|
|
/// ```
|
|
|
|
pub fn build_webfinger_response_with_type(
|
|
|
|
subject: String,
|
|
|
|
urls: Vec<(Url, Option<&str>)>,
|
|
|
|
) -> Webfinger {
|
2023-03-01 23:19:10 +00:00
|
|
|
Webfinger {
|
2023-03-02 14:18:06 +00:00
|
|
|
subject,
|
2023-04-04 19:56:34 +00:00
|
|
|
links: urls.iter().fold(vec![], |mut acc, (url, kind)| {
|
|
|
|
let properties: HashMap<Url, String> = kind
|
|
|
|
.map(|kind| {
|
|
|
|
HashMap::from([(
|
|
|
|
"https://www.w3.org/ns/activitystreams#type"
|
|
|
|
.parse()
|
|
|
|
.expect("parse url"),
|
|
|
|
kind.to_string(),
|
|
|
|
)])
|
|
|
|
})
|
|
|
|
.unwrap_or_default();
|
|
|
|
let mut links = vec![
|
|
|
|
WebfingerLink {
|
|
|
|
rel: Some("http://webfinger.net/rel/profile-page".to_string()),
|
|
|
|
kind: Some("text/html".to_string()),
|
|
|
|
href: Some(url.clone()),
|
2023-08-31 11:42:58 +00:00
|
|
|
..Default::default()
|
2023-04-04 19:56:34 +00:00
|
|
|
},
|
|
|
|
WebfingerLink {
|
|
|
|
rel: Some("self".to_string()),
|
|
|
|
kind: Some(FEDERATION_CONTENT_TYPE.to_string()),
|
|
|
|
href: Some(url.clone()),
|
|
|
|
properties,
|
2023-08-31 11:42:58 +00:00
|
|
|
..Default::default()
|
2023-04-04 19:56:34 +00:00
|
|
|
},
|
|
|
|
];
|
|
|
|
acc.append(&mut links);
|
|
|
|
acc
|
|
|
|
}),
|
2023-03-02 14:18:06 +00:00
|
|
|
aliases: vec![],
|
|
|
|
properties: Default::default(),
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-02 14:18:06 +00:00
|
|
|
/// A webfinger response with information about a `Person` or other type of actor.
|
2023-03-16 01:11:48 +00:00
|
|
|
#[derive(Serialize, Deserialize, Debug, Default)]
|
2023-03-01 23:19:10 +00:00
|
|
|
pub struct Webfinger {
|
2023-03-02 14:18:06 +00:00
|
|
|
/// The actor which is described here, for example `acct:LemmyDev@mastodon.social`
|
2023-03-01 23:19:10 +00:00
|
|
|
pub subject: String,
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Links where further data about `subject` can be retrieved
|
2023-03-01 23:19:10 +00:00
|
|
|
pub links: Vec<WebfingerLink>,
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Other Urls which identify the same actor as the `subject`
|
2023-03-07 22:01:36 +00:00
|
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
2023-03-02 14:18:06 +00:00
|
|
|
pub aliases: Vec<Url>,
|
|
|
|
/// Additional data about the subject
|
2023-03-07 22:01:36 +00:00
|
|
|
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
2023-03-02 14:18:06 +00:00
|
|
|
pub properties: HashMap<Url, String>,
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
|
|
|
|
2023-03-02 14:18:06 +00:00
|
|
|
/// A single link included as part of a [Webfinger] response.
|
2023-03-16 01:11:48 +00:00
|
|
|
#[derive(Serialize, Deserialize, Debug, Default)]
|
2023-03-01 23:19:10 +00:00
|
|
|
pub struct WebfingerLink {
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Relationship of the link, such as `self` or `http://webfinger.net/rel/profile-page`
|
2023-03-01 23:19:10 +00:00
|
|
|
pub rel: Option<String>,
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Media type of the target resource
|
2023-03-01 23:19:10 +00:00
|
|
|
#[serde(rename = "type")]
|
|
|
|
pub kind: Option<String>,
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Url pointing to the target resource
|
2023-03-01 23:19:10 +00:00
|
|
|
pub href: Option<Url>,
|
2023-08-31 11:42:58 +00:00
|
|
|
/// Used for remote follow external interaction url
|
|
|
|
pub template: Option<String>,
|
2023-03-02 14:18:06 +00:00
|
|
|
/// Additional data about the link
|
2023-03-07 22:01:36 +00:00
|
|
|
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
2023-03-02 14:18:06 +00:00
|
|
|
pub properties: HashMap<Url, String>,
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use crate::{
|
|
|
|
config::FederationConfig,
|
|
|
|
traits::tests::{DbConnection, DbUser},
|
|
|
|
};
|
|
|
|
|
2023-06-20 09:54:14 +00:00
|
|
|
#[tokio::test]
|
2023-07-26 14:17:39 +00:00
|
|
|
async fn test_webfinger() -> Result<(), Error> {
|
2023-03-01 23:19:10 +00:00
|
|
|
let config = FederationConfig::builder()
|
|
|
|
.domain("example.com")
|
|
|
|
.app_data(DbConnection)
|
|
|
|
.build()
|
2023-06-20 09:54:14 +00:00
|
|
|
.await
|
2023-03-01 23:19:10 +00:00
|
|
|
.unwrap();
|
|
|
|
let data = config.to_request_data();
|
2023-07-26 14:17:39 +00:00
|
|
|
|
|
|
|
webfinger_resolve_actor::<DbConnection, DbUser>("LemmyDev@mastodon.social", &data).await?;
|
2023-07-18 20:17:21 +00:00
|
|
|
// poa.st is as of 2023-07-14 the largest Pleroma instance
|
2023-07-26 14:17:39 +00:00
|
|
|
webfinger_resolve_actor::<DbConnection, DbUser>("graf@poa.st", &data).await?;
|
|
|
|
Ok(())
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|
2023-10-24 09:08:55 +00:00
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_webfinger_extract_name() -> Result<(), Error> {
|
|
|
|
use crate::traits::tests::DbConnection;
|
|
|
|
let data = Data {
|
|
|
|
config: FederationConfig::builder()
|
|
|
|
.domain("example.com")
|
|
|
|
.app_data(DbConnection)
|
|
|
|
.build()
|
|
|
|
.await
|
|
|
|
.unwrap(),
|
|
|
|
request_counter: Default::default(),
|
|
|
|
};
|
|
|
|
assert_eq!(
|
2023-12-11 21:48:32 +00:00
|
|
|
Ok("test123"),
|
2023-10-24 09:08:55 +00:00
|
|
|
extract_webfinger_name("acct:test123@example.com", &data)
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2023-12-11 21:48:32 +00:00
|
|
|
Ok("Владимир"),
|
2023-10-24 09:08:55 +00:00
|
|
|
extract_webfinger_name("acct:Владимир@example.com", &data)
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2023-12-11 21:48:32 +00:00
|
|
|
Ok("تجريب"),
|
2023-10-24 09:08:55 +00:00
|
|
|
extract_webfinger_name("acct:تجريب@example.com", &data)
|
|
|
|
);
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|