summaryrefslogtreecommitdiffstats
path: root/src/server/routes/users/webfinger.rs
blob: 8efeda61a06198978d1d16663fc5a33269592a7a (plain)
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
78
79
80
81
82
83
84
85
86
use activitypub_federation::{
    config::Data,
    fetch::webfinger::{build_webfinger_response, extract_webfinger_name},
};
use axum::{Json, extract::Query, http::StatusCode, response::IntoResponse};
use serde::Deserialize;

use crate::{error::AppError, server::routes::users::get_user::read_user, state::AppHandle};

#[derive(Deserialize)]
pub struct WebfingerQuery {
    resource: String,
}

pub async fn webfinger(
    Query(query): Query<WebfingerQuery>,
    data: Data<AppHandle>,
) -> Result<impl IntoResponse, AppError> {
    let name = extract_webfinger_name(&query.resource, &data)?;
    if let Some(db_user) = read_user(name, &data).await? {
        Ok((
            StatusCode::OK,
            Json(build_webfinger_response(
                query.resource,
                db_user.ap_id.into_inner(),
            )),
        )
            .into_response())
    } else {
        Ok((StatusCode::NOT_FOUND, "").into_response())
    }
}

#[cfg(test)]
mod tests {
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use sqlx::PgPool;
    use stack_up::Services;
    use tower::ServiceExt;

    use crate::{
        server::{self, test_config},
        state::AppState,
    };

    #[sqlx::test]
    async fn webfinger_ok(pool: PgPool) {
        let services = Services { postgres: pool };
        let state = AppState::new(services, &test_config()).await.unwrap();
        let app = server::router(state);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/.well-known/webfinger?resource=acct:sellershut@localhost")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[sqlx::test]
    async fn webfinger_err(pool: PgPool) {
        let services = Services { postgres: pool };
        let state = AppState::new(services, &test_config()).await.unwrap();
        let app = server::router(state);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/.well-known/webfinger?resource=acct:sst@localhost")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}