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