Skip to main content

ostrya_server/
receive_auth.rs

1//! The authentication of the receive endpoint by its host.
2
3use std::future::Future;
4use std::sync::Arc;
5
6use hyper::StatusCode;
7use hyper::header::{HeaderName, HeaderValue};
8use hyper::http::request::Parts;
9use ostrya::remote::proto::Hello;
10use ostrya::{ReceiveHooks, ReceivePolicy};
11
12/// The authentication of the requests of the receive endpoint.
13///
14/// A refusal of [`authenticate`](Self::authenticate) or [`open`](Self::open)
15/// gets its status, its headers, and an `unauthorized` frame with its
16/// message. The endpoint adds no `WWW-Authenticate` header of its own.
17///
18/// # Call order
19///
20/// The endpoint calls [`authenticate`](Self::authenticate) for each request
21/// with a known route and method, before it reads a byte of the body. It
22/// gives the [`RequestKind`] of the route. For a `session` request, the
23/// endpoint then does these steps, in this order:
24///
25/// 1. It reads `Hello`.
26/// 2. It refuses a `Hello` that has `one-way` set to `true`, with the error
27///    code `protocol`. This step comes before the check of the version.
28/// 3. It checks `Hello` with
29///    [`ReceiveService::check_hello`](ostrya::ReceiveService::check_hello).
30/// 4. It takes a slot of the session limit, or answers 503.
31/// 5. It calls [`open`](Self::open), which gives the [`SessionSetup`] of the
32///    session. A refusal frees the slot.
33/// 6. It opens the session.
34///
35/// The checks of `Hello` come before the slot. A bad `Hello` gets 422 also
36/// when the sessions are at the limit or the endpoint stopped.
37///
38/// # Examples
39///
40/// An implementation with one bearer token, which gives the same receive
41/// policy to each session:
42///
43/// ```
44/// use std::sync::Arc;
45///
46/// use hyper::http::request::Parts;
47/// use ostrya::remote::proto::Hello;
48/// use ostrya::{ReceivePolicy, Repo};
49/// use ostrya_server::{
50///     EndpointOptions, ReceiveAuth, ReceiveEndpoint, Refusal, RequestKind, SessionSetup,
51/// };
52///
53/// struct OneToken {
54///     header: String,
55///     policy: Arc<ReceivePolicy>,
56/// }
57///
58/// impl ReceiveAuth for OneToken {
59///     type Principal = String;
60///
61///     fn owner(principal: &String) -> &str {
62///         principal
63///     }
64///
65///     async fn authenticate(&self, parts: &Parts, _kind: RequestKind) -> Result<String, Refusal> {
66///         // A real host compares a digest of the token in constant time.
67///         match parts.headers.get("authorization") {
68///             Some(value) if value.as_bytes() == self.header.as_bytes() => Ok("builder".into()),
69///             _ => Err(Refusal::unauthorized("a valid token is necessary")),
70///         }
71///     }
72///
73///     async fn open(&self, _principal: &String, _hello: &Hello) -> Result<SessionSetup, Refusal> {
74///         Ok(SessionSetup { policy: self.policy.clone(), hooks: None })
75///     }
76/// }
77///
78/// fn endpoint(
79///     repo: Repo,
80///     token: &str,
81///     policy: Arc<ReceivePolicy>,
82/// ) -> ostrya_server::Result<ReceiveEndpoint<OneToken>> {
83///     let auth = OneToken {
84///         header: format!("Bearer {token}"),
85///         policy,
86///     };
87///     ReceiveEndpoint::new(repo, auth, EndpointOptions::default())
88/// }
89/// ```
90pub trait ReceiveAuth: Send + Sync + 'static {
91    /// The identity of a request.
92    type Principal: Send + Sync + 'static;
93
94    /// Returns the owner key of a principal.
95    ///
96    /// A session belongs to the key of its `session` request. If a later
97    /// request of the session gives a different key, it gets 404, the answer
98    /// to an unknown session.
99    fn owner(principal: &Self::Principal) -> &str;
100
101    /// Returns the principal of a request, or its refusal.
102    ///
103    /// The endpoint calls it in the [call order](ReceiveAuth#call-order), with
104    /// the route of the request as `kind`. If it returns a refusal, the
105    /// endpoint reads and drops up to 1 MiB of the body before it answers.
106    ///
107    /// # Errors
108    ///
109    /// - [`Refusal`] to refuse the request. The endpoint answers with the
110    ///   status, the headers, and the message of the refusal.
111    fn authenticate(
112        &self,
113        parts: &Parts,
114        kind: RequestKind,
115    ) -> impl Future<Output = Result<Self::Principal, Refusal>> + Send;
116
117    /// Returns the setup of the session that `hello` opens for `principal`.
118    ///
119    /// The setup holds the receive policy and the hooks of the session. The
120    /// endpoint calls `open` in the [call order](ReceiveAuth#call-order),
121    /// after the checks of `Hello` and after it reserves a session slot.
122    /// Because of these checks, `hello` holds valid ref names alone. Its
123    /// collection id, if present, is valid too.
124    ///
125    /// The scope of the returned [`ReceivePolicy`](ostrya::ReceivePolicy)
126    /// must cover the namespace of `hello`. Otherwise the session refuses
127    /// the policy with 422 and `ref-denied`.
128    ///
129    /// Each `open` call holds a slot, so the session limit also limits the
130    /// count of `open` calls that run at one time.
131    ///
132    /// The host must not keep state from `open` alone, because a session can
133    /// fail to start after `open` returns. For example, a read of the
134    /// repository configuration fails, or a `bare` repository gets
135    /// `mode-refused` because the server does not run as root.
136    ///
137    /// # Errors
138    ///
139    /// - [`Refusal`] to refuse the session. The endpoint answers with the
140    ///   status, the headers, and the message of the refusal, and frees the
141    ///   slot.
142    fn open(
143        &self,
144        principal: &Self::Principal,
145        hello: &Hello,
146    ) -> impl Future<Output = Result<SessionSetup, Refusal>> + Send;
147}
148
149/// The route of a request of the receive endpoint.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151#[non_exhaustive]
152pub enum RequestKind {
153    /// The `POST session` request, which opens a session.
154    Open,
155    /// The `POST session/ID/have` request.
156    Have,
157    /// The `POST session/ID/objects` request.
158    Objects,
159    /// The `POST session/ID/commit` request.
160    Commit,
161    /// The `DELETE session/ID` request, which ends a session.
162    Delete,
163}
164
165/// A refusal of [`ReceiveAuth::authenticate`] or [`ReceiveAuth::open`].
166///
167/// A refusal holds:
168///
169/// - the status, 401 or 403
170/// - the message of its `unauthorized` frame
171/// - the response headers that it adds
172#[derive(Debug)]
173pub struct Refusal {
174    pub(crate) status: StatusCode,
175    pub(crate) message: String,
176    /// The headers, in the order of the `with_header` calls.
177    pub(crate) headers: Vec<(HeaderName, HeaderValue)>,
178}
179
180/// The longest message of a refusal, in bytes.
181const MAX_MESSAGE: usize = 4096;
182
183impl Refusal {
184    /// Creates a refusal with the status 401.
185    ///
186    /// If `message` is longer than 4096 bytes, `unauthorized` cuts it to at
187    /// most 4096 bytes, at a character boundary.
188    pub fn unauthorized(message: impl Into<String>) -> Refusal {
189        Refusal::new(StatusCode::UNAUTHORIZED, message.into())
190    }
191
192    /// Creates a refusal with the status 403.
193    ///
194    /// If `message` is longer than 4096 bytes, `forbidden` cuts it to at most
195    /// 4096 bytes, at a character boundary.
196    pub fn forbidden(message: impl Into<String>) -> Refusal {
197        Refusal::new(StatusCode::FORBIDDEN, message.into())
198    }
199
200    fn new(status: StatusCode, mut message: String) -> Refusal {
201        // The cut keeps the frame of the refusal in the frame limit.
202        message.truncate(message.floor_char_boundary(MAX_MESSAGE));
203        Refusal {
204            status,
205            message,
206            headers: Vec::new(),
207        }
208    }
209
210    /// Returns the refusal with one more response header.
211    ///
212    /// An example is a `WWW-Authenticate` header. The response holds the
213    /// headers in the order of the calls. If the host adds a name two times,
214    /// the response holds two headers.
215    ///
216    /// The endpoint drops a header named `Content-Length`,
217    /// `Transfer-Encoding`, or `Connection`, because it sets the framing and
218    /// the connection state of the response itself.
219    pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Refusal {
220        self.headers.push((name, value));
221        self
222    }
223}
224
225/// The receive policy and the hooks that [`ReceiveAuth::open`] gives to a
226/// session.
227pub struct SessionSetup {
228    /// The receive policy of the session.
229    pub policy: Arc<ReceivePolicy>,
230    /// The hooks of the session, or `None` for a session with no hooks.
231    ///
232    /// The endpoint opens the session with
233    /// [`ReceiveService::hello_with_hooks`](ostrya::ReceiveService::hello_with_hooks).
234    /// The commit of the session calls [`ReceiveHooks::before_update`] just
235    /// before the update lock. It calls [`ReceiveHooks::after_update`] after
236    /// it releases the update lock.
237    ///
238    /// # Refusals and errors of a hook
239    ///
240    /// - A refusal of `before_update` with
241    ///   [`HookRefusal::denied`](ostrya::HookRefusal::denied) gets 422 with
242    ///   `ref-denied`.
243    /// - A refusal of `before_update` with
244    ///   [`HookRefusal::internal`](ostrya::HookRefusal::internal) gets 500
245    ///   with `internal`.
246    /// - An error of `after_update` gets 500 with `internal`. The refs and
247    ///   the detached metadata stay written, and the session ends as aborted.
248    ///   The endpoint does not call
249    ///   [`EndpointOptions::on_report`](crate::EndpointOptions::on_report).
250    ///
251    /// The client gets the message of the refusal or of the error in the
252    /// `Error` frame, as the hook wrote it, cut at 4096 bytes. The host must
253    /// not put secrets or internal details in the message, because the
254    /// client sees it.
255    ///
256    /// # Session state during a hook
257    ///
258    /// While a hook runs, the session commits:
259    ///
260    /// - It keeps its slot of
261    ///   [`EndpointOptions::max_sessions`](crate::EndpointOptions::max_sessions).
262    /// - The idle timeout, a `DELETE`, and
263    ///   [`ReceiveEndpoint::shutdown`](crate::ReceiveEndpoint::shutdown) do
264    ///   not end it.
265    /// - During `before_update`, it also holds a shared lock of the
266    ///   repository, so a prune waits.
267    ///
268    /// Because the response to `commit` waits for both hooks, the host must
269    /// limit the time of its hooks.
270    ///
271    /// # Checks after the hook
272    ///
273    /// The commit runs these checks after `before_update` returns its plan,
274    /// so a commit can fail after a plan from the hook:
275    ///
276    /// - Before the update lock, a plan that the checks refuse gets 500 with
277    ///   `internal`. [`ReceiveHooks`] states the checks of the plan.
278    /// - Before the update lock, a merged dict with the host entries that is
279    ///   larger than the size limit gets 422 with `limit-exceeded`.
280    /// - Under the update lock, these updates get 422 with `ref-denied`:
281    ///   - a ref that is an alias
282    ///   - a path that a ref write cannot replace
283    ///   - two updates of which one names a directory of the other
284    /// - Under the update lock, `ref-mismatch` and `non-fast-forward` get
285    ///   409, and `delete-denied` gets 422.
286    /// - Under the update lock, if the stored dict changed after the plan, a
287    ///   merged dict over the size limit gets 422 with `limit-exceeded`.
288    pub hooks: Option<Arc<dyn ReceiveHooks>>,
289}