Merge branch 'fix/listener-and-token-safety' into integration/phase2

This commit is contained in:
ari committed 2026-10-16 10:04:58 -04:00
commit 695eb6778e
11 files changed
+397 -146

No files matched your search

Generated
+1
View File
@@ -2820,6 +2820,7 @@ dependencies = [
"futures",
"hyper-util",
"jiff",
"libc",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry_sdk",
+1
View File
@@ -22,6 +22,7 @@ futures = "0.3.34"
async-trait = "0.1.92"
anyhow = "1.0.104"
thiserror = "2.0.21"
libc = "0.2"
# HTTP
axum = "0.8.9"
+3 -2
View File
@@ -40,7 +40,7 @@ Startup refuses `auth.enabled = false` on a non-loopback `server.bind`.
All `/api/v1/*` and `/mcp` requests need `Authorization: Bearer <token>`. `/healthz` is public. Tokens are stored hashed (sha256) in SQLite, and the plaintext is shown once.
Run the token CLI **as the service user** so the database keeps the right owner and mode:
Run the token CLI **as the service user** (the unit's `User=skyg`), i.e. `sudo -u <service user> slinuxm token create <name>`. The CLI refuses to run (with the matching `sudo -u <owner> ...` hint) when the effective uid, root included, does not own the database file or, if it does not exist yet, its existing state directory, so it cannot create or modify state owned by another user:
```sh
sudo -u skyg slinuxm token create my-laptop --config /etc/skyg-linux-tracker.toml
@@ -54,6 +54,7 @@ Notes:
- `auth.db_path` must stay under the unit's `StateDirectory` (`/var/lib/skyg-linux-tracker`). The unit uses `ProtectSystem=strict`, so any other location needs a matching `ReadWritePaths=`.
- `token create` needs the state directory to exist, so start the service once first (systemd creates it with the right owner), then run the CLI as `skyg`.
- A state directory the server creates itself is made 0700 and the database file 0600 from creation. An existing directory is never chmod'd; a group/world-accessible one only logs a warning.
## REST
@@ -135,7 +136,7 @@ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days
curl --cacert cert.pem -H "Authorization: Bearer $TOKEN" https://localhost:9109/api/v1/systemd/units
```
Rotation: replace the files and send `SIGHUP` (`kill -HUP $(pidof slinuxm)`, or `systemctl kill -s HUP <unit>`). New connections get the new certificate; established ones are not dropped. The certificate and key are read as two separate files, so rotation tooling must send SIGHUP only after BOTH are in place; if the pair is unreadable or mismatched (for example the cert was replaced but the key not yet), the old certificate stays, an error is logged, and you send SIGHUP again once the files are consistent. Any intermediate certificates must be in the `cert_file` chain. The TLS listener is HTTP/1.1 only, caps concurrent connections at 1024 and closes connections that send no request header within 30 seconds. SIGHUP is harmless when TLS is disabled (it is logged and ignored). For ACME, point `cert_file` and `key_file` at the client's output (for example certbot's `live/<name>/fullchain.pem` and `privkey.pem`, or the NixOS `security.acme` directory) and send SIGHUP from the renewal hook. For sops-nix or systemd `LoadCredential`, point at the decrypted or credential path (`/run/credentials/<unit>/...`) so the service user needs no access to the original key file.
Rotation: replace the files and send `SIGHUP` (`kill -HUP $(pidof slinuxm)`, or `systemctl kill -s HUP <unit>`). New connections get the new certificate; established ones are not dropped. The certificate and key are read as two separate files, so rotation tooling must send SIGHUP only after BOTH are in place; if the pair is unreadable or mismatched (for example the cert was replaced but the key not yet), the old certificate stays, an error is logged, and you send SIGHUP again once the files are consistent. Any intermediate certificates must be in the `cert_file` chain. Both the TLS and the plain listener are HTTP/1.1 only, share one accept loop, cap concurrent connections at 1024 and close connections that send no request header within 30 seconds. SIGHUP is harmless when TLS is disabled (it is logged and ignored). For ACME, point `cert_file` and `key_file` at the client's output (for example certbot's `live/<name>/fullchain.pem` and `privkey.pem`, or the NixOS `security.acme` directory) and send SIGHUP from the renewal hook. For sops-nix or systemd `LoadCredential`, point at the decrypted or credential path (`/run/credentials/<unit>/...`) so the service user needs no access to the original key file.
## Docker access
+2
View File
@@ -148,6 +148,8 @@ pub async fn verify(pool: &SqlitePool, token: &str) -> Result<bool> {
}
pub async fn run(cmd: TokenCmd, config: &Config) -> Result<()> {
#[cfg(unix)]
crate::db::ensure_token_cli_owner(&config.auth.db_path)?;
let pool = crate::db::open(config).await?;
match cmd {
TokenCmd::Create { name } => {
+145 -8
View File
@@ -14,6 +14,7 @@ pub async fn open(config: &Config) -> Result<SqlitePool> {
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
create_private_dir(dir)?;
}
precreate_private_file(path)?;
let opts = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
@@ -57,6 +58,9 @@ pub async fn migrate(pool: &SqlitePool) -> Result<()> {
.context("running database migrations")
}
/// Create `dir` (and missing parents) as 0700. A directory that already
/// exists is never chmod'd (it may be systemd's `StateDirectory` or an
/// admin's choice); a group/world-accessible one only draws a warning.
fn create_private_dir(dir: &Path) -> Result<()> {
if dir.exists() {
#[cfg(unix)]
@@ -64,12 +68,8 @@ fn create_private_dir(dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(dir)?.permissions().mode();
if mode & 0o077 != 0 {
if let Err(e) =
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
{
tracing::warn!(dir = %dir.display(), mode = format!("{:o}", mode & 0o777), error = %e,
"state directory is accessible to others and could not be tightened");
}
tracing::warn!(dir = %dir.display(), mode = format!("{:o}", mode & 0o777),
"state directory is accessible to group/others; consider chmod 0700");
}
}
return Ok(());
@@ -85,6 +85,72 @@ fn create_private_dir(dir: &Path) -> Result<()> {
.with_context(|| format!("creating {}", dir.display()))
}
/// Create the database file as 0600 if missing, so it never exists with
/// umask-default permissions (sqlx would create it 0644 under umask 022).
fn precreate_private_file(path: &Path) -> Result<()> {
let mut o = std::fs::OpenOptions::new();
o.write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
o.mode(0o600);
}
o.open(path)
.map(drop)
.with_context(|| format!("creating token database {}", path.display()))
}
/// Effective uid of this process.
#[cfg(unix)]
pub fn effective_uid() -> u32 {
// SAFETY: geteuid has no preconditions and cannot fail.
unsafe { libc::geteuid() }
}
/// Pure ownership rule: the caller must own the state it is about to touch.
/// Root gets no exemption: it must not create or modify root-owned state next
/// to a service user's.
pub fn check_owner(euid: u32, owner: u32, path: &Path) -> Result<()> {
if euid == owner {
return Ok(());
}
let who = user_name(owner).unwrap_or_else(|| format!("#{owner}"));
anyhow::bail!(
"{} is owned by uid {owner} but slinuxm is running as uid {euid}; \
run it as the owner instead: sudo -u {who} slinuxm token ...",
path.display()
)
}
fn user_name(uid: u32) -> Option<String> {
let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
passwd.lines().find_map(|l| {
let mut f = l.split(':');
let name = f.next()?;
(f.nth(1)? == uid.to_string()).then(|| name.to_owned())
})
}
/// For the token CLI: refuse to run unless the effective uid owns the
/// database file, or (when it does not exist yet) its existing parent
/// directory. A missing directory is fine; we will create it as ourselves.
#[cfg(unix)]
pub fn ensure_token_cli_owner(db_path: &Path) -> Result<()> {
use std::os::unix::fs::MetadataExt;
let euid = effective_uid();
if let Ok(m) = std::fs::metadata(db_path) {
return check_owner(euid, m.uid(), db_path);
}
let parent = match db_path.parent() {
Some(p) if !p.as_os_str().is_empty() => p,
_ => Path::new("."),
};
match std::fs::metadata(parent) {
Ok(m) => check_owner(euid, m.uid(), parent),
Err(_) => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -120,7 +186,7 @@ mod tests {
}
assert!(tmp.join("state/db.sqlite").exists());
}
// a looser existing dir is tightened on reopen
// a looser existing dir is left alone (warn only), never chmod'd
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@@ -129,11 +195,82 @@ mod tests {
drop(pool);
open(&c).await.unwrap();
let m = std::fs::metadata(&d).unwrap().permissions().mode();
assert_eq!(m & 0o777, 0o700);
assert_eq!(m & 0o777, 0o755);
}
#[cfg(not(unix))]
drop(pool);
open(&c).await.unwrap();
std::fs::remove_dir_all(tmp).ok();
}
fn tmpdir(tag: &str) -> std::path::PathBuf {
use rand::TryRng;
let mut r = [0u8; 8];
rand::rngs::SysRng.try_fill_bytes(&mut r).unwrap();
let p = std::env::temp_dir().join(format!(
"slinuxm-{tag}-{}",
r.iter().map(|b| format!("{b:02x}")).collect::<String>()
));
std::fs::create_dir_all(&p).unwrap();
p
}
#[cfg(unix)]
#[test]
fn precreated_file_is_0600() {
use std::os::unix::fs::PermissionsExt;
let d = tmpdir("precreate");
let f = d.join("db.sqlite");
precreate_private_file(&f).unwrap();
assert_eq!(
std::fs::metadata(&f).unwrap().permissions().mode() & 0o777,
0o600
);
// An existing file is neither truncated nor re-moded.
std::fs::write(&f, b"keep").unwrap();
precreate_private_file(&f).unwrap();
assert_eq!(std::fs::read(&f).unwrap(), b"keep");
std::fs::remove_dir_all(d).ok();
}
#[cfg(unix)]
#[test]
fn new_dir_is_0700_existing_dir_untouched() {
use std::os::unix::fs::PermissionsExt;
let d = tmpdir("privdir");
let fresh = d.join("a/b");
create_private_dir(&fresh).unwrap();
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&fresh), 0o700);
std::fs::set_permissions(&fresh, std::fs::Permissions::from_mode(0o750)).unwrap();
create_private_dir(&fresh).unwrap();
assert_eq!(mode(&fresh), 0o750);
std::fs::remove_dir_all(d).ok();
}
#[test]
fn owner_check_pure() {
let p = Path::new("/var/lib/x/db.sqlite");
assert!(check_owner(1000, 1000, p).is_ok());
let e = check_owner(0, 1000, p).unwrap_err().to_string();
assert!(e.contains("sudo -u"), "{e}");
assert!(check_owner(1000, 0, p).is_err());
// root is not exempt
assert!(check_owner(0, 5, p).is_err());
}
#[cfg(unix)]
#[test]
fn cli_owner_check_uses_file_then_parent_and_allows_missing_dir() {
let d = tmpdir("owner");
assert!(ensure_token_cli_owner(&d.join("db.sqlite")).is_ok());
assert!(ensure_token_cli_owner(&d.join("missing/db.sqlite")).is_ok());
std::fs::write(d.join("db.sqlite"), b"").unwrap();
assert!(ensure_token_cli_owner(&d.join("db.sqlite")).is_ok());
// A root-owned location seen from a non-root uid fails.
if effective_uid() != 0 {
assert!(ensure_token_cli_owner(Path::new("/usr/db.sqlite")).is_err());
}
std::fs::remove_dir_all(d).ok();
}
}
+5 -7
View File
@@ -168,17 +168,15 @@ async fn serve(config: Config) -> Result<()> {
// `serve_listener` returns once the shutdown token fires and connections
// drain. If the token has not fired it is a server error, so return
// immediately. Bound the drain so a stuck client cannot hang SIGTERM.
let serving: std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> = match tls
{
Some((acceptor, _)) => Box::pin(tls::serve_tls(
let acceptor = tls.map(|(acceptor, _)| acceptor);
let serving: std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> =
Box::pin(server::serve_listener(
listener,
acceptor,
app,
shutdown.clone(),
tls::Limits::default(),
)),
None => Box::pin(server::serve_listener(listener, app, shutdown.clone())),
};
server::Limits::default(),
));
tokio::pin!(serving);
let result = tokio::select! {
r = &mut serving => r,
+120 -6
View File
@@ -8,6 +8,15 @@ use tokio_util::sync::CancellationToken;
use tower_http::trace::TraceLayer;
use std::sync::Arc;
use std::time::Duration;
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto::Builder;
use hyper_util::service::TowerToHyperService;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
use tokio::time::Instant;
use tokio_rustls::TlsAcceptor;
use axum::extract::{Request, State};
use axum::http::{header, StatusCode};
@@ -42,18 +51,123 @@ pub fn build_router(state: AppState) -> Router {
.layer(TraceLayer::new_for_http())
}
/// Serve `app` on `listener` until `shutdown` is cancelled.
/// Connection limits shared by the plain and TLS listeners.
#[derive(Debug, Clone, Copy)]
pub struct Limits {
/// Maximum concurrent connections (handshaking or established). At the
/// cap, accepting pauses until a connection closes.
pub max_conns: usize,
/// Time allowed to receive a request header (also covers idle
/// keep-alive and post-handshake silence).
pub header_timeout: Duration,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_conns: 1024,
header_timeout: Duration::from_secs(30),
}
}
}
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// Serve `app` on `listener` (over TLS when `acceptor` is set) until
/// `shutdown` is cancelled, then drain: stop accepting, ask each connection
/// to finish gracefully, and wait. The caller bounds the drain by dropping
/// this future (which aborts the connections).
pub async fn serve_listener(
listener: tokio::net::TcpListener,
acceptor: Option<TlsAcceptor>,
app: Router,
shutdown: CancellationToken,
limits: Limits,
) -> Result<()> {
let addr = listener.local_addr().context("local_addr")?;
tracing::info!(%addr, "listening");
axum::serve(listener, app)
.with_graceful_shutdown(async move { shutdown.cancelled().await })
.await
.context("server error")
tracing::info!(%addr, tls = acceptor.is_some(), "listening");
let mut conns: JoinSet<()> = JoinSet::new();
let slots = Arc::new(Semaphore::new(limits.max_conns));
let mut last_accept_warn: Option<Instant> = None;
loop {
// Wait for a free slot first, so at the cap we stop accepting.
let permit = tokio::select! {
_ = shutdown.cancelled() => break,
Some(_) = conns.join_next(), if !conns.is_empty() => continue,
p = slots.clone().acquire_owned() => match p {
Ok(p) => p,
Err(_) => break,
},
};
tokio::select! {
_ = shutdown.cancelled() => break,
Some(_) = conns.join_next(), if !conns.is_empty() => {}
r = listener.accept() => {
let (tcp, peer) = match r {
Ok(x) => x,
Err(e) => {
if last_accept_warn.is_none_or(|t| t.elapsed() > Duration::from_secs(10)) {
tracing::warn!(error = %e, "accept failed (further failures suppressed for 10s)");
last_accept_warn = Some(Instant::now());
}
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
};
let acceptor = acceptor.clone();
let svc = TowerToHyperService::new(app.clone());
let stop = shutdown.clone();
conns.spawn(async move {
let _permit = permit;
match acceptor {
None => serve_conn(tcp, peer, svc, stop, limits).await,
Some(acceptor) => {
match tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(tcp)).await {
Ok(Ok(tls)) => serve_conn(tls, peer, svc, stop, limits).await,
Ok(Err(e)) => tracing::debug!(%peer, error = %e, "TLS handshake failed"),
Err(_) => tracing::debug!(%peer, "TLS handshake timed out"),
}
}
}
});
}
}
}
drop(listener);
while conns.join_next().await.is_some() {}
Ok(())
}
async fn serve_conn<I>(
io: I,
peer: std::net::SocketAddr,
svc: TowerToHyperService<Router>,
stop: CancellationToken,
limits: Limits,
) where
I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let mut builder = Builder::new(TokioExecutor::new()).http1_only();
builder
.http1()
.timer(TokioTimer::new())
.header_read_timeout(limits.header_timeout);
// Plain serve_connection: the auto builder's _with_upgrades variant
// sniffs the protocol first, which would defeat the header timeout for
// silent clients.
let conn = builder.serve_connection(TokioIo::new(io), svc);
tokio::pin!(conn);
tokio::select! {
r = conn.as_mut() => {
if let Err(e) = r { tracing::debug!(%peer, error = %e, "connection error"); }
}
_ = stop.cancelled() => {
conn.as_mut().graceful_shutdown();
if let Err(e) = conn.as_mut().await {
tracing::debug!(%peer, error = %e, "connection error");
}
}
}
}
fn allowed_hosts(c: &Config) -> Arc<Vec<String>> {
+2 -117
View File
@@ -1,7 +1,8 @@
//! Native TLS: rustls with the `ring` provider passed explicitly to
//! the config builder (nothing is installed process-wide, so the OTLP
//! clients' provider choice is unaffected). Only used when
//! `server.tls.enabled`; the plain path never touches this module.
//! `server.tls.enabled`; the plain path never touches this module. The accept
//! loop itself lives in [`crate::server`].
//!
//! The certificate lives behind a [`ResolvesServerCert`] that can be swapped
//! at runtime, so SIGHUP reload leaves established connections untouched and
@@ -9,29 +10,19 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use anyhow::{anyhow, Context, Result};
use axum::Router;
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto::Builder;
use hyper_util::service::TowerToHyperService;
use rustls::crypto::ring as provider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use rustls::ServerConfig;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
use tokio::time::Instant;
use tokio_rustls::TlsAcceptor;
use tokio_util::sync::CancellationToken;
use crate::config::TlsConfig;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// Hot-swappable server certificate.
#[derive(Debug)]
pub struct ReloadableCert {
@@ -131,109 +122,3 @@ pub fn spawn_sighup_reload(
}
});
}
/// Connection limits for the TLS listener.
#[derive(Debug, Clone, Copy)]
pub struct Limits {
/// Maximum concurrent connections (handshaking or established). At the
/// cap, accepting pauses until a connection closes.
pub max_conns: usize,
/// Time allowed to receive a request header (also covers idle
/// keep-alive and post-handshake silence).
pub header_timeout: Duration,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_conns: 1024,
header_timeout: Duration::from_secs(30),
}
}
}
/// Serve `app` over TLS until `shutdown` is cancelled, then drain: stop
/// accepting, ask each connection to finish gracefully, and wait. The caller
/// bounds the drain by dropping this future (which aborts the connections).
pub async fn serve_tls(
listener: tokio::net::TcpListener,
acceptor: TlsAcceptor,
app: Router,
shutdown: CancellationToken,
limits: Limits,
) -> Result<()> {
let addr = listener.local_addr().context("local_addr")?;
tracing::info!(%addr, tls = true, "listening");
let mut conns: JoinSet<()> = JoinSet::new();
let slots = Arc::new(Semaphore::new(limits.max_conns));
let mut last_accept_warn: Option<Instant> = None;
loop {
// Wait for a free slot first, so at the cap we stop accepting.
let permit = tokio::select! {
_ = shutdown.cancelled() => break,
Some(_) = conns.join_next(), if !conns.is_empty() => continue,
p = slots.clone().acquire_owned() => match p {
Ok(p) => p,
Err(_) => break,
},
};
tokio::select! {
_ = shutdown.cancelled() => break,
Some(_) = conns.join_next(), if !conns.is_empty() => {}
r = listener.accept() => {
let (tcp, peer) = match r {
Ok(x) => x,
Err(e) => {
if last_accept_warn.is_none_or(|t| t.elapsed() > Duration::from_secs(10)) {
tracing::warn!(error = %e, "accept failed (further failures suppressed for 10s)");
last_accept_warn = Some(Instant::now());
}
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
};
let acceptor = acceptor.clone();
let svc = TowerToHyperService::new(app.clone());
let stop = shutdown.clone();
conns.spawn(async move {
let _permit = permit;
let tls = match tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(tcp)).await {
Ok(Ok(t)) => t,
Ok(Err(e)) => {
tracing::debug!(%peer, error = %e, "TLS handshake failed");
return;
}
Err(_) => {
tracing::debug!(%peer, "TLS handshake timed out");
return;
}
};
let mut builder = Builder::new(TokioExecutor::new()).http1_only();
builder
.http1()
.timer(TokioTimer::new())
.header_read_timeout(limits.header_timeout);
// Plain serve_connection: the auto builder's _with_upgrades
// variant sniffs the protocol first, which would defeat the
// header timeout for silent clients.
let conn = builder.serve_connection(TokioIo::new(tls), svc);
tokio::pin!(conn);
tokio::select! {
r = conn.as_mut() => {
if let Err(e) = r { tracing::debug!(%peer, error = %e, "connection error"); }
}
_ = stop.cancelled() => {
conn.as_mut().graceful_shutdown();
if let Err(e) = conn.as_mut().await {
tracing::debug!(%peer, error = %e, "connection error");
}
}
}
});
}
}
}
drop(listener);
while conns.join_next().await.is_some() {}
Ok(())
}
+9 -1
View File
@@ -43,7 +43,13 @@ async fn start(auth: bool) -> Harness {
let shutdown = state.shutdown.clone();
let state_db = state.db.clone();
let app = server::build_router(state);
let join = tokio::spawn(server::serve_listener(listener, app, shutdown.clone()));
let join = tokio::spawn(server::serve_listener(
listener,
None,
app,
shutdown.clone(),
server::Limits::default(),
));
Harness {
state_db,
port,
@@ -212,8 +218,10 @@ async fn docker_unavailable_does_not_affect_systemd() {
let shutdown = state.shutdown.clone();
tokio::spawn(server::serve_listener(
listener,
None,
server::build_router(state),
shutdown.clone(),
server::Limits::default(),
));
let (st, _, _) = http(port, "GET", "/api/v1/docker/ps", &[], None, SHORT).await;
assert_eq!(st, 503);
+104
View File
@@ -0,0 +1,104 @@
//! Plain-HTTP listener limits: the same accept loop as TLS, so the same
//! connection cap, header timeout and graceful drain apply.
use std::time::Duration;
use skyg_linux_tracker::config::Config;
use skyg_linux_tracker::server::{self, Limits};
use skyg_linux_tracker::sources::fake::fake_state;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
async fn plain(limits: Limits) -> (u16, CancellationToken, JoinHandle<anyhow::Result<()>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let mut config = Config::default();
config.auth.enabled = false;
let state = fake_state(config);
let shutdown = state.shutdown.clone();
let join = tokio::spawn(server::serve_listener(
listener,
None,
server::build_router(state),
shutdown.clone(),
limits,
));
(port, shutdown, join)
}
/// Connect and complete one `/healthz` exchange, keeping the connection open.
async fn served(port: u16) -> TcpStream {
let mut c = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
c.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n")
.await
.unwrap();
let mut buf = [0u8; 1024];
let n = c.read(&mut buf).await.unwrap();
assert!(String::from_utf8_lossy(&buf[..n]).contains("200 OK"));
c
}
#[tokio::test]
async fn slowloris_header_is_closed_after_timeout() {
let (port, shutdown, _j) = plain(Limits {
max_conns: 16,
header_timeout: Duration::from_millis(500),
})
.await;
let mut c = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
// A partial request line, then silence.
c.write_all(b"GET /healthz HTTP/1.1\r\nHost: loc")
.await
.unwrap();
let start = std::time::Instant::now();
let mut buf = [0u8; 256];
let r = tokio::time::timeout(Duration::from_secs(5), async {
loop {
match c.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
}
})
.await;
assert!(r.is_ok(), "slowloris connection was not closed");
assert!(start.elapsed() < Duration::from_secs(4));
shutdown.cancel();
}
#[tokio::test]
async fn connection_cap_is_enforced() {
let (port, shutdown, _j) = plain(Limits {
max_conns: 2,
header_timeout: Duration::from_secs(30),
})
.await;
let c1 = served(port).await;
let c2 = served(port).await;
let third = tokio::time::timeout(Duration::from_millis(800), served(port)).await;
assert!(third.is_err(), "third connection was served beyond the cap");
drop(c1);
let c3 = tokio::time::timeout(Duration::from_secs(5), served(port)).await;
assert!(c3.is_ok(), "slot was not released after a close");
drop(c2);
shutdown.cancel();
}
#[tokio::test]
async fn graceful_shutdown_drains_idle_connections() {
let (port, shutdown, join) = plain(Limits::default()).await;
let mut c = served(port).await;
// The idle keep-alive connection is still open; shutdown must complete.
shutdown.cancel();
let r = tokio::time::timeout(Duration::from_secs(5), join)
.await
.expect("serve did not return after shutdown");
r.unwrap().unwrap();
let mut buf = [0u8; 64];
let n = tokio::time::timeout(Duration::from_secs(2), c.read(&mut buf))
.await
.expect("idle connection left open");
assert!(matches!(n, Ok(0) | Err(_)));
}
+5 -5
View File
@@ -567,7 +567,7 @@ async fn sigterm_with_open_tls_connections_exits_promptly() {
/// In-process TLS listener with explicit limits.
async fn inproc(
pair: &Pair,
limits: skyg_linux_tracker::tls::Limits,
limits: skyg_linux_tracker::server::Limits,
) -> (u16, tokio_util::sync::CancellationToken, tempdir::Dir) {
use skyg_linux_tracker::{config::Config, server, sources::fake::fake_state, tls};
let dir = tempdir::Dir::new("inproc");
@@ -584,9 +584,9 @@ async fn inproc(
let app = server::build_router(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(tls::serve_tls(
tokio::spawn(server::serve_listener(
listener,
acceptor,
Some(acceptor),
app,
shutdown.clone(),
limits,
@@ -609,7 +609,7 @@ async fn silent_connection_closed_after_header_timeout() {
let pair = gen_pair();
let (port, shutdown, _d) = inproc(
&pair,
skyg_linux_tracker::tls::Limits {
skyg_linux_tracker::server::Limits {
max_conns: 16,
header_timeout: Duration::from_millis(500),
},
@@ -637,7 +637,7 @@ async fn connection_cap_is_enforced() {
let pair = gen_pair();
let (port, shutdown, _d) = inproc(
&pair,
skyg_linux_tracker::tls::Limits {
skyg_linux_tracker::server::Limits {
max_conns: 2,
header_timeout: Duration::from_secs(30),
},