1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//! Webfinger ([RFC 7033]) endpoint for discovering Actor objects by more human
//! readable handles ("username@server.domain").
//!
//! [RFC 7033]: https://www.rfc-editor.org/rfc/rfc7033

use crate::database::Database;
use crate::http_api::activity_json::{CT_ACTIVITY_JSON, CT_ACTIVITY_JSON_SHORT};
use crate::http_api::{actor_id, CanonicalServerUrl};
use actix_web::{get, web, HttpResponse};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Deserialize;
use serde_json::json;

/// Regex for extracting the user and host parts from an "acct:user@example.com"
/// string. Used to parse the `resource` query parameter in Webfinger requests.
static ACCT_PARSER: Lazy<Regex> = Lazy::new(|| Regex::new(r#"acct:@?(\w+)@(.+)"#).unwrap());

/// The query parameters of the Webfinger GET response.
#[derive(Deserialize)]
struct WebfingerParameters {
    resource: String,
}

/// The http responder for a GET, query parameters and response are formatted as
/// per the Webfinger spec.
///
/// The returned value's `links` array contains two links, both have the Actor's
/// id as the href and `"self"` as the rel, with the type fields set to
/// [CT_ACTIVITY_JSON] and [CT_ACTIVITY_JSON_SHORT]. Both versions of the link
/// are provided for wider client compatibility.
#[get("/.well-known/webfinger")]
async fn get(
    query: web::Query<WebfingerParameters>,
    db: web::Data<&'static Database>,
    server_url: web::Data<CanonicalServerUrl>,
) -> HttpResponse {
    let WebfingerParameters { resource } = query.0;
    if let Some(captures) = ACCT_PARSER.captures(&resource) {
        let user = captures.get(1).unwrap().as_str();
        let host = captures.get(2).unwrap().as_str();
        if host == server_url.host() {
            let id = actor_id(&server_url, user);
            match db.get_object(&id, None).await {
                Ok(Some(actor)) => {
                    let id = actor.id.unwrap();
                    let obj = json!({
                        "subject": format!("acct:{user}@{host}"),
                        "aliases": [id],
                        "links": [
                            {
                                "href": id,
                                "type": CT_ACTIVITY_JSON,
                                "rel": "self",
                            },
                            {
                                "href": id,
                                "type": CT_ACTIVITY_JSON_SHORT,
                                "rel": "self",
                            },
                        ],
                    });
                    HttpResponse::Ok().body(serde_json::to_string(&obj).unwrap())
                }
                Ok(None) => HttpResponse::NotFound().body(format!("No user called {user} found.")),
                Err(err) => {
                    tracing::error!("Failed to get actor for webfinger from db: {err}");
                    HttpResponse::ServiceUnavailable().finish()
                }
            }
        } else {
            HttpResponse::BadRequest().body("Wrong server.")
        }
    } else {
        HttpResponse::BadRequest().body("Couldn't parse the resource parameter.")
    }
}