ostrya_server/server.rs
1//! The listeners and the connections of a server.
2
3use std::convert::Infallible;
4use std::net::{IpAddr, SocketAddr};
5use std::sync::Arc;
6use std::time::Duration;
7
8use futures_lite::future;
9use futures_rustls::TlsAcceptor;
10use futures_rustls::rustls::ServerConfig;
11use futures_rustls::rustls::server::danger::ClientCertVerifier;
12use hyper::Request;
13use hyper::body::Incoming;
14use hyper::header::HeaderName;
15use hyper::server::conn::{http1, http2};
16use hyper::service::service_fn;
17use ostrya::access::{AuthItem, ClientAccess, ReadAccess};
18use ostrya::{ArchiveView, Repo};
19use ostrya_fetch::{FuturesIo, RtExecutor, RtTimer};
20use ostrya_rt as rt;
21
22use crate::auth::{GroupAuth, Peer};
23use crate::cert::{ClientCert, ForwardedCerts};
24use crate::endpoint::{EndpointOptions, ReceiveEndpoint};
25use crate::error::{Error, Result};
26use crate::event::StaleSummaries;
27use crate::forwarded::Forwarding;
28use crate::options::ServeOptions;
29use crate::proxy_protocol::{self, Rewind};
30use crate::refs::Listings;
31use crate::router::{self, Clients};
32use crate::shutdown::{Shutdown, Trigger};
33use crate::stall::Stall;
34
35/// The time a TLS handshake has to complete.
36const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
37
38/// The time a connection has to send its PROXY protocol header.
39const PROXY_HEADER_TIMEOUT: Duration = Duration::from_secs(30);
40
41/// The time an HTTP/1.1 connection has to send the headers of a request.
42const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
43
44/// The most streams one HTTP/2 connection carries at the same time.
45const MAX_CONCURRENT_STREAMS: u32 = 32;
46
47/// The largest header list of one request that an HTTP/2 connection takes:
48/// 32 KiB.
49///
50/// The size of the list is the sum, for each header field, of the name, the
51/// value, and 32 bytes. The pseudo-header `:path` counts, so the request
52/// target counts. The client of a ref listing sends a target of at most
53/// 16 KiB, which comes after the base path of the mirror. The limit leaves
54/// 16 KiB for the base path and the other fields. A larger list gets 431.
55const MAX_HEADER_LIST_SIZE: u32 = 32 * 1024;
56
57/// The wait after an accept fails, for example when the process is out of
58/// descriptors, before the listener accepts again.
59const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
60
61/// A server with its listeners bound, ready to [`run`](Server::run).
62///
63/// # HTTP behavior
64///
65/// - The server answers `GET` and `HEAD`, except on the ref listing. Outside
66/// the receive endpoint and the ref listing, another method gets 405 with
67/// `Allow: GET, HEAD`.
68/// - With a receive endpoint, a request under the raw path prefix
69/// `/_ostrya/receive/v1/` goes to the endpoint if its method is not `GET`
70/// or `HEAD`. A `GET` or a `HEAD` under the prefix goes to the archive
71/// view and gets 404.
72/// - With receive policies, the server identifies the client of each
73/// request by the steps of [Authentication](ServeOptions#authentication),
74/// after the check of the method. A `GET` and a `HEAD` of the archive
75/// view, and a `GET` of the ref listing, get the status of a refusal, 401
76/// or 403, with an empty body and `Content-Length: 0`. A 401 carries the
77/// two `WWW-Authenticate` headers. Claims that do not parse refuse each
78/// read with 403, as [Claims](ServeOptions#claims) states.
79/// - The server serves the archive view and the ref listing with the
80/// [`ReadAccess`] of the item, as
81/// [`ArchiveView`](ArchiveView#read-access) and
82/// [`Repo::build_ref_listing`] state. A path that the client cannot read
83/// gets the 404 of an absent path.
84/// - `summary` and `summary.sig` give the files of the summary of the item
85/// of the client, which [`Repo::regenerate_summaries`] writes. An item
86/// with no summary gets 404. When the `.access` file of the item holds
87/// another digest than the access digest of the item, or does not exist
88/// while the file exists, the request gets 404, and the server reports one
89/// [`ServerEvent::StaleSummary`](crate::ServerEvent::StaleSummary) for
90/// each item in the life of the server. The server computes the digests
91/// at start, and reads the files for each request, so a new write of the
92/// summaries takes effect while the server runs. A 200 and a 404 of these
93/// two paths carry `Cache-Control: private`, because the body depends on
94/// the client. A 401 and a 403 do not.
95/// - With no receive policies, the server identifies no client. Each read
96/// gets the rights of the `anonymous` item under the two implicit groups of
97/// a config with no client group, with the collection id of the
98/// repository. Each local ref and each mirror ref are served, and
99/// `refs/remotes/` is not. `summary` and `summary.sig` give the files of
100/// the summary of the `anonymous` item of these implicit groups.
101/// - The HTTP layer removes a `#` fragment before the routing, so the server
102/// does not see a fragment.
103/// - The server percent-decodes the request path. Outside the ref listing,
104/// it ignores the query. If the path has a bad escape, a NUL, or bytes
105/// that are not UTF-8, the response is 404. The server decodes the path
106/// after it identifies the client.
107/// - The server answers the raw path `/_ostrya/refs/v1`, with and without a
108/// receive endpoint, with the bytes of [`Repo::build_ref_listing`]. The
109/// path must match exactly, and the server reads its query. Each pair of
110/// the query is `pattern=VALUE`, an entry of the local refs, or
111/// `collection=VALUE`, an entry of the collection refs by `ID/NAME`. The
112/// raw key is `pattern` or `collection`, and the value is percent-decoded,
113/// with `+` that stays `+`. The value is one entry of a
114/// [`ostrya::RefSelector`]: a ref pattern with an optional leading `!`.
115/// An entry has at most [`ostrya::MAX_REF_ENTRY_PARTS`] parts and
116/// [`ostrya::MAX_REF_ENTRY_LEN`] bytes. No `pattern` pair is an empty
117/// list, which selects all local refs. With one or more `collection`
118/// pairs, the listing holds the selected collection refs in
119/// `ostree.summary.collection-map`. With none, it holds no collection ref.
120/// The checks come in this order:
121/// 1. A method other than `GET`, `HEAD` included, gets 405 with
122/// `Allow: GET`.
123/// 2. The server identifies the client. A refusal gets its status.
124/// 3. A bad pair, a pair with another key, an entry over the limits of one
125/// entry, an entry that [`ostrya::RefSelector::parse`] refuses, and a
126/// query of more than 256 pairs of the two keys together
127/// ([`ostrya::MAX_REF_PATTERNS`]), get 400. An entry given two times
128/// for one key counts two times, and the server keeps it one time.
129/// 4. If 4 listings are in flight over all connections, the request gets
130/// 503 with `Retry-After: 1`. A listing is in flight from the start of
131/// its build until its response body drops.
132///
133/// Then the server builds the listing with the read rights of the client.
134/// Each error of the build gets 500. For each directory under
135/// `refs/mirrors/` whose name fails the collection-id rule, the server
136/// reports one [`ServerEvent::InvalidCollectionDir`](crate::ServerEvent::InvalidCollectionDir)
137/// to [`ServeOptions::on_event`] in the life of the server, and the
138/// listing leaves out the directory.
139/// A 400, a 405, a 500, and a 503 have an empty body. A 200 carries
140/// `Content-Length`, and the server sends the body in frames of at most
141/// 64 KiB under the body timeout.
142/// - A path that the view does not find gets 404 with an empty body. A path
143/// that the view refuses gets the same response, so a client cannot tell
144/// a private path from an absent one.
145/// - If the view returns an error, the response is 500 with an empty body.
146/// - A response with a known length carries `Content-Length`. A `.filez`
147/// built on request carries no `Content-Length`.
148/// - The server reads a file of the archive view in frames of at most
149/// 64 KiB, and never collects the file whole. The server builds a ref
150/// listing whole in memory, at most [`ostrya::MAX_REF_LISTING`] bytes, and
151/// sends it in frames of at most 64 KiB.
152/// - A `HEAD` takes the answer of [`ArchiveView::head`], which reads no byte
153/// of the file. For a `.filez` built on request, it reads no xattr and
154/// does no deflate work.
155/// - Plain HTTP serves HTTP/1.1. Over TLS, ALPN selects HTTP/2 or HTTP/1.1.
156/// An HTTP/2 connection carries at most 32 streams at the same time. It
157/// takes a header list of at most 32 KiB for one request, counted as the
158/// name, the value, and 32 bytes of each header field. A larger list gets
159/// 431.
160/// - A TLS handshake has 30 seconds to complete. An HTTP/1.1 connection has
161/// 30 seconds to send the headers of each request.
162/// - With a receive endpoint, the HTTP/2 windows are the windows of
163/// [`ReceiveEndpoint::h2_windows`]. A read-only server keeps the windows
164/// of hyper.
165/// - If a response body waits longer than [`ServeOptions::body_timeout`]
166/// for the client, the server ends its connection. If an HTTP/2 peer does
167/// not answer a ping within that time, the server ends the connection.
168/// - A body that streams gives at most 256 KiB in one run of polls. Then it
169/// yields to the executor.
170/// - With a client CA, the server verifies a client certificate against the
171/// CA. A client that presents no certificate also completes the handshake,
172/// and the other auth items identify it.
173/// - With [`ServeOptions::proxy_protocol`], each listener reads a PROXY
174/// protocol header, version 1 or 2, at the start of each connection,
175/// before the TLS handshake. A connection with no valid header, or with no
176/// header within 30 seconds, closes with no response. The bytes after the
177/// header go to the TLS handshake or to the HTTP layer.
178/// - The server reads the client address, the scheme, and a forwarded
179/// certificate from the headers of a trusted proxy, for each request.
180/// [Client address](ServeOptions#client-address) and
181/// [Forwarded certificate](ServeOptions#forwarded-certificate) state the
182/// rules.
183pub struct Server {
184 listeners: Vec<rt::TcpListener>,
185 addrs: Vec<SocketAddr>,
186 view: Arc<ArchiveView>,
187 repo: Repo,
188 clients: Arc<Clients>,
189 /// The ref listings of the server.
190 listings: Arc<Listings>,
191 /// The stale summaries that the server reported.
192 stale: StaleSummaries,
193 tls: Option<Arc<ServerConfig>>,
194 body_timeout: Duration,
195 proxy_protocol: bool,
196}
197
198/// Returns the receive endpoint of `opts` over `repo`, or `None` if `opts`
199/// has no receive policies. With policies, the function checks the options
200/// of the endpoint with [`ReceiveEndpoint::new`]. With no policies, it checks
201/// nothing. `verifier` is the verifier of the client CA, which checks a
202/// forwarded certificate.
203fn receive(
204 repo: &Repo,
205 opts: &ServeOptions,
206 verifier: Option<&Arc<dyn ClientCertVerifier>>,
207) -> Result<Option<Arc<ReceiveEndpoint<GroupAuth>>>> {
208 let Some(policies) = &opts.receive else {
209 return Ok(None);
210 };
211 let forwarding = opts
212 .trusted_proxy_header
213 .map(|header| Forwarding::new(opts.trusted_proxies.clone(), header));
214 let certs = match (&opts.trusted_proxy_client_cert, verifier) {
215 (Some(name), Some(verifier)) => {
216 let name = HeaderName::from_bytes(name.as_bytes())
217 .map_err(|_| Error::Options(format!("a bad header name '{name}'")))?;
218 Some(ForwardedCerts::new(name, verifier.clone()))
219 }
220 _ => None,
221 };
222 let auth = GroupAuth::new(policies.clone(), opts.allow_cleartext_credentials)
223 .with_proxies(forwarding, certs)
224 .with_events(opts.on_event.clone());
225 let options = EndpointOptions {
226 parallel_uploads: opts.parallel_uploads,
227 session_idle_timeout: opts.session_idle_timeout,
228 max_sessions: opts.max_sessions,
229 on_report: opts.on_report.clone(),
230 };
231 let endpoint = ReceiveEndpoint::new(repo.clone(), auth, options)?;
232 Ok(Some(Arc::new(endpoint)))
233}
234
235/// Binds the listeners of `opts` and returns a server over `repo`.
236///
237/// The function checks the options and builds the TLS configuration of
238/// `opts`. Then it binds each listen address of `opts`, in order. The server
239/// serves the archive view of `repo`. With [`ServeOptions::receive`], it also
240/// serves the receive endpoint over `repo`.
241///
242/// # Errors
243///
244/// The checks run in this order:
245///
246/// - [`Error::Options`] if `listen` is empty, or if `body_timeout` is zero.
247/// - [`Error::Options`] if `trusted_proxy_client_cert` is not a header name
248/// ([`ostrya::access::is_header_name`]).
249/// - [`Error::Options`] if `trusted_proxy_client_cert` is set and
250/// `client_ca_pem` is `None`, or `trusted_proxies` is empty.
251/// - [`Error::Options`] if `trusted_proxies` is not empty and
252/// `trusted_proxy_header` is `None`, or the reverse.
253/// - [`Error::Options`] if `client_ca_pem` is set, and `tls` and
254/// `trusted_proxy_client_cert` are `None`.
255/// - [`Error::Tls`] if `client_ca_pem` gives no verifier: it does not decode
256/// as PEM, holds no certificate, or holds a certificate that rustls
257/// refuses as a trust anchor.
258/// - [`Error::Options`] if `receive` is set and `parallel_uploads` is
259/// outside `1..=31`, or `session_idle_timeout` or `max_sessions` is zero.
260/// - [`Error::Tls`] if the TLS files give no server configuration.
261/// - [`Error::Bind`] if a listen address cannot be bound, or if its local
262/// address cannot be read.
263pub async fn bind(repo: Repo, opts: ServeOptions) -> Result<Server> {
264 if opts.listen.is_empty() {
265 return Err(Error::Options("no listen address".into()));
266 }
267 if opts.body_timeout.is_zero() {
268 return Err(Error::Options("a body timeout of zero".into()));
269 }
270 check_proxies(&opts)?;
271 let tls_error = |e| match e {
272 ostrya_fetch::Error::Fetch(message) => Error::Tls(message),
273 other => Error::Tls(other.to_string()),
274 };
275 let verifier = match &opts.client_ca_pem {
276 Some(pem) => Some(ostrya_fetch::client_cert_verifier(pem).map_err(tls_error)?),
277 None => None,
278 };
279 let clients = match receive(&repo, &opts, verifier.as_ref())? {
280 Some(endpoint) => Clients::Groups(endpoint),
281 None => Clients::Anonymous(anonymous_reads(&repo)),
282 };
283 let tls = match &opts.tls {
284 Some(tls) => Some(
285 ostrya_fetch::server_config(
286 &tls.cert_chain_pem,
287 &tls.key_pem,
288 tls.key_passphrase.as_deref(),
289 verifier,
290 )
291 .await
292 .map_err(tls_error)?,
293 ),
294 None => None,
295 };
296 let mut listeners = Vec::with_capacity(opts.listen.len());
297 let mut addrs = Vec::with_capacity(opts.listen.len());
298 for addr in opts.listen {
299 let bound = |source| Error::Bind { addr, source };
300 let listener = rt::TcpListener::bind(addr).await.map_err(bound)?;
301 addrs.push(listener.local_addr().map_err(bound)?);
302 listeners.push(listener);
303 }
304 Ok(Server {
305 listeners,
306 addrs,
307 view: Arc::new(ArchiveView::new(repo.clone())),
308 repo,
309 clients: Arc::new(clients),
310 listings: Arc::new(Listings::new(opts.on_event.clone())),
311 stale: StaleSummaries::new(opts.on_event),
312 tls,
313 body_timeout: opts.body_timeout,
314 proxy_protocol: opts.proxy_protocol,
315 })
316}
317
318/// Returns the read rights of each request of a server with no receive
319/// policies: the rights of the `anonymous` item under the two implicit
320/// groups of a config with no client group. The config has the collection id
321/// of `repo`, so `refs/mirrors/ID/NAME` of that id is in the local
322/// namespace.
323fn anonymous_reads(repo: &Repo) -> ReadAccess {
324 let access = ClientAccess::implicit(repo.config().collection_id());
325 ReadAccess::new(Arc::new(access), AuthItem::Anonymous, None)
326}
327
328/// Checks the fields of `opts` that go together: the client CA, the TLS
329/// files, the trusted proxies, and their headers. The doc of [`bind`] lists
330/// the refusals.
331fn check_proxies(opts: &ServeOptions) -> Result<()> {
332 if let Some(name) = &opts.trusted_proxy_client_cert {
333 if !ostrya::access::is_header_name(name) {
334 return Err(Error::Options(format!(
335 "the forwarded certificate header '{name}' is not a header name"
336 )));
337 }
338 if opts.client_ca_pem.is_none() {
339 return Err(Error::Options(
340 "a forwarded certificate header with no client CA".into(),
341 ));
342 }
343 if opts.trusted_proxies.is_empty() {
344 return Err(Error::Options(
345 "a forwarded certificate header with no trusted proxy".into(),
346 ));
347 }
348 }
349 match (opts.trusted_proxies.is_empty(), opts.trusted_proxy_header) {
350 (false, None) => {
351 return Err(Error::Options(
352 "trusted proxies with no header of the client address".into(),
353 ));
354 }
355 (true, Some(header)) => {
356 return Err(Error::Options(format!(
357 "the client address header {header} with no trusted proxy"
358 )));
359 }
360 _ => {}
361 }
362 if opts.client_ca_pem.is_some()
363 && opts.tls.is_none()
364 && opts.trusted_proxy_client_cert.is_none()
365 {
366 return Err(Error::Options(
367 "a client CA with no TLS and no forwarded certificate header".into(),
368 ));
369 }
370 Ok(())
371}
372
373/// Binds the listeners of `opts` and runs the server until the future drops.
374///
375/// The function calls [`bind`], then [`Server::run`].
376///
377/// # Errors
378///
379/// The errors of [`bind`](bind#errors). The future of [`Server::run`] never
380/// completes, so it gives no error.
381pub async fn serve(repo: Repo, opts: ServeOptions) -> Result<()> {
382 bind(repo, opts).await?.run().await
383}
384
385impl Server {
386 /// Returns the address of each listener, in the order of the options.
387 ///
388 /// If the options give port 0, the address holds the port that the
389 /// kernel chose.
390 pub fn local_addrs(&self) -> &[SocketAddr] {
391 &self.addrs
392 }
393
394 /// Serves connections until the future drops.
395 ///
396 /// Each listener accepts in a task of its own. The idle sweep of the
397 /// sessions runs in a task of its own. If an accept fails, the listener
398 /// accepts again after 100 ms.
399 ///
400 /// When the future drops, the server closes the listeners and ends each
401 /// connection that it accepted. It also stops the receive endpoint,
402 /// which aborts each session that does not commit. The
403 /// [session rules](ReceiveEndpoint#sessions) of the endpoint state the
404 /// other effects.
405 ///
406 /// # Errors
407 ///
408 /// The future never completes, so it returns no error.
409 pub async fn run(self) -> Result<()> {
410 let shutdown = Arc::new(Shutdown::default());
411 let _trigger = Trigger(shutdown.clone());
412 if let Some(endpoint) = self.clients.endpoint() {
413 let endpoint = endpoint.clone();
414 let stop = shutdown.wait();
415 drop(rt::spawn(async move {
416 future::or(endpoint.sweep(), stop).await;
417 endpoint.shutdown();
418 }));
419 }
420 let serving = Arc::new(Serving {
421 view: self.view,
422 repo: self.repo,
423 listings: self.listings,
424 stale: self.stale,
425 clients: self.clients,
426 tls: self.tls,
427 body_timeout: self.body_timeout,
428 proxy_protocol: self.proxy_protocol,
429 });
430 for listener in self.listeners {
431 let accept = accept_loop(listener, serving.clone(), shutdown.clone());
432 drop(rt::spawn(future::or(accept, shutdown.wait())));
433 }
434 std::future::pending().await
435 }
436}
437
438/// The state that each connection of a server shares.
439struct Serving {
440 view: Arc<ArchiveView>,
441 repo: Repo,
442 /// The ref listings of the server, over all connections.
443 listings: Arc<Listings>,
444 /// The stale summaries that the server reported, over all connections.
445 stale: StaleSummaries,
446 clients: Arc<Clients>,
447 tls: Option<Arc<ServerConfig>>,
448 body_timeout: Duration,
449 /// `true` if each connection starts with a PROXY protocol header.
450 proxy_protocol: bool,
451}
452
453/// Accepts connections on `listener` and serves each one in a task of its
454/// own, until `shutdown` fires.
455async fn accept_loop(listener: rt::TcpListener, serving: Arc<Serving>, shutdown: Arc<Shutdown>) {
456 loop {
457 match listener.accept().await {
458 Ok((stream, peer)) => {
459 let connection = connection(stream, peer, serving.clone());
460 let stop = shutdown.wait();
461 drop(rt::spawn(future::or(connection, stop)));
462 }
463 Err(_) => rt::Timer::after(ACCEPT_BACKOFF).await,
464 }
465 }
466}
467
468/// Serves one connection until it ends, or until one of its response bodies
469/// waits longer than the body timeout for the client.
470async fn connection(stream: rt::TcpStream, addr: SocketAddr, serving: Arc<Serving>) {
471 let stall = Stall::new(serving.body_timeout);
472 future::or(
473 serve_connection(stream, addr, serving, stall.clone()),
474 async move { stall.expired().await },
475 )
476 .await
477}
478
479/// Serves one connection from the peer address `addr`. An error ends this
480/// connection and no other. With the PROXY protocol, the function first reads
481/// the header, and its source address replaces `addr`. A connection with no
482/// valid header ends with no byte written. With client groups, each request
483/// carries the [`Peer`] of the connection in its extensions. The server then
484/// reads the client certificate of a TLS connection one time, for each
485/// request of the connection.
486async fn serve_connection(
487 stream: rt::TcpStream,
488 addr: SocketAddr,
489 serving: Arc<Serving>,
490 stall: Arc<Stall>,
491) {
492 let (addr, stream): (IpAddr, _) = if serving.proxy_protocol {
493 match proxy_protocol::read_header(stream, PROXY_HEADER_TIMEOUT).await {
494 Some((source, stream)) => (source.unwrap_or(addr.ip()), stream),
495 None => return,
496 }
497 } else {
498 (addr.ip(), Rewind::new(stream))
499 };
500 let shared = serving.clone();
501 let service = move |peer: Peer| {
502 service_fn(move |mut req: Request<Incoming>| {
503 let serving = shared.clone();
504 let stall = stall.clone();
505 if serving.clients.endpoint().is_some() {
506 req.extensions_mut().insert(peer.clone());
507 }
508 async move {
509 let response = router::handle(
510 &serving.view,
511 &serving.repo,
512 &serving.listings,
513 &serving.stale,
514 &serving.clients,
515 &stall,
516 req,
517 )
518 .await;
519 Ok::<_, Infallible>(response)
520 }
521 })
522 };
523 let Some(config) = serving.tls.clone() else {
524 let peer = Peer {
525 tls: false,
526 addr,
527 cert: None,
528 };
529 let served = http1::Builder::new()
530 .timer(RtTimer)
531 .header_read_timeout(HEADER_READ_TIMEOUT)
532 .serve_connection(FuturesIo::new(stream), service(peer));
533 let _ = served.await;
534 return;
535 };
536 let handshake = future::or(
537 async { Some(TlsAcceptor::from(config).accept(stream).await) },
538 async {
539 rt::Timer::after(HANDSHAKE_TIMEOUT).await;
540 None
541 },
542 );
543 let Some(Ok(stream)) = handshake.await else {
544 return;
545 };
546 let connection = stream.get_ref().1;
547 let h2 = connection.alpn_protocol() == Some(b"h2".as_slice());
548 let cert = match serving.clients.endpoint() {
549 Some(_) => connection
550 .peer_certificates()
551 .and_then(|chain| chain.first())
552 .map(|der| Arc::new(ClientCert::from_der(der.as_ref()))),
553 None => None,
554 };
555 let peer = Peer {
556 tls: true,
557 addr,
558 cert,
559 };
560 let service = service(peer);
561 let io = FuturesIo::new(stream);
562 if h2 {
563 let mut builder = http2::Builder::new(RtExecutor);
564 builder
565 .timer(RtTimer)
566 .max_concurrent_streams(MAX_CONCURRENT_STREAMS)
567 .max_header_list_size(MAX_HEADER_LIST_SIZE)
568 .keep_alive_interval(Some(serving.body_timeout / 2))
569 .keep_alive_timeout(serving.body_timeout);
570 // With a receive endpoint, the windows bound the bytes of the request
571 // bodies of one connection that the server did not read. A
572 // read-only server keeps the windows of hyper.
573 if let Some((stream, connection)) = serving.clients.endpoint().map(|e| e.h2_windows()) {
574 builder
575 .initial_stream_window_size(stream)
576 .initial_connection_window_size(connection);
577 }
578 let served = builder.serve_connection(io, service);
579 let _ = served.await;
580 } else {
581 let served = http1::Builder::new()
582 .timer(RtTimer)
583 .header_read_timeout(HEADER_READ_TIMEOUT)
584 .serve_connection(io, service);
585 let _ = served.await;
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use ostrya::access::{ForwardedHeader, IpNet};
592
593 use super::*;
594 use crate::options::ServerTls;
595 use crate::session::tests::TmpRepo;
596
597 const CA_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/ca.pem");
598
599 /// The options with the trusted proxies of 10.0.0.0/8, the header
600 /// `X-Forwarded-For`, a forwarded certificate header, and a client CA,
601 /// with no TLS.
602 fn proxied() -> ServeOptions {
603 ServeOptions {
604 client_ca_pem: Some(CA_PEM.to_vec()),
605 trusted_proxies: vec![IpNet::parse("10.0.0.0/8").unwrap()],
606 trusted_proxy_header: Some(ForwardedHeader::XForwardedFor),
607 trusted_proxy_client_cert: Some("X-Client-Cert".into()),
608 ..ServeOptions::default()
609 }
610 }
611
612 fn refused(opts: &ServeOptions) -> String {
613 match check_proxies(opts) {
614 Err(Error::Options(message)) => message,
615 other => panic!("{opts:?}: {other:?}"),
616 }
617 }
618
619 /// A client CA with a forwarded certificate header needs no TLS.
620 #[test]
621 fn a_client_ca_with_a_forwarded_certificate_header_needs_no_tls() {
622 check_proxies(&proxied()).unwrap();
623 let tmp = TmpRepo::new("bind-tls-item");
624 let opts = ServeOptions {
625 receive: Some(
626 tmp.policies("[ex-ostrya client \"c\"]\nauth=tls:ostrya test\nallow=w:**\n"),
627 ),
628 ..proxied()
629 };
630 check_proxies(&opts).unwrap();
631 }
632
633 /// Each field that needs another field is refused without it.
634 #[test]
635 fn each_field_needs_its_partner() {
636 type Change = fn(&mut ServeOptions);
637 let cases: [(Change, &str); 7] = [
638 (
639 |o| o.trusted_proxy_client_cert = Some("X Client".into()),
640 "the forwarded certificate header 'X Client' is not a header name",
641 ),
642 (
643 |o| o.trusted_proxy_client_cert = Some(String::new()),
644 "the forwarded certificate header '' is not a header name",
645 ),
646 (
647 |o| o.client_ca_pem = None,
648 "a forwarded certificate header with no client CA",
649 ),
650 (
651 |o| o.trusted_proxies.clear(),
652 "a forwarded certificate header with no trusted proxy",
653 ),
654 (
655 |o| o.trusted_proxy_header = None,
656 "trusted proxies with no header of the client address",
657 ),
658 (
659 |o| {
660 o.trusted_proxy_client_cert = None;
661 o.trusted_proxies.clear();
662 },
663 "the client address header x-forwarded-for with no trusted proxy",
664 ),
665 (
666 |o| o.trusted_proxy_client_cert = None,
667 "a client CA with no TLS and no forwarded certificate header",
668 ),
669 ];
670 for (change, message) in cases {
671 let mut opts = proxied();
672 change(&mut opts);
673 assert_eq!(refused(&opts), message);
674 }
675 let mut opts = proxied();
676 opts.trusted_proxy_client_cert = None;
677 opts.tls = Some(ServerTls {
678 cert_chain_pem: Vec::new(),
679 key_pem: Vec::new(),
680 key_passphrase: None,
681 });
682 check_proxies(&opts).unwrap();
683 check_proxies(&ServeOptions::default()).unwrap();
684 }
685
686 /// A `tls:` item needs no client CA.
687 #[test]
688 fn a_tls_item_needs_no_client_ca() {
689 let tmp = TmpRepo::new("bind-no-ca");
690 let opts = ServeOptions {
691 receive: Some(tmp.policies("[ex-ostrya client \"c\"]\nauth=tls:*\nallow=w:**\n")),
692 ..ServeOptions::default()
693 };
694 check_proxies(&opts).unwrap();
695 }
696
697 /// A client CA that gives no verifier is a TLS error of `bind`, before
698 /// it binds a listener.
699 #[test]
700 fn a_bad_client_ca_is_a_tls_error() {
701 let tmp = TmpRepo::new("bind-bad-ca");
702 let opts = ServeOptions {
703 client_ca_pem: Some(b"no certificate".to_vec()),
704 listen: vec!["127.0.0.1:0".parse().unwrap()],
705 ..proxied()
706 };
707 let err = rt::block_on(bind(tmp.repo.clone(), opts)).err().unwrap();
708 assert!(matches!(err, Error::Tls(_)), "{err}");
709 }
710}