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, or [`ReceiveHooks::before_server_commit`] for
236 /// a server commit. It calls [`ReceiveHooks::after_update`] after it
237 /// releases the update lock.
238 ///
239 /// # Refusals and errors of a hook
240 ///
241 /// - A refusal of `before_update` or `before_server_commit` with
242 /// [`HookRefusal::denied`](ostrya::HookRefusal::denied) gets 422 with
243 /// `ref-denied`. Hooks that do not implement `before_server_commit`
244 /// refuse each server commit in this way.
245 /// - A refusal of `before_update` or `before_server_commit` with
246 /// [`HookRefusal::internal`](ostrya::HookRefusal::internal) gets 500
247 /// with `internal`.
248 /// - An error of `after_update` gets 500 with `internal`. The refs and
249 /// the detached metadata stay written, and the session ends as aborted.
250 /// The endpoint does not call
251 /// [`EndpointOptions::on_report`](crate::EndpointOptions::on_report).
252 ///
253 /// The client gets the message of the refusal or of the error in the
254 /// `Error` frame, as the hook wrote it, cut at 4096 bytes. The host must
255 /// not put secrets or internal details in the message, because the
256 /// client sees it.
257 ///
258 /// # Session state during a hook
259 ///
260 /// While a hook runs, the session commits:
261 ///
262 /// - It keeps its slot of
263 /// [`EndpointOptions::max_sessions`](crate::EndpointOptions::max_sessions).
264 /// - The idle timeout, a `DELETE`, and
265 /// [`ReceiveEndpoint::shutdown`](crate::ReceiveEndpoint::shutdown) do
266 /// not end it.
267 /// - During `before_update` or `before_server_commit`, it also holds a
268 /// shared lock of the repository, so a prune waits.
269 ///
270 /// Because the response to `commit` waits for both hooks, the host must
271 /// limit the time of its hooks.
272 ///
273 /// # Checks after the hook
274 ///
275 /// The commit runs these checks after `before_update` returns its plan,
276 /// so a commit can fail after a plan from the hook:
277 ///
278 /// - Before the update lock, a plan that the checks refuse gets 500 with
279 /// `internal`. [`ReceiveHooks`] states the checks of the plan.
280 /// - Before the update lock, a merged dict with the host entries that is
281 /// larger than the size limit gets 422 with `limit-exceeded`.
282 /// - Under the update lock, these updates get 422 with `ref-denied`:
283 /// - a ref that is an alias
284 /// - a path that a ref write cannot replace
285 /// - two updates of which one names a directory of the other
286 /// - Under the update lock, `ref-mismatch` and `non-fast-forward` get
287 /// 409, and `delete-denied` gets 422.
288 /// - Under the update lock, if the stored dict changed after the plan, a
289 /// merged dict over the size limit gets 422 with `limit-exceeded`.
290 ///
291 /// The commit of a server commit runs these checks after
292 /// `before_server_commit` returns, under the update lock:
293 ///
294 /// - The checks of the ref paths get 422 with `ref-denied`.
295 /// - `orphan` on a branch that is present, which the policy does not
296 /// allow, gets 409 with `non-fast-forward`.
297 /// - A tag that is present gets 409 with `ref-mismatch`.
298 pub hooks: Option<Arc<dyn ReceiveHooks>>,
299}