ostrya_server/options.rs
1//! The options of a server.
2
3use std::fmt;
4use std::net::{Ipv4Addr, SocketAddr};
5use std::sync::Arc;
6use std::time::Duration;
7
8use ostrya::access::{ForwardedHeader, IpNet};
9use ostrya::{ReceivePolicies, ReceiveReport};
10
11use crate::endpoint::EndpointOptions;
12use crate::event::EventSink;
13
14/// The PEM bytes of the server TLS files.
15///
16/// The caller reads each file once at start.
17#[derive(Clone, Eq, PartialEq)]
18pub struct ServerTls {
19 /// The server certificate, followed by any intermediates.
20 pub cert_chain_pem: Vec<u8>,
21 /// The private key of the certificate: plain, or encrypted PKCS#8 under
22 /// PBES2.
23 pub key_pem: Vec<u8>,
24 /// The passphrase of an encrypted key.
25 pub key_passphrase: Option<String>,
26}
27
28/// The debug text holds no byte of the private key or of the passphrase. It
29/// shows the key as `<N bytes redacted>`, and a passphrase that is set as
30/// `<redacted>`.
31impl fmt::Debug for ServerTls {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.debug_struct("ServerTls")
34 .field("cert_chain_pem", &self.cert_chain_pem)
35 .field(
36 "key_pem",
37 &format!("<{} bytes redacted>", self.key_pem.len()),
38 )
39 .field(
40 "key_passphrase",
41 &self.key_passphrase.as_ref().map(|_| "<redacted>"),
42 )
43 .finish()
44 }
45}
46
47/// The options of [`bind`](crate::bind).
48///
49/// The struct is `#[non_exhaustive]`, so a caller starts from
50/// [`ServeOptions::default`] and sets the fields.
51///
52/// [`bind`](crate::bind) checks the fields that go together. Its
53/// [errors](crate::bind#errors) list the refusals.
54///
55/// The fields `parallel_uploads`, `session_idle_timeout`, `max_sessions`, and
56/// `on_report` go to the [`EndpointOptions`] of the receive endpoint. Their
57/// defaults are the defaults of [`EndpointOptions::default`]. If
58/// [`receive`](ServeOptions::receive) is `None`, [`bind`](crate::bind) does
59/// not read these four fields or `allow_cleartext_credentials`. It then
60/// refuses no value of them.
61///
62/// # Authentication
63///
64/// The server identifies the client of each request by the auth items of the
65/// client groups of [`receive`](ServeOptions::receive): the requests of the
66/// receive endpoint, and the reads of the archive view and of the ref
67/// listing. Identification gives one auth item. The server takes the first
68/// step that applies:
69///
70/// 1. A request with more than one `Authorization` header gets 401.
71/// 2. If the connection has no TLS, a bearer or Basic credential gets 403,
72/// unless
73/// [`allow_cleartext_credentials`](ServeOptions::allow_cleartext_credentials)
74/// is set, or a trusted proxy states the scheme `https` (see
75/// [Client address](ServeOptions#client-address)).
76/// 3. A request with an `Authorization` header gets the item of its
77/// credential. A bearer token, `Authorization: Bearer TOKEN`, gets the
78/// `token-sha256:HEX` item of the SHA-256 digest of the token. A Basic
79/// credential, `Authorization: Basic` with the base64 of `USER:PASSWORD`,
80/// gets the `basic-sha256:USER:HEX` item of the user name and of the
81/// digest of the password. The user name runs to the first `:`, so the
82/// password can hold `:`. A credential that matches no item gets 401, also
83/// when the request has a client certificate. An empty token, a Basic
84/// credential with no `:`, a user name that is not UTF-8, an empty
85/// password, and another scheme match no item.
86/// 4. A request with a client certificate gets the first item that matches,
87/// in this order: `tls-sha256:HEX` by the SHA-256 digest of the DER
88/// bytes, `tls:NAME` by the subject CN, `tls:*`. A certificate that
89/// matches no item gets 403. A subject matches `tls:NAME` only if it holds
90/// exactly one CN, of type UTF8String or PrintableString. From a trusted
91/// proxy with a header of a forwarded certificate, the certificate comes
92/// from that header alone, and never from the TLS handshake (see
93/// [Forwarded certificate](ServeOptions#forwarded-certificate)). With no
94/// [`client_ca_pem`](ServeOptions::client_ca_pem), a request has no
95/// client certificate, so the `tls-sha256:HEX`, `tls:NAME`, and `tls:*`
96/// items match no request. The other items of their groups still match.
97/// 5. A request whose client address is in the network of a `net:` item gets
98/// that item. When two items match, the item with the longer prefix wins.
99/// 6. A request gets the `anonymous` item, if one exists.
100/// 7. Else the request gets 401 when a `token-sha256` or a `basic-sha256`
101/// item exists, and 403 when none exists.
102///
103/// The server compares the digest of a credential with every `token-sha256`
104/// or `basic-sha256` item in constant time. It does not stop at a match. The
105/// TLS handshake verifies a client certificate against
106/// [`client_ca_pem`](ServeOptions::client_ca_pem). The server reads the
107/// certificate of the handshake one time for each connection.
108///
109/// Each 401 carries two headers: `WWW-Authenticate: Bearer realm="ostrya"`
110/// and `WWW-Authenticate: Basic realm="ostrya"`.
111///
112/// A read gets the [`ReadAccess`](ostrya::access::ReadAccess) of the item,
113/// with the claims of its certificate. A refused read gets the status of the
114/// refusal and an empty body. [`Server`](crate::Server) states the rules of
115/// a read.
116///
117/// The owner key of a request is the text of its item, as
118/// [`AuthItem`](ostrya::access::AuthItem) writes it. All clients with one
119/// item share one owner key, for example all anonymous clients. A client
120/// certificate that gives a `tls:*`, `tls:NAME`, or `tls-sha256:HEX` item of
121/// a group with `tls-accept-claim=true` has the key `tls-sha256:HEX`, the
122/// SHA-256 digest of its DER bytes. So two certificates with different
123/// claims never share a session. This key is the key of no other client:
124/// the certificate sets the item that it matches, and only the certificate
125/// of that digest matches the item `tls-sha256:HEX`.
126///
127/// A `session` request selects the client group that carries the item in the
128/// namespace of its `Hello`, with
129/// [`ReceivePolicies::select`](ostrya::ReceivePolicies::select). The
130/// collection id of `Hello` names the namespace, and no collection or the
131/// collection id of the repository names the local refs. The session gets
132/// the policy of that group and no hooks. With no such group, and with a
133/// group that opens no push session, the request gets 403.
134///
135/// # Claims
136///
137/// A client group with `tls-accept-claim=true` reads the claims of the client
138/// certificate that gives the item of a `session` request or of a read: the
139/// URI SANs with the scheme `ostrya`, as [`Claims`](ostrya::access::Claims)
140/// reads them.
141/// The claims of the certificate of the TLS handshake are read one time for
142/// each connection. The claims of a forwarded certificate are read one time
143/// for each cache entry.
144///
145/// - When the certificate holds one or more claims for the namespace of the
146/// session or of the ref that a read names, as
147/// [`ClientAccess::claim_rules`](ostrya::access::ClientAccess::claim_rules)
148/// gives them, they replace the allow items and the deny items of the
149/// group. The other values of the policy come from the group.
150/// - When it holds no claim for the namespace, the rules of the group apply.
151/// - When the claims do not parse, the request gets 403, and the server
152/// reports a [`ServerEvent::BadClaims`](crate::ServerEvent::BadClaims) to
153/// [`on_event`](ServeOptions::on_event). The claims do not parse when a
154/// URI with the scheme `ostrya`, in any case, is no claim form, when the
155/// certificate holds more than [`MAX_CLAIMS`](ostrya::access::MAX_CLAIMS)
156/// such URIs, when the certificate does not decode, when it holds more
157/// than one subjectAltName extension, and when its subjectAltName
158/// extension does not decode. Each case has its own reason.
159/// - When the rules of the claims open no push session, the `session`
160/// request gets 403.
161/// - A read gets 403 when the claims do not parse and a group with
162/// `tls-accept-claim=true` carries the item of the certificate, also a read
163/// of an object or of `config`. The server reports a
164/// [`ServerEvent::BadClaims`](crate::ServerEvent::BadClaims) for each such
165/// read.
166///
167/// A group with `tls-accept-claim=false`, a credential, a `net:` item, and the
168/// `anonymous` item read no claim.
169///
170/// # Client address
171///
172/// The client address is the TCP peer address of the connection, with these
173/// changes:
174///
175/// - With [`proxy_protocol`](ServeOptions::proxy_protocol), the source
176/// address of the PROXY header replaces the peer address. A header with
177/// no address keeps the peer address.
178/// - When the peer address is in
179/// [`trusted_proxies`](ServeOptions::trusted_proxies), the server reads
180/// the client address from the one header of
181/// [`trusted_proxy_header`](ServeOptions::trusted_proxy_header). It walks
182/// the hops of the header from the right, and skips each hop whose address
183/// is in a trusted network. The first other hop is the client. When all
184/// hops are trusted, the client is the leftmost hop. A hop with no
185/// address, for example `unknown`, gives a client with no address, which
186/// matches no `net:` item. A header that is absent, or that has one line
187/// of white space alone, keeps the peer address. A header that is not
188/// UTF-8, that does not parse, or that has text and no hop, for example
189/// `X-Forwarded-For: , ,`, gives no address.
190/// - From a trusted peer, the request counts as TLS for step 2 when the
191/// proxy states the scheme `https`, in any case. With
192/// [`ForwardedHeader::Forwarded`], the scheme is the `proto` of the
193/// selected hop. With the other headers, it is the rightmost value of
194/// `X-Forwarded-Proto`.
195/// - From a peer that is not trusted, the server reads no forwarding header,
196/// no `X-Forwarded-Proto`, and no forwarded certificate.
197///
198/// An IPv4-mapped IPv6 address counts as its IPv4 address.
199///
200/// With [`proxy_protocol`](ServeOptions::proxy_protocol), the server compares
201/// the source address of the PROXY header with
202/// [`trusted_proxies`](ServeOptions::trusted_proxies), so it does not read
203/// the forwarding headers and the forwarded certificate of a proxy that
204/// states the address of its client in the PROXY header.
205///
206/// A trusted proxy must set or remove the forwarding header, the
207/// `X-Forwarded-Proto` header, and the header of a forwarded certificate of
208/// each request. Else a client can send these headers through the proxy and
209/// take another address or another certificate.
210///
211/// # Forwarded certificate
212///
213/// [`trusted_proxy_client_cert`](ServeOptions::trusted_proxy_client_cert)
214/// names the request header that carries the client certificate from a
215/// trusted proxy. The server reads the header for each request, and never
216/// keeps the result for a connection, because a proxy sends the requests of
217/// many clients over one connection. The value is one of these forms, after
218/// the server percent-decodes it, with `+` kept as `+`:
219///
220/// - a PEM certificate that starts with `-----BEGIN`, as nginx
221/// `$ssl_client_escaped_cert` gives it URL-escaped;
222/// - the base64 of the DER bytes, as HAProxy `ssl_c_der,base64` gives it, or
223/// URL-escaped, as Traefik `passTLSClientCert` gives it.
224///
225/// From a trusted proxy, this header alone gives the certificate. The server
226/// does not use the certificate of the TLS handshake, which is the
227/// certificate of the proxy. A request with no such header gives no
228/// certificate. From a peer that is not trusted, or with no
229/// `trusted_proxy_client_cert`, the certificate of the TLS handshake applies.
230///
231/// An empty value, or white space alone, is no certificate. These cases get
232/// 403: a value with a comma, as the chain of Traefik holds; more than one
233/// line of the header; PEM with more than one `CERTIFICATE` section; a value
234/// that does not decode; and a certificate that
235/// [`client_ca_pem`](ServeOptions::client_ca_pem) does not verify. The
236/// server uses no intermediate certificate from the proxy, so the client CA
237/// must hold each intermediate CA. The verification checks the validity
238/// period and the `clientAuth` extended key usage.
239///
240/// The server keeps each verified certificate in a cache of 1024 entries,
241/// keyed by the SHA-256 digest of its DER bytes, until the end of its
242/// validity period. A full cache removes its oldest entry. The cache keeps
243/// no refusal.
244#[derive(Clone)]
245#[non_exhaustive]
246pub struct ServeOptions {
247 /// The addresses to listen on.
248 ///
249 /// Port 0 lets the kernel choose a port, which
250 /// [`Server::local_addrs`](crate::Server::local_addrs) reports.
251 /// [`bind`](crate::bind) refuses an empty list. The default is
252 /// `127.0.0.1:8080`.
253 pub listen: Vec<SocketAddr>,
254 /// The TLS files, or `None` for plain HTTP. The default is `None`.
255 pub tls: Option<ServerTls>,
256 /// The PEM CA certificates that verify the client certificate of the TLS
257 /// handshake and a forwarded certificate, or `None`.
258 ///
259 /// [`bind`](crate::bind) builds one verifier from the certificates, and
260 /// the handshake and each forwarded certificate use it. A client that
261 /// presents no certificate also completes the handshake. A client that
262 /// presents a certificate that the CA did not sign fails the handshake.
263 /// The field needs [`tls`](ServeOptions::tls) or
264 /// [`trusted_proxy_client_cert`](ServeOptions::trusted_proxy_client_cert).
265 /// The default is `None`.
266 pub client_ca_pem: Option<Vec<u8>>,
267 /// The networks of the peers whose forwarding data the server reads.
268 ///
269 /// [Client address](ServeOptions#client-address) states the rules. A
270 /// non-empty list needs
271 /// [`trusted_proxy_header`](ServeOptions::trusted_proxy_header). The
272 /// default is an empty list, which trusts no peer.
273 pub trusted_proxies: Vec<IpNet>,
274 /// The request header from which the server reads the client address of
275 /// a request from a trusted proxy, or `None`.
276 ///
277 /// The server reads this one header, and no other header of a client
278 /// address. The field needs a non-empty
279 /// [`trusted_proxies`](ServeOptions::trusted_proxies). The default is
280 /// `None`.
281 pub trusted_proxy_header: Option<ForwardedHeader>,
282 /// The name of the request header that carries the client certificate
283 /// from a trusted proxy, or `None`.
284 ///
285 /// [Forwarded certificate](ServeOptions#forwarded-certificate) states the
286 /// rules. The name passes [`ostrya::access::is_header_name`]. The field
287 /// needs [`client_ca_pem`](ServeOptions::client_ca_pem) and a non-empty
288 /// [`trusted_proxies`](ServeOptions::trusted_proxies). The default is
289 /// `None`.
290 pub trusted_proxy_client_cert: Option<String>,
291 /// The switch that reads a PROXY protocol header, version 1 or 2, at the
292 /// start of each connection.
293 ///
294 /// With the switch, each listener reads the header before the TLS
295 /// handshake and before the first request. Its source address replaces
296 /// the peer address. A header with no address, for example `UNKNOWN` or
297 /// `LOCAL`, keeps the peer address. The server closes a connection with
298 /// no valid header, or with no header within 30 seconds, and writes no
299 /// byte to it. The default is `false`.
300 ///
301 /// Each peer that can connect states its own client address in the
302 /// header. Only the proxy must be able to reach the listener.
303 pub proxy_protocol: bool,
304 /// The longest time that a response body waits for the client to take its
305 /// next bytes.
306 ///
307 /// If a body waits longer, its connection ends. The bodies of the
308 /// connection then drop and release the files and the compressors that
309 /// they hold. An HTTP/2 connection sends a ping after half this time with
310 /// no frame from the peer. It ends if the peer does not answer within
311 /// this time.
312 ///
313 /// A body that waits for its own reader, for example for a compressor of
314 /// the archive view, does not wait for the client. The time does not
315 /// count for such a body until it gives its next frame.
316 ///
317 /// The default is 60 seconds. [`bind`](crate::bind) refuses zero.
318 pub body_timeout: Duration,
319 /// The client groups of the server and their policies, or `None` for a
320 /// read-only server.
321 ///
322 /// With `None`, the server has no receive endpoint and identifies no
323 /// client. Each read gets the rights of the `anonymous` item under the
324 /// two implicit groups of a config with no client group. The default is
325 /// `None`.
326 /// [`ReceivePolicies::from_config`](ostrya::ReceivePolicies::from_config)
327 /// builds the value from the repository config.
328 /// [Authentication](ServeOptions#authentication) states how a request
329 /// gets its group. The server does not read the groups or a repository
330 /// setting of the endpoint again while it runs. A change takes effect at
331 /// the next start.
332 pub receive: Option<Arc<ReceivePolicies>>,
333 /// The switch that takes a bearer or Basic credential on a connection
334 /// without TLS.
335 ///
336 /// The default is `false`. If the switch is `false`, the server refuses
337 /// such a credential with 403, unless a trusted proxy states the scheme
338 /// `https`. A server on a loopback address, or behind a proxy that
339 /// terminates TLS and is not in
340 /// [`trusted_proxies`](ServeOptions::trusted_proxies), can set it. A
341 /// read-only server does not read the field.
342 pub allow_cleartext_credentials: bool,
343 /// The number of object streams of one session, as in
344 /// [`EndpointOptions::parallel_uploads`].
345 ///
346 /// The default is 4.
347 pub parallel_uploads: u32,
348 /// The idle timeout of a session, as in
349 /// [`EndpointOptions::session_idle_timeout`].
350 ///
351 /// The default is 300 seconds.
352 pub session_idle_timeout: Duration,
353 /// The most sessions open at the same time, as in
354 /// [`EndpointOptions::max_sessions`].
355 ///
356 /// The default is 16.
357 pub max_sessions: usize,
358 /// The callback for the report of a committed session, as in
359 /// [`EndpointOptions::on_report`].
360 pub on_report: Option<Arc<dyn Fn(ReceiveReport) + Send + Sync>>,
361 /// The callback for each [`ServerEvent`](crate::ServerEvent) of the
362 /// server, or `None`.
363 ///
364 /// The server calls it in the task of the request, so the callback must
365 /// return soon. A host writes the event to its log, for example the
366 /// [`Display`](std::fmt::Display) text of the event on standard error.
367 /// [`ServerEvent::is_warning`](crate::ServerEvent::is_warning) tells a
368 /// warning from an error. The server calls it also with no receive
369 /// policies. The default is `None`, which drops each event.
370 pub on_event: Option<EventSink>,
371}
372
373/// The debug text shows a callback that is set as `<callback>`, a
374/// client CA that is set as `<N bytes>`, the trusted proxies as networks,
375/// and the receive policies as the
376/// names of their client groups. It holds no auth item, so no digest and no
377/// user name.
378impl fmt::Debug for ServeOptions {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 f.debug_struct("ServeOptions")
381 .field("listen", &self.listen)
382 .field("tls", &self.tls)
383 .field(
384 "client_ca_pem",
385 &self
386 .client_ca_pem
387 .as_ref()
388 .map(|pem| format!("<{} bytes>", pem.len())),
389 )
390 .field(
391 "trusted_proxies",
392 &self
393 .trusted_proxies
394 .iter()
395 .map(ToString::to_string)
396 .collect::<Vec<_>>(),
397 )
398 .field("trusted_proxy_header", &self.trusted_proxy_header)
399 .field("trusted_proxy_client_cert", &self.trusted_proxy_client_cert)
400 .field("proxy_protocol", &self.proxy_protocol)
401 .field("body_timeout", &self.body_timeout)
402 .field(
403 "receive",
404 &self.receive.as_ref().map(|policies| {
405 policies
406 .access()
407 .groups()
408 .iter()
409 .map(|group| group.name())
410 .collect::<Vec<_>>()
411 }),
412 )
413 .field(
414 "allow_cleartext_credentials",
415 &self.allow_cleartext_credentials,
416 )
417 .field("parallel_uploads", &self.parallel_uploads)
418 .field("session_idle_timeout", &self.session_idle_timeout)
419 .field("max_sessions", &self.max_sessions)
420 .field("on_report", &self.on_report.as_ref().map(|_| "<callback>"))
421 .field("on_event", &self.on_event.as_ref().map(|_| "<callback>"))
422 .finish()
423 }
424}
425
426impl Default for ServeOptions {
427 fn default() -> ServeOptions {
428 let endpoint = EndpointOptions::default();
429 ServeOptions {
430 listen: vec![SocketAddr::from((Ipv4Addr::LOCALHOST, 8080))],
431 tls: None,
432 client_ca_pem: None,
433 trusted_proxies: Vec::new(),
434 trusted_proxy_header: None,
435 trusted_proxy_client_cert: None,
436 proxy_protocol: false,
437 body_timeout: Duration::from_secs(60),
438 receive: None,
439 allow_cleartext_credentials: false,
440 parallel_uploads: endpoint.parallel_uploads,
441 session_idle_timeout: endpoint.session_idle_timeout,
442 max_sessions: endpoint.max_sessions,
443 on_report: endpoint.on_report,
444 on_event: None,
445 }
446 }
447}
448
449#[cfg(test)]
450mod tests {
451 use ostrya::Checksum;
452
453 use super::*;
454 use crate::session::tests::TmpRepo;
455
456 #[test]
457 fn debug_redacts_the_key_and_the_passphrase() {
458 let tls = ServerTls {
459 cert_chain_pem: b"cert".to_vec(),
460 key_pem: b"secret key".to_vec(),
461 key_passphrase: Some("secret passphrase".into()),
462 };
463 let text = format!("{tls:?}");
464 assert!(!text.contains("secret"), "{text}");
465 assert!(text.contains("<10 bytes redacted>"), "{text}");
466 }
467
468 #[test]
469 fn debug_shows_no_auth_item_of_the_receive_policies() {
470 let token = Checksum::sha256(b"a-token").to_hex();
471 let password = Checksum::sha256(b"a-pass").to_hex();
472 let tmp = TmpRepo::new("options-debug");
473 let options = ServeOptions {
474 receive: Some(tmp.policies(&format!(
475 "[ex-ostrya client \"pushers\"]\n\
476 auth=token-sha256:{token};basic-sha256:alice:{password}\n\
477 allow=w:**\n"
478 ))),
479 ..ServeOptions::default()
480 };
481 let text = format!("{options:?}");
482 assert!(text.contains("\"pushers\""), "{text}");
483 assert!(!text.contains(&token), "{text}");
484 assert!(!text.contains(&password), "{text}");
485 assert!(!text.contains("alice"), "{text}");
486 }
487}