Skip to main content

ojak_axum/
lib.rs

1//! Serving a [`Federation`] from an axum application.
2//!
3//! [`wrap`] puts the federation in front of an application's router: a
4//! request Ojak answers is answered, and every other one, including a
5//! request to one of Ojak's routes that asked for a page rather than
6//! ActivityPub, goes on to the application. An inbox's POST is read, up to
7//! [`MAX_INBOX_BODY`], and received.
8//!
9//! ~~~~ ignore
10//! let app = ojak_axum::wrap(app, federation, |parts| {
11//!     parts.extensions.get::<AppState>().cloned()
12//! });
13//! ~~~~
14//!
15//! The function from the request's parts to the federation's data is where
16//! an application with several tenants gives Ojak the one a request is for;
17//! `None` sends the request to the application untouched.
18
19use axum::Router;
20use axum::body::Body;
21use axum::extract::{Request, State};
22use axum::http::request::Parts;
23use axum::http::{HeaderValue, StatusCode, header};
24use axum::middleware::{self, Next};
25use axum::response::{IntoResponse, Response};
26use ojak::federation::{Federation, Handled, MAX_INBOX_BODY};
27use std::sync::Arc;
28
29type DataFn<D> = Arc<dyn Fn(&Parts) -> Option<D> + Send + Sync>;
30
31struct Serving<D> {
32    federation: Federation<D>,
33    data: DataFn<D>,
34}
35
36impl<D> Clone for Serving<D> {
37    fn clone(&self) -> Self {
38        Self {
39            federation: self.federation.clone(),
40            data: self.data.clone(),
41        }
42    }
43}
44
45/// `app`, with `federation` answering what is Ojak's. `app` is a router
46/// with its state already given, as it would be served.
47pub fn wrap<D>(
48    app: Router,
49    federation: Federation<D>,
50    data: impl Fn(&Parts) -> Option<D> + Send + Sync + 'static,
51) -> Router
52where
53    D: Clone + Send + Sync + 'static,
54{
55    let serving = Serving {
56        federation,
57        data: Arc::new(data),
58    };
59    // A router whose fallback is the application, so that the layer sees
60    // every request, not only those the application routes.
61    Router::new()
62        .fallback_service(app)
63        .layer(middleware::from_fn_with_state(serving, serve::<D>))
64}
65
66async fn serve<D: Clone + Send + Sync + 'static>(
67    State(serving): State<Serving<D>>,
68    request: Request,
69    next: Next,
70) -> Response {
71    let (parts, body) = request.into_parts();
72    let Some(data) = (serving.data)(&parts) else {
73        return next.run(Request::from_parts(parts, body)).await;
74    };
75    if serving.federation.is_inbox(parts.uri.path()) {
76        // An inbox's POST is read here, bounded, and the body is Ojak's.
77        let Ok(body) = axum::body::to_bytes(body, MAX_INBOX_BODY).await else {
78            return StatusCode::PAYLOAD_TOO_LARGE.into_response();
79        };
80        return match serving
81            .federation
82            .handle_with_body(&parts, &body, data)
83            .await
84        {
85            Handled::Response(response) => response.map(Body::from),
86            _ => next.run(Request::from_parts(parts, Body::from(body))).await,
87        };
88    }
89    match serving.federation.handle(&parts, data).await {
90        Handled::Response(response) => response.map(Body::from),
91        // A route of Ojak's that a browser asked for: the application's page
92        // is at the same URL as an ActivityPub document, so a cache has to
93        // keep the two apart by Accept.
94        Handled::NotAcceptable => {
95            let mut response = next.run(Request::from_parts(parts, body)).await;
96            vary_on_accept(response.headers_mut());
97            response
98        }
99        _ => next.run(Request::from_parts(parts, body)).await,
100    }
101}
102
103/// Add `Accept` to `headers`' `Vary`, unless it is there already.
104fn vary_on_accept(headers: &mut axum::http::HeaderMap) {
105    let covered = headers
106        .get_all(header::VARY)
107        .iter()
108        .filter_map(|value| value.to_str().ok())
109        .flat_map(|value| value.split(','))
110        .map(str::trim)
111        .any(|name| name == "*" || name.eq_ignore_ascii_case("accept"));
112    if !covered {
113        headers.append(header::VARY, HeaderValue::from_static("Accept"));
114    }
115}