2023-03-01 23:19:10 +00:00
|
|
|
use crate::{
|
2023-03-16 01:11:48 +00:00
|
|
|
config::Data,
|
2023-03-01 23:19:10 +00:00
|
|
|
error::{Error, Error::WebfingerResolveFailed},
|
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
|
|
|
};
|
|
|
|
use itertools::Itertools;
|
|
|
|
use regex::Regex;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use tracing::debug;
|
|
|
|
use url::Url;
|
|
|
|
|
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-11-20 10:42:47 +00:00
|
|
|
<Kind as Object>::Error: From<crate::error::Error> + Send + Sync,
|
2023-03-01 23:19:10 +00:00
|
|
|
{
|
|
|
|
let (_, domain) = identifier
|
|
|
|
.splitn(2, '@')
|
|
|
|
.collect_tuple()
|
2023-03-02 14:18:06 +00:00
|
|
|
.ok_or(WebfingerResolveFailed)?;
|
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,
|
|
|
|
"application/jrd+json",
|
|
|
|
)
|
|
|
|
.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();
|
|
|
|
for l in links {
|
|
|
|
let object = ObjectId::<Kind>::from(l).dereference(data).await;
|
|
|
|
if object.is_ok() {
|
|
|
|
return object;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(WebfingerResolveFailed.into())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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-03-16 01:11:48 +00:00
|
|
|
pub fn extract_webfinger_name<T>(query: &str, data: &Data<T>) -> Result<String, Error>
|
2023-03-01 23:19:10 +00:00
|
|
|
where
|
|
|
|
T: Clone,
|
|
|
|
{
|
2023-10-24 09:08:55 +00:00
|
|
|
// Regex to extract usernames from webfinger query. Supports different alphabets using `\p{L}`.
|
2023-03-01 23:19:10 +00:00
|
|
|
// TODO: would be nice if we could implement this without regex and remove the dependency
|
2023-11-20 10:42:47 +00:00
|
|
|
let result = Regex::new(&format!(r"^acct:([\p{{L}}0-9_]+)@{}$", data.domain()))
|
|
|
|
.map_err(|_| Error::WebfingerRegexFailed)
|
|
|
|
.and_then(|regex| {
|
|
|
|
regex
|
|
|
|
.captures(query)
|
|
|
|
.and_then(|c| c.get(1))
|
|
|
|
.ok_or_else(|| Error::WebfingerRegexFailed)
|
|
|
|
})?;
|
|
|
|
|
|
|
|
return Ok(result.as_str().to_string());
|
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!(
|
|
|
|
Ok("test123".to_string()),
|
|
|
|
extract_webfinger_name("acct:test123@example.com", &data)
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
Ok("Владимир".to_string()),
|
|
|
|
extract_webfinger_name("acct:Владимир@example.com", &data)
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
Ok("تجريب".to_string()),
|
|
|
|
extract_webfinger_name("acct:تجريب@example.com", &data)
|
|
|
|
);
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-03-01 23:19:10 +00:00
|
|
|
}
|