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