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(repo: Repo, token: &str) -> ostrya_server::Result<ReceiveEndpoint<OneToken>> {
79/// let auth = OneToken {
80/// header: format!("Bearer {token}"),
81/// policy: Arc::new(ReceivePolicy::default()),
82/// };
83/// ReceiveEndpoint::new(repo, auth, EndpointOptions::default())
84/// }
85/// ```
86pub trait ReceiveAuth: Send + Sync + 'static {
87 /// The identity of a request.
88 type Principal: Send + Sync + 'static;
89
90 /// Returns the owner key of a principal.
91 ///
92 /// A session belongs to the key of its `session` request. If a later
93 /// request of the session gives a different key, it gets 404, the answer
94 /// to an unknown session.
95 fn owner(principal: &Self::Principal) -> &str;
96
97 /// Returns the principal of a request, or its refusal.
98 ///
99 /// The endpoint calls it in the [call order](ReceiveAuth#call-order), with
100 /// the route of the request as `kind`. If it returns a refusal, the
101 /// endpoint reads and drops up to 1 MiB of the body before it answers.
102 ///
103 /// # Errors
104 ///
105 /// - [`Refusal`] to refuse the request. The endpoint answers with the
106 /// status, the headers, and the message of the refusal.
107 fn authenticate(
108 &self,
109 parts: &Parts,
110 kind: RequestKind,
111 ) -> impl Future<Output = Result<Self::Principal, Refusal>> + Send;
112
113 /// Returns the setup of the session that `hello` opens for `principal`.
114 ///
115 /// The setup holds the receive policy and the hooks of the session. The
116 /// endpoint calls `open` in the [call order](ReceiveAuth#call-order),
117 /// after the checks of `Hello` and after it reserves a session slot.
118 /// Because of these checks, `hello` holds valid ref names alone.
119 ///
120 /// Each `open` call holds a slot, so the session limit also limits the
121 /// count of `open` calls that run at one time.
122 ///
123 /// The host must not keep state from `open` alone, because a session can
124 /// fail to start after `open` returns. For example, a read of the
125 /// repository configuration fails, or a `bare` repository gets
126 /// `mode-refused` because the server does not run as root.
127 ///
128 /// # Errors
129 ///
130 /// - [`Refusal`] to refuse the session. The endpoint answers with the
131 /// status, the headers, and the message of the refusal, and frees the
132 /// slot.
133 fn open(
134 &self,
135 principal: &Self::Principal,
136 hello: &Hello,
137 ) -> impl Future<Output = Result<SessionSetup, Refusal>> + Send;
138}
139
140/// The route of a request of the receive endpoint.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum RequestKind {
144 /// The `POST session` request, which opens a session.
145 Open,
146 /// The `POST session/ID/have` request.
147 Have,
148 /// The `POST session/ID/objects` request.
149 Objects,
150 /// The `POST session/ID/commit` request.
151 Commit,
152 /// The `DELETE session/ID` request, which ends a session.
153 Delete,
154}
155
156/// A refusal of [`ReceiveAuth::authenticate`] or [`ReceiveAuth::open`].
157///
158/// A refusal holds:
159///
160/// - the status, 401 or 403
161/// - the message of its `unauthorized` frame
162/// - the response headers that it adds
163#[derive(Debug)]
164pub struct Refusal {
165 pub(crate) status: StatusCode,
166 pub(crate) message: String,
167 /// The headers, in the order of the `with_header` calls.
168 pub(crate) headers: Vec<(HeaderName, HeaderValue)>,
169}
170
171/// The longest message of a refusal, in bytes.
172const MAX_MESSAGE: usize = 4096;
173
174impl Refusal {
175 /// Creates a refusal with the status 401.
176 ///
177 /// If `message` is longer than 4096 bytes, `unauthorized` cuts it to at
178 /// most 4096 bytes, at a character boundary.
179 pub fn unauthorized(message: impl Into<String>) -> Refusal {
180 Refusal::new(StatusCode::UNAUTHORIZED, message.into())
181 }
182
183 /// Creates a refusal with the status 403.
184 ///
185 /// If `message` is longer than 4096 bytes, `forbidden` cuts it to at most
186 /// 4096 bytes, at a character boundary.
187 pub fn forbidden(message: impl Into<String>) -> Refusal {
188 Refusal::new(StatusCode::FORBIDDEN, message.into())
189 }
190
191 fn new(status: StatusCode, mut message: String) -> Refusal {
192 // The cut keeps the frame of the refusal in the frame limit.
193 message.truncate(message.floor_char_boundary(MAX_MESSAGE));
194 Refusal {
195 status,
196 message,
197 headers: Vec::new(),
198 }
199 }
200
201 /// Returns the refusal with one more response header.
202 ///
203 /// An example is a `WWW-Authenticate` header. The response holds the
204 /// headers in the order of the calls. If the host adds a name two times,
205 /// the response holds two headers.
206 ///
207 /// The endpoint drops a header named `Content-Length`,
208 /// `Transfer-Encoding`, or `Connection`, because it sets the framing and
209 /// the connection state of the response itself.
210 pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Refusal {
211 self.headers.push((name, value));
212 self
213 }
214}
215
216/// The receive policy and the hooks that [`ReceiveAuth::open`] gives to a
217/// session.
218pub struct SessionSetup {
219 /// The receive policy of the session.
220 pub policy: Arc<ReceivePolicy>,
221 /// The hooks of the session, or `None` for a session with no hooks.
222 ///
223 /// The endpoint opens the session with
224 /// [`ReceiveService::hello_with_hooks`](ostrya::ReceiveService::hello_with_hooks).
225 /// The commit of the session calls [`ReceiveHooks::before_update`] just
226 /// before the update lock. It calls [`ReceiveHooks::after_update`] after
227 /// it releases the update lock.
228 ///
229 /// # Refusals and errors of a hook
230 ///
231 /// - A refusal of `before_update` with
232 /// [`HookRefusal::denied`](ostrya::HookRefusal::denied) gets 422 with
233 /// `ref-denied`.
234 /// - A refusal of `before_update` with
235 /// [`HookRefusal::internal`](ostrya::HookRefusal::internal) gets 500
236 /// with `internal`.
237 /// - An error of `after_update` gets 500 with `internal`. The refs and
238 /// the detached metadata stay written, and the session ends as aborted.
239 /// The endpoint does not call
240 /// [`EndpointOptions::on_report`](crate::EndpointOptions::on_report).
241 ///
242 /// The client gets the message of the refusal or of the error in the
243 /// `Error` frame, as the hook wrote it, cut at 4096 bytes. The host must
244 /// not put secrets or internal details in the message, because the
245 /// client sees it.
246 ///
247 /// # Session state during a hook
248 ///
249 /// While a hook runs, the session commits:
250 ///
251 /// - It keeps its slot of
252 /// [`EndpointOptions::max_sessions`](crate::EndpointOptions::max_sessions).
253 /// - The idle timeout, a `DELETE`, and
254 /// [`ReceiveEndpoint::shutdown`](crate::ReceiveEndpoint::shutdown) do
255 /// not end it.
256 /// - During `before_update`, it also holds a shared lock of the
257 /// repository, so a prune waits.
258 ///
259 /// Because the response to `commit` waits for both hooks, the host must
260 /// limit the time of its hooks.
261 ///
262 /// # Checks after the hook
263 ///
264 /// The commit runs these checks after `before_update` returns its plan,
265 /// so a commit can fail after a plan from the hook:
266 ///
267 /// - Before the update lock, a plan that the checks refuse gets 500 with
268 /// `internal`. [`ReceiveHooks`] states the checks of the plan.
269 /// - Before the update lock, a merged dict with the host entries that is
270 /// larger than the size limit gets 422 with `limit-exceeded`.
271 /// - Under the update lock, these updates get 422 with `ref-denied`:
272 /// - a ref that is an alias
273 /// - a path that a ref write cannot replace
274 /// - two updates of which one names a directory of the other
275 /// - Under the update lock, `ref-mismatch` and `non-fast-forward` get
276 /// 409, and `delete-denied` gets 422.
277 /// - Under the update lock, if the stored dict changed after the plan, a
278 /// merged dict over the size limit gets 422 with `limit-exceeded`.
279 pub hooks: Option<Arc<dyn ReceiveHooks>>,
280}