Skip to main content

feder_runtime_server/
webfinger.rs

1// Feder: A portable ActivityPub core for many runtimes.
2// Copyright (C) 2026 Feder contributors
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU Affero General Public License as published by
6// the Free Software Foundation, version 3.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16use axum::{
17    Json,
18    extract::{Query, State},
19    http::{StatusCode, header},
20    response::{IntoResponse, Response},
21};
22use serde::{Deserialize, Serialize};
23
24use crate::app::AppState;
25
26#[derive(Deserialize)]
27pub struct WebFingerQuery {
28    resource: Option<String>,
29}
30
31#[derive(Serialize)]
32pub struct WebFingerResponse {
33    subject: String,
34    aliases: Vec<String>,
35    links: Vec<WebFingerLink>,
36}
37
38#[derive(Serialize)]
39pub struct WebFingerLink {
40    rel: &'static str,
41    #[serde(rename = "type")]
42    media_type: &'static str,
43    href: String,
44}
45
46pub async fn webfinger(
47    State(state): State<AppState>,
48    Query(query): Query<WebFingerQuery>,
49) -> Result<Response, StatusCode> {
50    let Some(resource) = query.resource else {
51        return Err(StatusCode::BAD_REQUEST);
52    };
53
54    let expected = format!("acct:{}@{}", state.username, state.handle_host);
55    if resource != expected {
56        return Err(StatusCode::NOT_FOUND);
57    }
58
59    let actor_id = state.local_actor.id.to_string();
60
61    Ok((
62        [(header::CONTENT_TYPE, "application/jrd+json")],
63        Json(WebFingerResponse {
64            subject: resource,
65            aliases: vec![actor_id.clone()],
66            links: vec![WebFingerLink {
67                rel: "self",
68                media_type: "application/activity+json",
69                href: actor_id,
70            }],
71        }),
72    )
73        .into_response())
74}
75
76#[cfg(test)]
77mod tests {
78    use axum::{
79        body::{Body, to_bytes},
80        http::{Request, StatusCode, header},
81    };
82    use serde_json::Value;
83    use tower::ServiceExt;
84
85    use crate::{app::build_router, config::RuntimeConfig};
86
87    const WEBFINGER_PATH: &str = "/.well-known/webfinger?resource=acct:alice@127.0.0.1:3000";
88
89    #[tokio::test]
90    async fn returns_webfinger_descriptor_for_local_actor() {
91        let app = build_router(&RuntimeConfig::default_local());
92
93        let response = app
94            .oneshot(
95                Request::builder()
96                    .uri(WEBFINGER_PATH)
97                    .body(Body::empty())
98                    .expect("valid request"),
99            )
100            .await
101            .expect("response");
102
103        assert_eq!(response.status(), StatusCode::OK);
104        assert_eq!(
105            response.headers().get(header::CONTENT_TYPE).unwrap(),
106            "application/jrd+json"
107        );
108
109        let body = to_bytes(response.into_body(), 1024)
110            .await
111            .expect("read response body");
112        let json: Value = serde_json::from_slice(&body).expect("valid json");
113
114        assert_eq!(json["subject"], "acct:alice@127.0.0.1:3000");
115        assert_eq!(json["aliases"][0], "http://127.0.0.1:3000/users/alice");
116        assert_eq!(json["links"][0]["rel"], "self");
117        assert_eq!(json["links"][0]["type"], "application/activity+json");
118        assert_eq!(
119            json["links"][0]["href"],
120            "http://127.0.0.1:3000/users/alice"
121        );
122    }
123
124    #[tokio::test]
125    async fn rejects_missing_resource() {
126        let app = build_router(&RuntimeConfig::default_local());
127
128        let response = app
129            .oneshot(
130                Request::builder()
131                    .uri("/.well-known/webfinger")
132                    .body(Body::empty())
133                    .expect("valid request"),
134            )
135            .await
136            .expect("response");
137
138        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
139    }
140
141    #[tokio::test]
142    async fn rejects_non_local_actor_resource() {
143        let app = build_router(&RuntimeConfig::default_local());
144
145        let response = app
146            .oneshot(
147                Request::builder()
148                    .uri("/.well-known/webfinger?resource=acct:bob@127.0.0.1:3000")
149                    .body(Body::empty())
150                    .expect("valid request"),
151            )
152            .await
153            .expect("response");
154
155        assert_eq!(response.status(), StatusCode::NOT_FOUND);
156    }
157}