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