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, and no
123 /// two names of one ref. A name `@ID:NAME` holds a valid collection id.
124 ///
125 /// The session reads the rules of the returned
126 /// [`ReceivePolicy`](ostrya::ReceivePolicy) for the namespace of each ref
127 /// of `hello`. A policy that opens no push session, or that gives no `r`
128 /// on a ref of `hello` in its namespace, gets 422 and `ref-denied`.
129 ///
130 /// Each `open` call holds a slot, so the session limit also limits the
131 /// count of `open` calls that run at one time.
132 ///
133 /// The host must not keep state from `open` alone, because a session can
134 /// fail to start after `open` returns. For example, a read of the
135 /// repository configuration fails, or a `bare` repository gets
136 /// `mode-refused` because the server does not run as root.
137 ///
138 /// # Errors
139 ///
140 /// - [`Refusal`] to refuse the session. The endpoint answers with the
141 /// status, the headers, and the message of the refusal, and frees the
142 /// slot.
143 fn open(
144 &self,
145 principal: &Self::Principal,
146 hello: &Hello,
147 ) -> impl Future<Output = Result<SessionSetup, Refusal>> + Send;
148}
149
150/// The route of a request of the receive endpoint.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum RequestKind {
154 /// The `POST session` request, which opens a session.
155 Open,
156 /// The `POST session/ID/have` request.
157 Have,
158 /// The `POST session/ID/objects` request.
159 Objects,
160 /// The `POST session/ID/commit` request.
161 Commit,
162 /// The `DELETE session/ID` request, which ends a session.
163 Delete,
164}
165
166/// A refusal of [`ReceiveAuth::authenticate`] or [`ReceiveAuth::open`].
167///
168/// A refusal holds:
169///
170/// - the status, 401 or 403
171/// - the message of its `unauthorized` frame
172/// - the response headers that it adds
173#[derive(Debug)]
174pub struct Refusal {
175 pub(crate) status: StatusCode,
176 pub(crate) message: String,
177 /// The headers, in the order of the `with_header` calls.
178 pub(crate) headers: Vec<(HeaderName, HeaderValue)>,
179}
180
181/// The longest message of a refusal, in bytes.
182const MAX_MESSAGE: usize = 4096;
183
184impl Refusal {
185 /// Creates a refusal with the status 401.
186 ///
187 /// If `message` is longer than 4096 bytes, `unauthorized` cuts it to at
188 /// most 4096 bytes, at a character boundary.
189 pub fn unauthorized(message: impl Into<String>) -> Refusal {
190 Refusal::new(StatusCode::UNAUTHORIZED, message.into())
191 }
192
193 /// Creates a refusal with the status 403.
194 ///
195 /// If `message` is longer than 4096 bytes, `forbidden` cuts it to at most
196 /// 4096 bytes, at a character boundary.
197 pub fn forbidden(message: impl Into<String>) -> Refusal {
198 Refusal::new(StatusCode::FORBIDDEN, message.into())
199 }
200
201 fn new(status: StatusCode, mut message: String) -> Refusal {
202 // The cut keeps the frame of the refusal in the frame limit.
203 message.truncate(message.floor_char_boundary(MAX_MESSAGE));
204 Refusal {
205 status,
206 message,
207 headers: Vec::new(),
208 }
209 }
210
211 /// Returns the refusal with one more response header.
212 ///
213 /// An example is a `WWW-Authenticate` header. The response holds the
214 /// headers in the order of the calls. If the host adds a name two times,
215 /// the response holds two headers.
216 ///
217 /// The endpoint drops a header named `Content-Length`,
218 /// `Transfer-Encoding`, or `Connection`, because it sets the framing and
219 /// the connection state of the response itself.
220 pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Refusal {
221 self.headers.push((name, value));
222 self
223 }
224}
225
226/// The receive policy and the hooks that [`ReceiveAuth::open`] gives to a
227/// session.
228pub struct SessionSetup {
229 /// The receive policy of the session.
230 pub policy: Arc<ReceivePolicy>,
231 /// The hooks of the session, or `None` for a session with no hooks.
232 ///
233 /// The endpoint opens the session with
234 /// [`ReceiveService::hello_with_hooks`](ostrya::ReceiveService::hello_with_hooks).
235 /// The commit of the session calls [`ReceiveHooks::before_update`], or
236 /// [`ReceiveHooks::before_server_commit`] for a server commit, before the
237 /// update lock. It calls [`ReceiveHooks::after_update`] after it releases
238 /// the update lock.
239 ///
240 /// # Refusals and errors of a hook
241 ///
242 /// - A refusal of `before_update` or `before_server_commit` with
243 /// [`HookRefusal::denied`](ostrya::HookRefusal::denied) gets 422 with
244 /// `ref-denied`. Hooks that do not implement `before_server_commit`
245 /// refuse each server commit in this way.
246 /// - A refusal of `before_update` or `before_server_commit` with
247 /// [`HookRefusal::internal`](ostrya::HookRefusal::internal) gets 500
248 /// with `internal`.
249 /// - An error of `after_update` gets 500 with `internal`. The refs and
250 /// the detached metadata stay written, and the session ends as aborted.
251 /// The endpoint does not call
252 /// [`EndpointOptions::on_report`](crate::EndpointOptions::on_report).
253 ///
254 /// The client gets the message of the refusal or of the error in the
255 /// `Error` frame, as the hook wrote it, cut at 4096 bytes. The host must
256 /// not put secrets or internal details in the message, because the
257 /// client sees it.
258 ///
259 /// # Session state during a hook
260 ///
261 /// While a hook runs, the session commits:
262 ///
263 /// - It keeps its slot of
264 /// [`EndpointOptions::max_sessions`](crate::EndpointOptions::max_sessions).
265 /// - The idle timeout, a `DELETE`, and
266 /// [`ReceiveEndpoint::shutdown`](crate::ReceiveEndpoint::shutdown) do
267 /// not end it.
268 /// - During `before_update` or `before_server_commit`, it also holds a
269 /// shared lock of the repository, so a prune waits.
270 ///
271 /// Because the response to `commit` waits for both hooks, the host must
272 /// limit the time of its hooks.
273 ///
274 /// # Checks after the hook
275 ///
276 /// The commit runs these checks after `before_update` returns its plan,
277 /// so a commit can fail after a plan from the hook:
278 ///
279 /// - Before the update lock, a plan that the checks refuse gets 500 with
280 /// `internal`. [`ReceiveHooks`] states the checks of the plan.
281 /// - Before the update lock, a merged dict with the host entries that is
282 /// larger than the size limit gets 422 with `limit-exceeded`.
283 /// - Under the update lock, these updates get 422 with `ref-denied`:
284 /// - a ref that is an alias
285 /// - a path that a ref write cannot replace
286 /// - two updates of which one names a directory of the other
287 /// - Under the update lock, `ref-mismatch` and `non-fast-forward` get
288 /// 409, and `delete-denied` gets 422.
289 /// - Under the update lock, if the stored dict changed after the plan, a
290 /// merged dict over the size limit gets 422 with `limit-exceeded`.
291 ///
292 /// The commit of a server commit runs these checks after
293 /// `before_server_commit` returns:
294 ///
295 /// - Under the update lock, the checks of the ref paths get 422 with
296 /// `ref-denied`.
297 /// - Under the update lock, `orphan` on a branch that is present, which
298 /// the policy does not allow, gets 409 with `non-fast-forward`.
299 /// - Under the update lock, a tag that is present gets 409 with
300 /// `ref-mismatch`.
301 /// - Under the update lock, if the stored dict of a staged attachment
302 /// changed after the size check before the hook, a merged dict over the
303 /// size limit gets 422 with `limit-exceeded`.
304 pub hooks: Option<Arc<dyn ReceiveHooks>>,
305}