use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use futures_lite::future;
use futures_rustls::TlsAcceptor;
use futures_rustls::rustls::ServerConfig;
use futures_rustls::rustls::server::danger::ClientCertVerifier;
use hyper::Request;
use hyper::body::Incoming;
use hyper::header::HeaderName;
use hyper::server::conn::{http1, http2};
use hyper::service::service_fn;
use ostrya::access::{AuthItem, ClientAccess, ReadAccess};
use ostrya::{ArchiveView, Repo};
use ostrya_fetch::{FuturesIo, RtExecutor, RtTimer};
use ostrya_rt as rt;
use crate::auth::{GroupAuth, Peer};
use crate::cert::{ClientCert, ForwardedCerts};
use crate::endpoint::{EndpointOptions, ReceiveEndpoint};
use crate::error::{Error, Result};
use crate::event::StaleSummaries;
use crate::forwarded::Forwarding;
use crate::options::ServeOptions;
use crate::proxy_protocol::{self, Rewind};
use crate::refs::Listings;
use crate::router::{self, Clients};
use crate::shutdown::{Shutdown, Trigger};
use crate::stall::Stall;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
const PROXY_HEADER_TIMEOUT: Duration = Duration::from_secs(30);
const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_CONCURRENT_STREAMS: u32 = 32;
const MAX_HEADER_LIST_SIZE: u32 = 32 * 1024;
const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
pub struct Server {
listeners: Vec<rt::TcpListener>,
addrs: Vec<SocketAddr>,
view: Arc<ArchiveView>,
repo: Repo,
clients: Arc<Clients>,
listings: Arc<Listings>,
stale: StaleSummaries,
tls: Option<Arc<ServerConfig>>,
body_timeout: Duration,
proxy_protocol: bool,
}
fn receive(
repo: &Repo,
opts: &ServeOptions,
verifier: Option<&Arc<dyn ClientCertVerifier>>,
) -> Result<Option<Arc<ReceiveEndpoint<GroupAuth>>>> {
let Some(policies) = &opts.receive else {
return Ok(None);
};
let forwarding = opts
.trusted_proxy_header
.map(|header| Forwarding::new(opts.trusted_proxies.clone(), header));
let certs = match (&opts.trusted_proxy_client_cert, verifier) {
(Some(name), Some(verifier)) => {
let name = HeaderName::from_bytes(name.as_bytes())
.map_err(|_| Error::Options(format!("a bad header name '{name}'")))?;
Some(ForwardedCerts::new(name, verifier.clone()))
}
_ => None,
};
let auth = GroupAuth::new(policies.clone(), opts.allow_cleartext_credentials)
.with_proxies(forwarding, certs)
.with_events(opts.on_event.clone());
let options = EndpointOptions {
parallel_uploads: opts.parallel_uploads,
session_idle_timeout: opts.session_idle_timeout,
max_sessions: opts.max_sessions,
on_report: opts.on_report.clone(),
};
let endpoint = ReceiveEndpoint::new(repo.clone(), auth, options)?;
Ok(Some(Arc::new(endpoint)))
}
pub async fn bind(repo: Repo, opts: ServeOptions) -> Result<Server> {
if opts.listen.is_empty() {
return Err(Error::Options("no listen address".into()));
}
if opts.body_timeout.is_zero() {
return Err(Error::Options("a body timeout of zero".into()));
}
check_proxies(&opts)?;
let tls_error = |e| match e {
ostrya_fetch::Error::Fetch(message) => Error::Tls(message),
other => Error::Tls(other.to_string()),
};
let verifier = match &opts.client_ca_pem {
Some(pem) => Some(ostrya_fetch::client_cert_verifier(pem).map_err(tls_error)?),
None => None,
};
let clients = match receive(&repo, &opts, verifier.as_ref())? {
Some(endpoint) => Clients::Groups(endpoint),
None => Clients::Anonymous(anonymous_reads(&repo)),
};
let tls = match &opts.tls {
Some(tls) => Some(
ostrya_fetch::server_config(
&tls.cert_chain_pem,
&tls.key_pem,
tls.key_passphrase.as_deref(),
verifier,
)
.await
.map_err(tls_error)?,
),
None => None,
};
let mut listeners = Vec::with_capacity(opts.listen.len());
let mut addrs = Vec::with_capacity(opts.listen.len());
for addr in opts.listen {
let bound = |source| Error::Bind { addr, source };
let listener = rt::TcpListener::bind(addr).await.map_err(bound)?;
addrs.push(listener.local_addr().map_err(bound)?);
listeners.push(listener);
}
Ok(Server {
listeners,
addrs,
view: Arc::new(ArchiveView::new(repo.clone())),
repo,
clients: Arc::new(clients),
listings: Arc::new(Listings::new(opts.on_event.clone())),
stale: StaleSummaries::new(opts.on_event),
tls,
body_timeout: opts.body_timeout,
proxy_protocol: opts.proxy_protocol,
})
}
fn anonymous_reads(repo: &Repo) -> ReadAccess {
let access = ClientAccess::implicit(repo.config().collection_id());
ReadAccess::new(Arc::new(access), AuthItem::Anonymous, None)
}
fn check_proxies(opts: &ServeOptions) -> Result<()> {
if let Some(name) = &opts.trusted_proxy_client_cert {
if !ostrya::access::is_header_name(name) {
return Err(Error::Options(format!(
"the forwarded certificate header '{name}' is not a header name"
)));
}
if opts.client_ca_pem.is_none() {
return Err(Error::Options(
"a forwarded certificate header with no client CA".into(),
));
}
if opts.trusted_proxies.is_empty() {
return Err(Error::Options(
"a forwarded certificate header with no trusted proxy".into(),
));
}
}
match (opts.trusted_proxies.is_empty(), opts.trusted_proxy_header) {
(false, None) => {
return Err(Error::Options(
"trusted proxies with no header of the client address".into(),
));
}
(true, Some(header)) => {
return Err(Error::Options(format!(
"the client address header {header} with no trusted proxy"
)));
}
_ => {}
}
if opts.client_ca_pem.is_some()
&& opts.tls.is_none()
&& opts.trusted_proxy_client_cert.is_none()
{
return Err(Error::Options(
"a client CA with no TLS and no forwarded certificate header".into(),
));
}
Ok(())
}
pub async fn serve(repo: Repo, opts: ServeOptions) -> Result<()> {
bind(repo, opts).await?.run().await
}
impl Server {
pub fn local_addrs(&self) -> &[SocketAddr] {
&self.addrs
}
pub async fn run(self) -> Result<()> {
let shutdown = Arc::new(Shutdown::default());
let _trigger = Trigger(shutdown.clone());
if let Some(endpoint) = self.clients.endpoint() {
let endpoint = endpoint.clone();
let stop = shutdown.wait();
drop(rt::spawn(async move {
future::or(endpoint.sweep(), stop).await;
endpoint.shutdown();
}));
}
let serving = Arc::new(Serving {
view: self.view,
repo: self.repo,
listings: self.listings,
stale: self.stale,
clients: self.clients,
tls: self.tls,
body_timeout: self.body_timeout,
proxy_protocol: self.proxy_protocol,
});
for listener in self.listeners {
let accept = accept_loop(listener, serving.clone(), shutdown.clone());
drop(rt::spawn(future::or(accept, shutdown.wait())));
}
std::future::pending().await
}
}
struct Serving {
view: Arc<ArchiveView>,
repo: Repo,
listings: Arc<Listings>,
stale: StaleSummaries,
clients: Arc<Clients>,
tls: Option<Arc<ServerConfig>>,
body_timeout: Duration,
proxy_protocol: bool,
}
async fn accept_loop(listener: rt::TcpListener, serving: Arc<Serving>, shutdown: Arc<Shutdown>) {
loop {
match listener.accept().await {
Ok((stream, peer)) => {
let connection = connection(stream, peer, serving.clone());
let stop = shutdown.wait();
drop(rt::spawn(future::or(connection, stop)));
}
Err(_) => rt::Timer::after(ACCEPT_BACKOFF).await,
}
}
}
async fn connection(stream: rt::TcpStream, addr: SocketAddr, serving: Arc<Serving>) {
let stall = Stall::new(serving.body_timeout);
future::or(
serve_connection(stream, addr, serving, stall.clone()),
async move { stall.expired().await },
)
.await
}
async fn serve_connection(
stream: rt::TcpStream,
addr: SocketAddr,
serving: Arc<Serving>,
stall: Arc<Stall>,
) {
let (addr, stream): (IpAddr, _) = if serving.proxy_protocol {
match proxy_protocol::read_header(stream, PROXY_HEADER_TIMEOUT).await {
Some((source, stream)) => (source.unwrap_or(addr.ip()), stream),
None => return,
}
} else {
(addr.ip(), Rewind::new(stream))
};
let shared = serving.clone();
let service = move |peer: Peer| {
service_fn(move |mut req: Request<Incoming>| {
let serving = shared.clone();
let stall = stall.clone();
if serving.clients.endpoint().is_some() {
req.extensions_mut().insert(peer.clone());
}
async move {
let response = router::handle(
&serving.view,
&serving.repo,
&serving.listings,
&serving.stale,
&serving.clients,
&stall,
req,
)
.await;
Ok::<_, Infallible>(response)
}
})
};
let Some(config) = serving.tls.clone() else {
let peer = Peer {
tls: false,
addr,
cert: None,
};
let served = http1::Builder::new()
.timer(RtTimer)
.header_read_timeout(HEADER_READ_TIMEOUT)
.serve_connection(FuturesIo::new(stream), service(peer));
let _ = served.await;
return;
};
let handshake = future::or(
async { Some(TlsAcceptor::from(config).accept(stream).await) },
async {
rt::Timer::after(HANDSHAKE_TIMEOUT).await;
None
},
);
let Some(Ok(stream)) = handshake.await else {
return;
};
let connection = stream.get_ref().1;
let h2 = connection.alpn_protocol() == Some(b"h2".as_slice());
let cert = match serving.clients.endpoint() {
Some(_) => connection
.peer_certificates()
.and_then(|chain| chain.first())
.map(|der| Arc::new(ClientCert::from_der(der.as_ref()))),
None => None,
};
let peer = Peer {
tls: true,
addr,
cert,
};
let service = service(peer);
let io = FuturesIo::new(stream);
if h2 {
let mut builder = http2::Builder::new(RtExecutor);
builder
.timer(RtTimer)
.max_concurrent_streams(MAX_CONCURRENT_STREAMS)
.max_header_list_size(MAX_HEADER_LIST_SIZE)
.keep_alive_interval(Some(serving.body_timeout / 2))
.keep_alive_timeout(serving.body_timeout);
if let Some((stream, connection)) = serving.clients.endpoint().map(|e| e.h2_windows()) {
builder
.initial_stream_window_size(stream)
.initial_connection_window_size(connection);
}
let served = builder.serve_connection(io, service);
let _ = served.await;
} else {
let served = http1::Builder::new()
.timer(RtTimer)
.header_read_timeout(HEADER_READ_TIMEOUT)
.serve_connection(io, service);
let _ = served.await;
}
}
#[cfg(test)]
mod tests {
use ostrya::access::{ForwardedHeader, IpNet};
use super::*;
use crate::options::ServerTls;
use crate::session::tests::TmpRepo;
const CA_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/ca.pem");
fn proxied() -> ServeOptions {
ServeOptions {
client_ca_pem: Some(CA_PEM.to_vec()),
trusted_proxies: vec![IpNet::parse("10.0.0.0/8").unwrap()],
trusted_proxy_header: Some(ForwardedHeader::XForwardedFor),
trusted_proxy_client_cert: Some("X-Client-Cert".into()),
..ServeOptions::default()
}
}
fn refused(opts: &ServeOptions) -> String {
match check_proxies(opts) {
Err(Error::Options(message)) => message,
other => panic!("{opts:?}: {other:?}"),
}
}
#[test]
fn a_client_ca_with_a_forwarded_certificate_header_needs_no_tls() {
check_proxies(&proxied()).unwrap();
let tmp = TmpRepo::new("bind-tls-item");
let opts = ServeOptions {
receive: Some(
tmp.policies("[ex-ostrya client \"c\"]\nauth=tls:ostrya test\nallow=w:**\n"),
),
..proxied()
};
check_proxies(&opts).unwrap();
}
#[test]
fn each_field_needs_its_partner() {
type Change = fn(&mut ServeOptions);
let cases: [(Change, &str); 7] = [
(
|o| o.trusted_proxy_client_cert = Some("X Client".into()),
"the forwarded certificate header 'X Client' is not a header name",
),
(
|o| o.trusted_proxy_client_cert = Some(String::new()),
"the forwarded certificate header '' is not a header name",
),
(
|o| o.client_ca_pem = None,
"a forwarded certificate header with no client CA",
),
(
|o| o.trusted_proxies.clear(),
"a forwarded certificate header with no trusted proxy",
),
(
|o| o.trusted_proxy_header = None,
"trusted proxies with no header of the client address",
),
(
|o| {
o.trusted_proxy_client_cert = None;
o.trusted_proxies.clear();
},
"the client address header x-forwarded-for with no trusted proxy",
),
(
|o| o.trusted_proxy_client_cert = None,
"a client CA with no TLS and no forwarded certificate header",
),
];
for (change, message) in cases {
let mut opts = proxied();
change(&mut opts);
assert_eq!(refused(&opts), message);
}
let mut opts = proxied();
opts.trusted_proxy_client_cert = None;
opts.tls = Some(ServerTls {
cert_chain_pem: Vec::new(),
key_pem: Vec::new(),
key_passphrase: None,
});
check_proxies(&opts).unwrap();
check_proxies(&ServeOptions::default()).unwrap();
}
#[test]
fn a_tls_item_needs_no_client_ca() {
let tmp = TmpRepo::new("bind-no-ca");
let opts = ServeOptions {
receive: Some(tmp.policies("[ex-ostrya client \"c\"]\nauth=tls:*\nallow=w:**\n")),
..ServeOptions::default()
};
check_proxies(&opts).unwrap();
}
#[test]
fn a_bad_client_ca_is_a_tls_error() {
let tmp = TmpRepo::new("bind-bad-ca");
let opts = ServeOptions {
client_ca_pem: Some(b"no certificate".to_vec()),
listen: vec!["127.0.0.1:0".parse().unwrap()],
..proxied()
};
let err = rt::block_on(bind(tmp.repo.clone(), opts)).err().unwrap();
assert!(matches!(err, Error::Tls(_)), "{err}");
}
}