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::{ReceivePolicy, ReceiveReport};
9
10use crate::endpoint::EndpointOptions;
11
12/// The PEM bytes of the server TLS files.
13///
14/// The caller reads each file once at start.
15#[derive(Clone, Eq, PartialEq)]
16pub struct ServerTls {
17 /// The server certificate, followed by any intermediates.
18 pub cert_chain_pem: Vec<u8>,
19 /// The private key of the certificate: plain, or encrypted PKCS#8 under
20 /// PBES2.
21 pub key_pem: Vec<u8>,
22 /// The passphrase of an encrypted key.
23 pub key_passphrase: Option<String>,
24 /// The CA against which the server verifies client certificates. The
25 /// server also serves a client that presents no certificate.
26 pub client_ca_pem: Option<Vec<u8>>,
27}
28
29/// The debug text holds no byte of the private key or of the passphrase. It
30/// shows the key as `<N bytes redacted>`, and a passphrase that is set as
31/// `<redacted>`.
32impl fmt::Debug for ServerTls {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 f.debug_struct("ServerTls")
35 .field("cert_chain_pem", &self.cert_chain_pem)
36 .field(
37 "key_pem",
38 &format!("<{} bytes redacted>", self.key_pem.len()),
39 )
40 .field(
41 "key_passphrase",
42 &self.key_passphrase.as_ref().map(|_| "<redacted>"),
43 )
44 .field("client_ca_pem", &self.client_ca_pem)
45 .finish()
46 }
47}
48
49/// The options of [`bind`](crate::bind).
50///
51/// The struct is `#[non_exhaustive]`, so a caller starts from
52/// [`ServeOptions::default`] and sets the fields.
53///
54/// The fields `parallel_uploads`, `session_idle_timeout`, `max_sessions`, and
55/// `on_report` go to the [`EndpointOptions`] of the receive endpoint. Their
56/// defaults are the defaults of [`EndpointOptions::default`]. If
57/// [`receive`](ServeOptions::receive) is `None`, [`bind`](crate::bind) does
58/// not read these four fields, `allow_anonymous_push`, `credentials`, or
59/// `allow_cleartext_credentials`. It then refuses no value of them.
60///
61/// # Authentication
62///
63/// The server runs the receive endpoint with built-in authentication methods.
64/// Each session gets the policy of [`receive`](ServeOptions::receive) and no
65/// hooks. The methods are:
66///
67/// - A bearer token, `Authorization: Bearer TOKEN`. It matches a line of
68/// [`credentials`](ServeOptions::credentials) by the SHA-256 digest of the
69/// token. An empty token matches no line.
70/// - A Basic credential, `Authorization: Basic` with the base64 of
71/// `NAME:TOKEN`. It matches the line of `NAME` by the digest of the token.
72/// The token runs from the first `:` to the end, so it can hold `:`. A
73/// credential with no `:`, a name that is not UTF-8, and an empty token
74/// match no line.
75/// - A client certificate that the TLS handshake verified against the client
76/// CA of [`tls`](ServeOptions::tls).
77/// - [`allow_anonymous_push`](ServeOptions::allow_anonymous_push), for a
78/// request with no credential.
79///
80/// [`bind`](crate::bind) refuses an endpoint with no method. If the server
81/// has no TLS, [`bind`](crate::bind) also refuses an endpoint whose one method
82/// is the credential file, unless
83/// [`allow_cleartext_credentials`](ServeOptions::allow_cleartext_credentials)
84/// is set. No request can pass that method, because the endpoint refuses
85/// each credential over plain HTTP.
86///
87/// The server compares the digest of a request with the digest of each line
88/// in constant time. It does not stop at a match. The checks run in this
89/// order:
90///
91/// 1. A request with more than one `Authorization` header gets 401.
92/// 2. If the connection has no TLS, a bearer or Basic credential gets 403,
93/// unless
94/// [`allow_cleartext_credentials`](ServeOptions::allow_cleartext_credentials)
95/// is set. This check also applies where anonymous push is allowed.
96/// 3. An `Authorization` header that matches no line gets 401, also when the
97/// request has a client certificate.
98/// 4. A request with no `Authorization` header gets the first result that
99/// applies:
100/// - the owner of its client certificate
101/// - the owner `anonymous`, if anonymous push is allowed
102/// - 401, if the server has credential lines
103/// - 403, if the client CA is the one method of the server
104///
105/// Each 401 of the built-in methods carries two headers:
106/// `WWW-Authenticate: Bearer realm="ostrya"` and
107/// `WWW-Authenticate: Basic realm="ostrya"`.
108///
109/// The owner key of a request has a prefix for each method:
110///
111/// - `token:NAME` for a bearer token or a Basic credential, where `NAME` is
112/// the name of its credential line.
113/// - `cert:HEX` for a client certificate, where `HEX` is the SHA-256 digest
114/// of its DER bytes in lowercase hex.
115/// - `anonymous` for anonymous push.
116///
117/// A name can be equal to a digest, so the prefix keeps the keys of two
118/// methods apart. A bearer token and a Basic credential of one line give one
119/// key.
120#[derive(Clone)]
121#[non_exhaustive]
122pub struct ServeOptions {
123 /// The addresses to listen on.
124 ///
125 /// Port 0 lets the kernel choose a port, which
126 /// [`Server::local_addrs`](crate::Server::local_addrs) reports.
127 /// [`bind`](crate::bind) refuses an empty list. The default is
128 /// `127.0.0.1:8080`.
129 pub listen: Vec<SocketAddr>,
130 /// The TLS files, or `None` for plain HTTP. The default is `None`.
131 pub tls: Option<ServerTls>,
132 /// The longest time that a response body waits for the client to take its
133 /// next bytes.
134 ///
135 /// If a body waits longer, its connection ends. The bodies of the
136 /// connection then drop and release the files and the compressors that
137 /// they hold. An HTTP/2 connection sends a ping after half this time with
138 /// no frame from the peer. It ends if the peer does not answer within
139 /// this time.
140 ///
141 /// A body that waits for its own reader, for example for a compressor of
142 /// the archive view, does not wait for the client. The time does not
143 /// count for such a body until it gives its next frame.
144 ///
145 /// The default is 60 seconds. [`bind`](crate::bind) refuses zero.
146 pub body_timeout: Duration,
147 /// The receive policy of the receive endpoint, or `None` for a read-only
148 /// server.
149 ///
150 /// The default is `None`. Every session of the endpoint shares the
151 /// policy. The server does not read the policy or a repository setting of
152 /// the endpoint again while it runs. A change takes effect at the next
153 /// start.
154 pub receive: Option<Arc<ReceivePolicy>>,
155 /// The switch that lets a request with no credential push.
156 ///
157 /// The default is `false`. The switch is one of the methods in
158 /// [Authentication](ServeOptions#authentication).
159 pub allow_anonymous_push: bool,
160 /// The bytes of the push credential file.
161 ///
162 /// The default is `None`. Each line of the file holds one credential,
163 /// `NAME:HEX`. `NAME` is one or more visible ASCII characters other than
164 /// `:`. `HEX` is the SHA-256 digest of the secret in 64 lowercase hex
165 /// digits.
166 ///
167 /// A line that starts with `#` and an empty line hold no credential. A
168 /// file with no credential line gives no authentication method.
169 ///
170 /// If [`receive`](ServeOptions::receive) is set, [`bind`](crate::bind)
171 /// parses the file. A read-only server does not read the field. A
172 /// malformed line, a name on two lines, and a digest on two lines are
173 /// [`Error::Credentials`](crate::Error::Credentials). This error names
174 /// the line by its number and holds no byte of the line.
175 pub credentials: Option<Vec<u8>>,
176 /// The switch that takes a bearer or Basic credential on a connection
177 /// without TLS.
178 ///
179 /// The default is `false`. If the switch is `false`, the endpoint refuses
180 /// such a credential with 403. A server on a loopback address or behind a
181 /// proxy that terminates TLS can set it. A read-only server does not read
182 /// the field.
183 pub allow_cleartext_credentials: bool,
184 /// The number of object streams of one session, as in
185 /// [`EndpointOptions::parallel_uploads`].
186 ///
187 /// The default is 4.
188 pub parallel_uploads: u32,
189 /// The idle timeout of a session, as in
190 /// [`EndpointOptions::session_idle_timeout`].
191 ///
192 /// The default is 300 seconds.
193 pub session_idle_timeout: Duration,
194 /// The most sessions open at the same time, as in
195 /// [`EndpointOptions::max_sessions`].
196 ///
197 /// The default is 16.
198 pub max_sessions: usize,
199 /// The callback for the report of a committed session, as in
200 /// [`EndpointOptions::on_report`].
201 pub on_report: Option<Arc<dyn Fn(ReceiveReport) + Send + Sync>>,
202}
203
204/// The debug text holds no byte of the credential file. It shows the file as
205/// `<N bytes redacted>`, and a report callback that is set as `<callback>`.
206impl fmt::Debug for ServeOptions {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 f.debug_struct("ServeOptions")
209 .field("listen", &self.listen)
210 .field("tls", &self.tls)
211 .field("body_timeout", &self.body_timeout)
212 .field("receive", &self.receive)
213 .field("allow_anonymous_push", &self.allow_anonymous_push)
214 .field(
215 "credentials",
216 &self
217 .credentials
218 .as_ref()
219 .map(|c| format!("<{} bytes redacted>", c.len())),
220 )
221 .field(
222 "allow_cleartext_credentials",
223 &self.allow_cleartext_credentials,
224 )
225 .field("parallel_uploads", &self.parallel_uploads)
226 .field("session_idle_timeout", &self.session_idle_timeout)
227 .field("max_sessions", &self.max_sessions)
228 .field("on_report", &self.on_report.as_ref().map(|_| "<callback>"))
229 .finish()
230 }
231}
232
233impl Default for ServeOptions {
234 fn default() -> ServeOptions {
235 let endpoint = EndpointOptions::default();
236 ServeOptions {
237 listen: vec![SocketAddr::from((Ipv4Addr::LOCALHOST, 8080))],
238 tls: None,
239 body_timeout: Duration::from_secs(60),
240 receive: None,
241 allow_anonymous_push: false,
242 credentials: None,
243 allow_cleartext_credentials: false,
244 parallel_uploads: endpoint.parallel_uploads,
245 session_idle_timeout: endpoint.session_idle_timeout,
246 max_sessions: endpoint.max_sessions,
247 on_report: endpoint.on_report,
248 }
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn debug_redacts_the_key_and_the_passphrase() {
258 let tls = ServerTls {
259 cert_chain_pem: b"cert".to_vec(),
260 key_pem: b"secret key".to_vec(),
261 key_passphrase: Some("secret passphrase".into()),
262 client_ca_pem: None,
263 };
264 let text = format!("{tls:?}");
265 assert!(!text.contains("secret"), "{text}");
266 assert!(text.contains("<10 bytes redacted>"), "{text}");
267 }
268
269 #[test]
270 fn debug_states_the_credentials_by_their_length() {
271 let opts = ServeOptions {
272 credentials: Some(b"alice:secret".to_vec()),
273 ..ServeOptions::default()
274 };
275 let text = format!("{opts:?}");
276 assert!(!text.contains("secret"), "{text}");
277 assert!(!text.contains("alice"), "{text}");
278 assert!(text.contains("<12 bytes redacted>"), "{text}");
279 }
280}