From 26649bddfc51f1a6f8a49e3f59679bfa282e2046 Mon Sep 17 00:00:00 2001 From: CI Test Date: Tue, 17 Nov 2026 20:49:00 +0000 Subject: [PATCH 1/3] Plan 320: require --public for any non-loopback bind Close the operator footgun where unicast LAN/public addresses could bind without acknowledgment; align CLI, Python ServeConfig/runtime, and docs. Co-authored-by: Cursor --- architecture/eggserve-bin.md | 3 +- architecture/policy-system.md | 2 +- crates/eggserve-bin/src/args.rs | 33 +++++++++- .../eggserve-python/python/eggserve/server.py | 23 ++++--- .../python/eggserve/subprocess.py | 5 +- crates/eggserve-python/src/server/runtime.rs | 13 ++-- crates/eggserve-python/tests/test_server.py | 17 ++++++ docs/cli.md | 10 +-- docs/deployment.md | 9 ++- docs/release-contract.md | 2 +- docs/security-policy.md | 8 ++- docs/security-review.md | 2 +- ...20-public-bind-acknowledgment-hardening.md | 40 ++++++++++++ ...20-public-bind-acknowledgment-hardening.md | 61 +++++++++++++++++++ plans/registry.md | 5 +- .../cli-ops-observability-roadmap.md | 23 +++++++ 16 files changed, 227 insertions(+), 29 deletions(-) create mode 100644 plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md create mode 100644 plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md diff --git a/architecture/eggserve-bin.md b/architecture/eggserve-bin.md index 877dd667..707427f2 100644 --- a/architecture/eggserve-bin.md +++ b/architecture/eggserve-bin.md @@ -42,7 +42,8 @@ Canonical grammar is `[OPTIONS] [PORT] [DIRECTORY]` (normative flags in * `--directory DIR` occupies DIRECTORY; `.` default. `--bind HOST[:PORT]` (host-only leaves PORT free), `--port PORT`, `--addr HOST:PORT` (cannot combine with `--bind`); `:PORT` means `0.0.0.0:PORT` (still needs - `--public`). Hostnames resolve once; wildcard results still need `--public`. + `--public`). Hostnames resolve once; any non-loopback result needs + `--public` (acknowledgment only; the flag does not expand the host). * Two logical slots: PORT then DIRECTORY. Explicit port sources occupy PORT; the next positional after occupied PORT is DIRECTORY verbatim (even numeric). `--directory` occupying DIRECTORY leaves a later numeric positional free for diff --git a/architecture/policy-system.md b/architecture/policy-system.md index f60c6bf0..495a69c2 100644 --- a/architecture/policy-system.md +++ b/architecture/policy-system.md @@ -175,7 +175,7 @@ Users must explicitly opt-in to less restrictive behavior via CLI flags or Pytho | `--directory-listing` | `DirectoryListingPolicy::Enabled` | Enable directory listing | | `--follow-symlinks` | `SymlinkPolicy::Follow` | Follow symlinks | | `--allow-dotfiles` | `DotfilePolicy::Serve` | Serve dotfiles | -| `--public` | Bind to `0.0.0.0` | Accept non-loopback connections | +| `--public` | Acknowledge non-loopback bind | Required for any non-loopback `--bind`/`--addr` (does not expand the host alone) | ## Python API Mapping diff --git a/crates/eggserve-bin/src/args.rs b/crates/eggserve-bin/src/args.rs index 25d6c561..9b933070 100644 --- a/crates/eggserve-bin/src/args.rs +++ b/crates/eggserve-bin/src/args.rs @@ -741,7 +741,12 @@ impl Args { let bind_ip = resolve_bind_ip(&bind_host, bind_port)?; - if !public && bind_ip.is_unspecified() { + // Threat-model asset: without `--public`, do not bind a public + // interface. Unspecified addresses are the usual case, but any + // non-loopback unicast (LAN or routable) is also network exposure + // and needs the same acknowledgment. `--public` alone does not + // expand the default host; it only authorizes a non-loopback bind. + if !public && !bind_ip.is_loopback() { return Err(format!( "binding to {bind_ip} requires --public to acknowledge public exposure intent" )); @@ -887,7 +892,7 @@ pub fn print_usage() { println!(" --port Bind port (default: 8000)"); println!(" --addr Full socket address (cannot combine with --bind)"); println!( - " --public Acknowledge public exposure intent (required for 0.0.0.0 or ::)" + " --public Acknowledge public exposure intent (required for any non-loopback bind)" ); println!(" --directory-listing Enable directory listing (disabled by default)"); println!(" --follow-symlinks Follow symlinks (denied by default)"); @@ -1425,6 +1430,30 @@ mod tests { assert!(result.unwrap_err().contains("--public")); } + #[test] + fn non_loopback_unicast_without_public_flag_fails() { + let result = parse(&["--addr", "192.168.1.10:8000"]); + assert!(result.is_err()); + let error = result.unwrap_err(); + assert!(error.contains("--public"), "{error}"); + assert!(error.contains("192.168.1.10"), "{error}"); + } + + #[test] + fn non_loopback_unicast_with_public_flag_allowed() { + let args = parse(&["--addr", "192.168.1.10:8000", "--public"]).unwrap(); + assert_eq!(args.bind, "192.168.1.10:8000".parse().unwrap()); + assert!(!args.bind.ip().is_loopback()); + } + + #[test] + fn loopback_bind_does_not_require_public_flag() { + let args = parse(&["--addr", "127.0.0.1:8000"]).unwrap(); + assert!(args.bind.ip().is_loopback()); + let args = parse(&["--bind", "::1", "--port", "8000"]).unwrap(); + assert!(args.bind.ip().is_loopback()); + } + #[test] fn unsafe_flags_update_policy() { let args = parse(&[ diff --git a/crates/eggserve-python/python/eggserve/server.py b/crates/eggserve-python/python/eggserve/server.py index 1f9a21be..0ca1c65e 100644 --- a/crates/eggserve-python/python/eggserve/server.py +++ b/crates/eggserve-python/python/eggserve/server.py @@ -358,8 +358,11 @@ def _normalize_compat_server_address(server_address): The empty host is the conventional IPv4 wildcard spelling used by ``http.server``. It is normalized before entering the native binding - layer, where it also carries explicit wildcard intent. Other hostnames - and literals remain untouched so Rust performs the only resolution. + layer. An explicit constructor address is itself the public-bind + acknowledgment (Plan 094): non-loopback IP literals, wildcards, and + hostnames set ``public_intent`` so the native gate does not demand a + second flag. Loopback literals stay quiet. Other hostnames and + literals remain untouched so Rust performs the only resolution. """ if not isinstance(server_address, tuple) or len(server_address) != 2: raise OSError("server_address must be a (host, port) tuple") @@ -371,10 +374,14 @@ def _normalize_compat_server_address(server_address): if host == "": return "0.0.0.0", port, True try: - wildcard = ipaddress.ip_address(host).is_unspecified + # Non-loopback (including unspecified) needs public acknowledgment. + public_intent = not ipaddress.ip_address(host).is_loopback except ValueError: - wildcard = False - return host, port, wildcard + # Hostname: the constructor already chose a non-literal host, so + # treat that as explicit network-bind intent. Loopback hostnames + # still bind loopback; public_intent does not expand the address. + public_intent = True + return host, port, public_intent def _split_native_address(value): @@ -453,7 +460,7 @@ def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, def _init_compat(self, server_address, handler_class, bind_and_activate, *, max_workers, max_request_body_bytes, max_handler_response_bytes, tls_certfile, tls_keyfile): - host, port, wildcard = _normalize_compat_server_address(server_address) + host, port, public_intent = _normalize_compat_server_address(server_address) factory = handler_class.func if isinstance(handler_class, partial) else handler_class if not isinstance(factory, type) or not issubclass(factory, BaseHTTPRequestHandler): raise TypeError("RequestHandlerClass must subclass BaseHTTPRequestHandler") @@ -483,7 +490,7 @@ def _init_compat(self, server_address, handler_class, bind_and_activate, *, max_ self._serve_done.set() self._native = None self._bind = host - self._wildcard_bind = wildcard + self._public_bind = public_intent self._requested_port = port self._max_workers = max_workers self._max_request_body_bytes = max_request_body_bytes @@ -612,7 +619,7 @@ def server_activate(self): native_kwargs["max_connections"] = self._max_workers self._native = _NativeServer( root, bind=self._bind, port=self._requested_port, handler=callback, - public=self._wildcard_bind, + public=self._public_bind, max_python_callbacks=self._max_workers if callback is not None else 1, request_body_mode="reject" if self._static_config is not None else "buffer", max_request_body_bytes=0 if self._static_config is not None else self._max_request_body_bytes, diff --git a/crates/eggserve-python/python/eggserve/subprocess.py b/crates/eggserve-python/python/eggserve/subprocess.py index ec5e6819..6f1dbe9a 100644 --- a/crates/eggserve-python/python/eggserve/subprocess.py +++ b/crates/eggserve-python/python/eggserve/subprocess.py @@ -153,7 +153,10 @@ def __post_init__(self) -> None: f"log_format must be one of {sorted(_VALID_LOG_FORMATS)}, " f"got {self.log_format!r}" ) - if not self.public and ipaddress.ip_address(host).is_unspecified: + # Match the CLI gate: any non-loopback bind (wildcard or unicast) + # needs an explicit public acknowledgment. `public=True` alone does + # not expand the host; it only authorizes network exposure. + if not self.public and not ipaddress.ip_address(host).is_loopback: raise ValueError( f"binding to {self.bind} requires public=True " "to acknowledge public exposure intent" diff --git a/crates/eggserve-python/src/server/runtime.rs b/crates/eggserve-python/src/server/runtime.rs index 2f5690ba..30bb310f 100644 --- a/crates/eggserve-python/src/server/runtime.rs +++ b/crates/eggserve-python/src/server/runtime.rs @@ -183,10 +183,15 @@ impl PyServer { })? .next() .ok_or_else(|| pyo3::exceptions::PyOSError::new_err("bind address did not resolve"))?; - if !public && bind_addr.ip().is_unspecified() { - return Err(pyo3::exceptions::PyValueError::new_err( - "binding to 0.0.0.0 or :: requires public=True", - )); + // Same gate as the CLI: without public=True, only loopback binds + // are admitted. Unspecified and non-loopback unicast both count as + // network exposure. `public=True` is acknowledgment only; it does + // not rewrite the bind address. + if !public && !bind_addr.ip().is_loopback() { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "binding to {} requires public=True to acknowledge public exposure intent", + bind_addr.ip() + ))); } // Python-only admission: callback concurrency has no canonical // runtime counterpart (downstream app admission is separate). diff --git a/crates/eggserve-python/tests/test_server.py b/crates/eggserve-python/tests/test_server.py index 61947007..b6bd3ef8 100644 --- a/crates/eggserve-python/tests/test_server.py +++ b/crates/eggserve-python/tests/test_server.py @@ -177,6 +177,23 @@ def test_public_ipv6_without_public_raises(self): ServeConfig(bind="::", public=False) self.assertIn("public=True", str(ctx.exception)) + def test_non_loopback_unicast_without_public_raises(self): + with self.assertRaises(ValueError) as ctx: + ServeConfig(bind="192.168.1.10", public=False) + self.assertIn("public=True", str(ctx.exception)) + self.assertIn("192.168.1.10", str(ctx.exception)) + + def test_non_loopback_unicast_with_public_true_allowed(self): + config = ServeConfig(bind="192.168.1.10", public=True) + self.assertTrue(config.public) + self.assertEqual(config.bind, "192.168.1.10") + + def test_loopback_bind_does_not_require_public(self): + config = ServeConfig(bind="127.0.0.1", public=False) + self.assertFalse(config.public) + config = ServeConfig(bind="::1", public=False) + self.assertFalse(config.public) + def test_valid_public_bind_with_public_true_allowed(self): config = ServeConfig(bind="0.0.0.0", public=True) self.assertEqual(config.bind, "0.0.0.0") diff --git a/docs/cli.md b/docs/cli.md index 88099ba2..ca947c10 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -20,15 +20,16 @@ eggserve [OPTIONS] [PORT] [DIRECTORY] | `--port PORT` | Port to listen on (blocks positional port override) | `8000` | | `PORT` | Positional port argument; a valid numeric token fills the unoccupied port slot | `8000` | | `DIRECTORY` | First positional token not consumed as PORT; once PORT is occupied, it is used verbatim, including numeric names | `.` (current directory) | -| `--public` | Bind to all interfaces (required for `0.0.0.0` or `::` binds) | off | +| `--public` | Acknowledge public exposure intent (required for any non-loopback bind) | off | | `--http3` | Enable experimental native HTTP/3/QUIC beside TCP; requires `--tls-cert` (and optionally `--tls-key`), binds same-port UDP, and advertises `Alt-Svc` | off | | `--tls-cert PATH` | PEM certificate chain; enables TLS (requires `tls` build) | none | | `--tls-key PATH` | PEM private key; defaults to `--tls-cert` when omitted; requires `--tls-cert` (requires `tls` build) | `--tls-cert` | `--bind` accepts IPv4/IPv6 literals and hostnames. Hostname resolution happens once during argument validation; the resolved address is then used for the -listener. A hostname that resolves to a wildcard address still requires -`--public`. +listener. Any resolved non-loopback address (wildcard or unicast) requires +`--public`. The flag is acknowledgment only: it does not expand a loopback +default host to `0.0.0.0`. Note: `--bind HOST` (without a port) leaves the positional port slot available. A subsequent numeric positional argument will be parsed as the @@ -50,7 +51,8 @@ sets both host and port and cannot be combined with `--bind`. Default is `--header-timeout` must not exceed `--connection-total-timeout`. -Binding to `0.0.0.0` or `::` without `--public` is rejected with an error. +Binding to any non-loopback address (including `0.0.0.0`, `::`, or a LAN/unicast +address) without `--public` is rejected with an error. ### Security policies diff --git a/docs/deployment.md b/docs/deployment.md index e8c90850..7e7894ae 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -193,13 +193,16 @@ See README.md for Windows-specific profiles (windows-reverse-proxy, windows-dire ## Binding to all interfaces -To make eggserve accessible from other machines (without a reverse proxy), use `--public`: +To make eggserve accessible from other machines (without a reverse proxy), pass +an explicit non-loopback address and acknowledge it with `--public`: ```sh -eggserve --public --port 8000 --directory public +eggserve --public --addr 0.0.0.0:8000 --directory public ``` -This binds to `0.0.0.0`. The `--public` flag is required to acknowledge public exposure intent. When binding publicly, consider using a reverse proxy for TLS termination and access control. +`--public` is required for any non-loopback bind (wildcard or unicast). It does +not expand a loopback default by itself. When binding publicly, consider using a +reverse proxy for TLS termination and access control. ## Combining patterns diff --git a/docs/release-contract.md b/docs/release-contract.md index 638adc67..3ddefced 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -221,7 +221,7 @@ These behaviors are determined by hyper's HTTP/1.1 parser, not eggserve policy: ### Safe Defaults (enforced at library level) -- Loopback bind (`127.0.0.1`) unless `--public` is passed +- Loopback bind (`127.0.0.1`) by default; any non-loopback bind requires `--public` - Symlinks denied unless `--follow-symlinks` is passed - Dotfiles denied unless `--allow-dotfiles` is passed - Directory listing disabled unless `--directory-listing` is passed diff --git a/docs/security-policy.md b/docs/security-policy.md index 6efbd1d0..b669f446 100644 --- a/docs/security-policy.md +++ b/docs/security-policy.md @@ -54,7 +54,13 @@ The following options weaken security defaults. Each requires an explicit CLI fl ### `--public` -Binds to all network interfaces (`0.0.0.0`) instead of loopback. Use only when the server must be accessible from other machines. The operator is responsible for network-level access control. +Acknowledges intent to bind a non-loopback address. Without this flag, the CLI +rejects any resolved address that is not loopback (wildcards such as `0.0.0.0` +/`::`, and unicast LAN or routable addresses). The flag does not rewrite the +bind host by itself: pass an explicit non-loopback `--bind`/`--addr` (for +example `--addr 0.0.0.0:8000 --public`). Use only when the server must be +reachable from other machines. The operator is responsible for network-level +access control. ### `--follow-symlinks` diff --git a/docs/security-review.md b/docs/security-review.md index 63476430..949cea35 100644 --- a/docs/security-review.md +++ b/docs/security-review.md @@ -24,7 +24,7 @@ Every security default is enforced at the library level in `eggserve-core`. See | Default | Enforcement | |---------|-------------| -| Loopback bind | `127.0.0.1` unless `--public` | +| Loopback bind | `127.0.0.1` default; any non-loopback bind requires `--public` | | GET/HEAD only | 405 for other methods | | Static body rejection | 413/400 for body signals | | No symlinks | Descriptor-relative `statat(AT_SYMLINK_NOFOLLOW)` + `openat(O_NOFOLLOW)` on Unix; component-wise `symlink_metadata` on non-Unix | diff --git a/plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md b/plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md new file mode 100644 index 00000000..edd8c596 --- /dev/null +++ b/plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md @@ -0,0 +1,40 @@ +# Closure — Plan 320 public-bind acknowledgment hardening + +Status: closed + +Implementation: `plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md` + +## What landed + +- CLI `Args` rejects any resolved non-loopback bind without `--public` + (`!bind_ip.is_loopback()`), not only unspecified addresses. +- Python `ServeConfig` and the native lowlevel constructor use the same + non-loopback gate. +- `HTTPServer` address normalization treats non-loopback IP literals and + hostnames as explicit public intent (Plan 094 constructor-as-intent); + loopback literals stay quiet. `--public` / `public=True` remains + acknowledgment only and does not expand the host. +- Docs corrected: `docs/cli.md`, `docs/security-policy.md`, + `docs/deployment.md`, `docs/security-review.md`, + `docs/release-contract.md`, `architecture/eggserve-bin.md`, + `architecture/policy-system.md`. + +## Evidence + +```text +cargo test -p eggserve-bin --lib public_ + → 5 passed (includes non_loopback_unicast_* and loopback_bind_*) + +PYTHONPATH=python:tests python3 -m unittest \ + test_server.TestConfigValidation.test_non_loopback_unicast_without_public_raises \ + test_server.TestConfigValidation.test_non_loopback_unicast_with_public_true_allowed \ + test_server.TestConfigValidation.test_loopback_bind_does_not_require_public \ + test_server.TestConfigValidation.test_public_ipv4_without_public_raises \ + test_server.TestLegacyPublicBindGuard + → 13 passed +``` + +## Residuals + +None for this gate. Accepted filesystem/protocol residuals from the security +audit are unchanged and out of scope for 320. diff --git a/plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md b/plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md new file mode 100644 index 00000000..27928c70 --- /dev/null +++ b/plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md @@ -0,0 +1,61 @@ +# Plan 320 — Public-bind acknowledgment hardening + +Status: closed + +Source roadmap: `plans/subsystems/cli-ops-observability-roadmap.md` + +## Objective + +Close the gap between the threat-model asset (“without `--public`, do not +bind a public interface”) and the CLI/Python gate that only rejected +*unspecified* addresses (`0.0.0.0` / `::`). Require an explicit public +acknowledgment for any non-loopback bind on the CLI-facing surfaces, while +preserving the Python `http.server` contract that an explicit constructor +address is itself the acknowledgment. + +## Non-goals + +- Do not make `--public` alone expand the default bind to `0.0.0.0` + (Plan 303 verified `--public --port` still binds loopback). +- Do not add authentication, per-IP rate limiting, or bind-interface + allowlists. +- Do not change filesystem confinement, TLS, or protocol tiers. + +## Current evidence + +- `crates/eggserve-bin/src/args.rs` rejects only `bind_ip.is_unspecified()`. +- `docs/threat-model.md` names any public interface, not only wildcards. +- `docs/deployment.md` / `docs/security-policy.md` incorrectly imply + `--public` alone binds `0.0.0.0`; Plan 303 evidence shows acknowledgment + without address expansion. +- Python `ServeConfig` mirrors the unspecified-only check; native + `eggserve-python` runtime does the same; `HTTPServer` auto-sets + `public` only for wildcards. + +## Work packages + +1. CLI: reject `!public && !bind_ip.is_loopback()`; update help text and + unit tests (unicast non-loopback without `--public`, allowed with it, + loopback still free). +2. Python `ServeConfig` + native lowlevel constructor: same non-loopback + gate; `HTTPServer` normalize treats non-loopback IP literals and + hostnames as explicit public intent (loopback literals stay quiet). +3. Docs: `docs/cli.md`, `docs/security-policy.md`, `docs/deployment.md`, + `architecture/eggserve-bin.md`, `architecture/policy-system.md` — + describe acknowledgment for any non-loopback bind; correct the false + “`--public` alone binds 0.0.0.0” claim. +4. Register milestone 320 on the CLI roadmap + `plans/registry.md`. + +## Verification + +```sh +cargo test -p eggserve-bin --lib +# focused Python when wheel env available: +# python -m unittest crates.eggserve-python.tests.test_server +``` + +## Acceptance + +- Non-loopback CLI bind without `--public` fails. +- Loopback and wildcard-with-`--public` still work. +- Docs no longer claim `--public` alone expands the bind address. diff --git a/plans/registry.md b/plans/registry.md index ef7f6c13..87e353b2 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -9,7 +9,7 @@ Canonical direction remains in: - `plans/002-long-term-roadmap.md` - `plans/003-planning-process.md` -New milestone numbers continue from `320`. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. +New milestone numbers continue from `321`. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. ## Status vocabulary @@ -33,7 +33,7 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | Direct H1 runtime + service contract | active | `plans/subsystems/direct-h1-runtime-roadmap.md` | 306 runtime error representation single authority | 294–297 polish campaign closed; 299 F3 repair closed. Plan 300's publication completed on 2026-09-25 and was closed by Milestone 304, whose disclosed condition — that the published artifact predated the post-tag corrective batch — Milestone 305 discharged by republishing the corrected 0.5.0 line on 2026-10-22. Milestones 306–309 are all closed: one runtime-error authority, an accurate drift-bounded Plan 253 ledger, a parity-preserving compatibility projection, and one accept-error classification authority. | | Planning governance | active | `plans/subsystems/planning-governance-roadmap.md` | 314 publication-state staleness sweep | Milestones 1 and 302 closed. Reopened: six surfaces still describe the published 0.4.0 line as pending, including the agent-facing skill. Interface dependency: 304's closure record supplies the facts. | | Python facade | active | `plans/subsystems/python-facade-roadmap.md` | 311 directory-listing renderer consolidation | New roadmap. Milestone 311 is closed: the bridge's second listing renderer is gone and the 1 MiB response-byte ceiling now applies to the Python path. | -| CLI, ops, and observability | active | `plans/subsystems/cli-ops-observability-roadmap.md` | 313 lint policy enforcement (closed) | 312 closed the routine Windows/macOS compile coverage. 313 closed the lint policy: `missing_docs` and `clippy::undocumented_unsafe_blocks` are enforced in the root lint table, with lanes for the Python-internal feature, the excluded Python crate, and the Windows confinement boundary. 315 closed the dependency specification consolidation: a root `[workspace.dependencies]` table owns the shared versions and the `rustls` floor, with all three lockfiles byte-identical. | +| CLI, ops, and observability | active | `plans/subsystems/cli-ops-observability-roadmap.md` | 320 public-bind acknowledgment hardening (closed) | 312–320 closed. 320 hardened the CLI/Python public-bind gate so any non-loopback address requires `--public`/`public=True`; docs no longer claim `--public` alone expands to `0.0.0.0`. | | Docs architecture (overview index + deep dives) | closed | `plans/subsystems/docs-architecture-roadmap.md` | 301 closed (overview + deep dives refreshed to 0.4.0 baseline) | Trace: `plans/closure/docs-architecture/293-architecture-overview-deep-dive-refresh.md`. Interface: closed 294–299 code state + Plan 300 publication as review input. | ## Dependency-ready implementation plans @@ -67,6 +67,7 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | Static confinement | 317 | closed | `plans/implementation/static-confinement/317-windows-runtime-qualification-and-corpus-seed-hygiene.md` | The Windows confinement path is qualified by hosted CI instead of a manual lane: the `platform-compile` job's Windows leg runs the static crate's tests, so the Windows-only unit tests and the corpus byte-identity check actually run. The NT information class the enumeration path depends on (37 — the `ntifs.h` numbering, which the user-mode `winnt.h` numbering contradicts at 16) is pinned against a live kernel. The fuzz corpus is byte-stable across platforms (`-text` in `.gitattributes`) and live: the `path_components` and `platform_component` seeds are the exact bytes their targets consume, and the cross-platform replay asserts non-vacuity. Gate rule `check_plan317_corpus_seed_hygiene`. Closure: `plans/closure/static-confinement/317-windows-runtime-qualification-and-corpus-seed-hygiene.md`. | | CLI, ops, and observability | 318 | closed | `plans/implementation/cli-ops-observability/318-rustls-floor-and-testpypi-staging.md` | The manifest `rustls` floor is raised from `0.23.45` to `0.23.46` in the workspace table and in the excluded Python crate. The resolution does not move — all three lockfiles and the resolved feature sets are unchanged — but a consumer pinned to `=0.23.45` can no longer unify to the vulnerable release alongside these crates. The guard `docs/dependency-policy.md` already required but that never existed now does: gate rule `check_plan318_rustls_floor`. Closure: `plans/closure/cli-ops-observability/318-rustls-floor-and-testpypi-staging.md`. | | CLI, ops, and observability | 319 | closed | `plans/implementation/cli-ops-observability/319-static-0-5-1-patch-release-and-doc-sweep.md` | `eggserve-static` is bumped to `0.5.1` with the NT directory-buffer fixes the published `0.5.0` still carried; the dependent crates' caret requirements already accept it and are unchanged. `docs/release-contract.md` and five `architecture/` deep dives no longer name the superseded `0.4.0` line's versions. The six factually-wrong doc comments an audit found in Plan 313's 539-item remediation are corrected. Closure: `plans/closure/cli-ops-observability/319-static-0-5-1-patch-release-and-doc-sweep.md`. | +| CLI, ops, and observability | 320 | closed | `plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md` | Done; closure: `plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md`. Non-loopback binds require `--public`/`public=True`; docs match acknowledgment-only semantics. | ## Blocked work diff --git a/plans/subsystems/cli-ops-observability-roadmap.md b/plans/subsystems/cli-ops-observability-roadmap.md index f9d729ec..67a644a1 100644 --- a/plans/subsystems/cli-ops-observability-roadmap.md +++ b/plans/subsystems/cli-ops-observability-roadmap.md @@ -249,6 +249,28 @@ Exit conditions: all three lockfiles and the resolved feature sets are unchanged; the floor is declared once and inherited; the gate rule fails closed on a regressed floor in either the table or the excluded crate. +### Milestone 320 — Public-bind acknowledgment hardening + +Class: invariant + +Objective: align the CLI and Python public-bind gates with the threat-model +asset that without an explicit public acknowledgment the process must not +bind a public (non-loopback) interface. + +Dependencies: none beyond the closed code state. + +Deliverable boundary: CLI `Args` parsing, Python `ServeConfig` and native +runtime constructor, `HTTPServer` address normalization, and the user/docs +surfaces that describe `--public`. No filesystem, TLS, or protocol change. + +User or operator value: a LAN or routable unicast bind cannot slip through +without `--public`/`public=True`, and documentation no longer claims the +flag alone expands the default host to `0.0.0.0`. + +Exit conditions: non-loopback binds without acknowledgment fail; loopback +and acknowledged non-loopback binds succeed; docs match the acknowledgment +semantics verified by Plan 303 (`--public --port` still loopback). + ### Milestone 319 — `eggserve-static` 0.5.1 patch release and current-line sweep Class: polish @@ -349,3 +371,4 @@ changing any resolved version. | 315 | closed | `plans/implementation/cli-ops-observability/315-dependency-specification-consolidation.md` | `plans/closure/cli-ops-observability/315-dependency-specification-consolidation.md` | A root `[workspace.dependencies]` table owns every shared dependency version and the `rustls` `0.23.45` floor; the excluded Python crate keeps explicit specs. All three lockfiles are byte-identical and the resolved package and feature sets are unchanged. The plan's `default-features` guidance was factually backwards and is recorded as a deviation. | | 318 | closed | `plans/implementation/cli-ops-observability/318-rustls-floor-and-testpypi-staging.md` | `plans/closure/cli-ops-observability/318-rustls-floor-and-testpypi-staging.md` | The manifest `rustls` floor is raised from `0.23.45` to `0.23.46` in the workspace table and in the excluded Python crate. The resolution does not move — all three lockfiles and the resolved feature sets are unchanged — but a consumer pinned to `=0.23.45` can no longer unify to the vulnerable release alongside these crates. The guard `docs/dependency-policy.md` already required but that never existed now does: gate rule `check_plan318_rustls_floor`. The TestPyPI trusted publisher's GitHub-side environment exists and its workflow job is wired; the PyPI-side account registration remains a maintainer step. | | 319 | closed | `plans/implementation/cli-ops-observability/319-static-0-5-1-patch-release-and-doc-sweep.md` | `plans/closure/cli-ops-observability/319-static-0-5-1-patch-release-and-doc-sweep.md` | `eggserve-static` is bumped to `0.5.1` and published with the NT directory-buffer fixes the published `0.5.0` still carried; the dependent crates' caret requirements already accept it and are unchanged. `docs/release-contract.md` and five `architecture/` deep dives no longer name the superseded `0.4.0` line's versions. The six factually-wrong doc comments an audit found in Plan 313's 539-item remediation are corrected. | +| 320 | closed | `plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md` | `plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md` | CLI/Python gate requires `--public`/`public=True` for any non-loopback bind; docs corrected; `HTTPServer` constructor address remains intent. | From eae051244fbbe863ba6a74f65b60adb63879ab03 Mon Sep 17 00:00:00 2001 From: CI Test Date: Tue, 24 Nov 2026 23:15:39 +0000 Subject: [PATCH 2/3] Plan 321/322: TLS substrate corrective and reload ALPN coherence Correct the five TLS seam defects found by the capability review at 26649bd plus the reload-coherence gap found by its follow-up security review: - Build every rustls server configuration with the ring provider explicitly instead of the process default, and drop the Python wheel's global install_default workaround. - Validate TLS ALPN against HTTP/2 availability at build/start, and reject a contradictory snapshot at ServerHandle's reload swap before it becomes live. - Map --header-timeout onto tls_handshake_timeout, matching the published security policy. - Make the named-SNI identity ceiling order-independent; the optional default identity no longer counts toward it. - Bound H3 QUIC receive windows and idle timeout to the VarInt range and report transport failures as InvalidTransportConfig instead of InvalidKey. Milestone 321/322 implementation and closure records, the TLS identity roadmap, the registry (next number 323), the CHANGELOG, and the affected docs are included. The milestone records carry the exact verification commands and outcomes, including the two pre-existing macOS-only test failures that keep the broad verify wrapper red on this host. --- CHANGELOG.md | 24 ++ architecture/eggnet-tls.md | 9 + crates/eggnet-tls/src/lib.rs | 64 +++++- crates/eggnet-tls/tests/neutral_tls.rs | 46 +++- crates/eggserve-bin/src/args.rs | 18 +- .../src/server/config/runtime.rs | 52 ++++- crates/eggserve-core/src/server/config/tls.rs | 4 +- crates/eggserve-core/src/server/handle.rs | 52 +++-- crates/eggserve-core/src/server/mod.rs | 5 + crates/eggserve-core/tests/tls_identity.rs | 99 ++++++++ crates/eggserve-h3/src/config.rs | 71 +++++- crates/eggserve-h3/src/quic.rs | 33 ++- crates/eggserve-python/src/server/runtime.rs | 4 - docs/cli.md | 2 +- docs/deployment.md | 2 +- docs/security-policy.md | 2 +- docs/timeout-reference.md | 6 +- docs/tls.md | 22 +- .../321-tls-substrate-corrective.md | 141 ++++++++++++ .../tls-identity/322-reload-alpn-coherence.md | 112 +++++++++ .../321-tls-substrate-corrective.md | 214 ++++++++++++++++++ .../tls-identity/322-reload-alpn-coherence.md | 154 +++++++++++++ plans/registry.md | 5 +- plans/subsystems/tls-identity-roadmap.md | 165 ++++++++++++++ 24 files changed, 1243 insertions(+), 63 deletions(-) create mode 100644 plans/closure/tls-identity/321-tls-substrate-corrective.md create mode 100644 plans/closure/tls-identity/322-reload-alpn-coherence.md create mode 100644 plans/implementation/tls-identity/321-tls-substrate-corrective.md create mode 100644 plans/implementation/tls-identity/322-reload-alpn-coherence.md create mode 100644 plans/subsystems/tls-identity-roadmap.md diff --git a/CHANGELOG.md b/CHANGELOG.md index fd77f416..c30fc031 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## Unreleased + +- **TLS configuration is provider-deterministic.** `eggnet-tls` and the H3 + QUIC assembler build every rustls configuration with the ring provider + explicitly instead of the process default. A consumer graph that also + enables `aws-lc-rs` no longer panics on a valid certificate pair, and the + Python wheel no longer installs a process-global provider as a workaround. +- **ALPN/runtime coherence is validated.** A static TLS configuration or + reload snapshot that advertises `h2` while the runtime has HTTP/2 disabled + (or was built without the `http2` feature) is rejected at build/start, and a + running server rejects it at the reload swap (`ServerHandle::replace_tls_*`) + with the previous identity left live, instead of completing the handshake and + dropping the connection. +- **`--header-timeout` now bounds TLS handshakes.** The CLI maps the flag to + both `header_read_timeout` and `tls_handshake_timeout`, matching the + published security policy instead of leaving the handshake at a fixed 10s. +- **The SNI identity ceiling is order-independent.** The optional default + identity no longer counts toward `MAX_TLS_IDENTITIES`, so 64 named + identities are accepted whether the default is configured first or last. +- **H3 QUIC bounds are validated and typed.** Out-of-range receive windows + and idle timeouts are rejected by `Http3Config::validate` with the field + named, and transport configuration failures no longer surface as + `invalid private key`. + ## 0.5.1 — `eggserve-static` patch (published 2026-10-23) The `eggserve-static` crate is republished on its own line. The rest of the diff --git a/architecture/eggnet-tls.md b/architecture/eggnet-tls.md index 5c16e127..50b2c10f 100644 --- a/architecture/eggnet-tls.md +++ b/architecture/eggnet-tls.md @@ -66,6 +66,15 @@ through `load_tls_config_with_http2` to `http_alpn_protocols(http2)` (offers non-HTTP transports advertise their own identifiers (empty means no ALPN); an explicit override wins over the `http2(bool)` convenience (last call wins). +Every configuration is built with the ring provider explicitly +(`crypto_provider()` in `crates/eggnet-tls/src/lib.rs`), never through +rustls's process-default selection. A consumer graph that also enables +`aws-lc-rs` therefore cannot make construction panic, and key validation uses +the same provider as the handshake configuration. EggServe's compatibility +runtime separately validates that a static configuration or a reload snapshot +does not advertise `h2` when its own HTTP/2 capability is disabled or absent, +both at build/start and when the server handle performs the reload swap. + Bounded inputs (`crates/eggnet-tls/src/lib.rs`): | Bound | Value | Source | diff --git a/crates/eggnet-tls/src/lib.rs b/crates/eggnet-tls/src/lib.rs index b5e6e835..1f48977f 100644 --- a/crates/eggnet-tls/src/lib.rs +++ b/crates/eggnet-tls/src/lib.rs @@ -20,7 +20,8 @@ use rustls::ServerConfig; use rustls_pki_types::pem::PemObject; use rustls_pki_types::{CertificateDer, CertificateRevocationListDer, PrivateKeyDer}; -/// Maximum SNI identities per [`TlsServerConfig`] (exact + wildcard combined). +/// Maximum named SNI identities per [`TlsServerConfig`] (exact + wildcard +/// combined; the optional default identity is separate). pub const MAX_TLS_IDENTITIES: usize = 64; /// Maximum DNS length for an SNI identity (DNS limit, without `*.` prefix). pub const MAX_SNI_LEN: usize = 253; @@ -77,6 +78,11 @@ pub enum TlsError { TrustRootsRequired, /// The ALPN advertisement was malformed or out of bounds. InvalidAlpn(String), + /// The configured crypto provider could not serve the requested + /// protocol versions. + InvalidCryptoProvider(String), + /// A transport adapter's TLS configuration was out of range. + InvalidTransportConfig(String), } impl fmt::Display for TlsError { @@ -110,6 +116,12 @@ impl fmt::Display for TlsError { write!(f, "client authentication requires at least one trust root") } Self::InvalidAlpn(msg) => write!(f, "invalid ALPN protocols: {msg}"), + Self::InvalidCryptoProvider(msg) => { + write!(f, "invalid TLS crypto provider: {msg}") + } + Self::InvalidTransportConfig(msg) => { + write!(f, "invalid transport configuration: {msg}") + } } } } @@ -261,6 +273,15 @@ pub fn parse_crls_pem(pem: &[u8]) -> Result Arc { + Arc::new(rustls::crypto::ring::default_provider()) +} + fn build_single_cert_config( certs: Vec>, key: PrivateKeyDer<'static>, @@ -271,7 +292,9 @@ fn build_single_cert_config( "certificate chain too long (max {MAX_IDENTITY_CHAIN})" ))); } - let mut config = ServerConfig::builder() + let mut config = ServerConfig::builder_with_provider(crypto_provider()) + .with_safe_default_protocol_versions() + .map_err(|e| TlsError::InvalidCryptoProvider(e.to_string()))? .with_no_client_auth() .with_single_cert(certs, key) .map_err(|e| TlsError::InvalidKey(e.to_string()))?; @@ -327,7 +350,7 @@ fn validate_key_pair( certs: &[CertificateDer<'static>], key: &PrivateKeyDer<'static>, ) -> Result<(), TlsError> { - let provider = rustls::crypto::ring::default_provider(); + let provider = crypto_provider(); let signing_key = provider .key_provider .load_private_key(key.clone_key()) @@ -572,7 +595,7 @@ impl TlsServerConfigBuilder { certs: Vec>, key: PrivateKeyDer<'static>, ) -> Result { - if self.identities.len() + usize::from(self.default.is_some()) >= MAX_TLS_IDENTITIES { + if self.identities.len() >= MAX_TLS_IDENTITIES { return Err(TlsError::TooManyIdentities); } let (is_wildcard, normalized) = normalize_sni_name(name)?; @@ -688,7 +711,7 @@ impl TlsServerConfigBuilder { if self.client_auth != ClientAuthMode::Disabled && self.roots.is_empty() { return Err(TlsError::TrustRootsRequired); } - let provider = rustls::crypto::ring::default_provider(); + let provider = crypto_provider(); let mut exact: HashMap> = HashMap::new(); let mut wildcards: Vec<(String, Arc)> = Vec::new(); let mut identity_names: Vec = Vec::new(); @@ -727,7 +750,9 @@ impl TlsServerConfigBuilder { default, }); let verifier = build_client_verifier(self.client_auth, &self.roots, self.crls)?; - let mut config = ServerConfig::builder() + let mut config = ServerConfig::builder_with_provider(crypto_provider()) + .with_safe_default_protocol_versions() + .map_err(|e| TlsError::InvalidCryptoProvider(e.to_string()))? .with_client_cert_verifier(verifier) .with_cert_resolver(resolver); let alpn = self.alpn.unwrap_or_else(|| http_alpn_protocols(self.http2)); @@ -762,7 +787,8 @@ fn build_client_verifier( .add(root.clone()) .map_err(|e| TlsError::InvalidTrustRoots(e.to_string()))?; } - let builder = WebPkiClientVerifier::builder(Arc::new(store)); + let builder = + WebPkiClientVerifier::builder_with_provider(Arc::new(store), crypto_provider()); let builder = if crls.is_empty() { builder } else { @@ -847,7 +873,8 @@ pub fn http_alpn_protocols(http2: bool) -> Vec> { #[cfg(test)] mod tests { - use super::{http_alpn_protocols, normalize_sni_name}; + use super::{http_alpn_protocols, normalize_sni_name, ClientAuthMode, TlsServerConfig}; + use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; #[test] fn h2_alpn_is_preferred_only_when_enabled() { @@ -875,4 +902,25 @@ mod tests { assert!(!wild); assert_eq!(norm, "example.com"); } + + /// This test binary links both rustls providers (the `tokio-rustls` + /// dev-dependency enables `aws-lc-rs`), so the process-default builder + /// would panic here. Construction must be provider-explicit. + #[test] + fn construction_does_not_require_a_process_default_provider() { + let key_pair = rcgen::KeyPair::generate().expect("key pair"); + let params = rcgen::CertificateParams::new(vec!["provider.test".to_owned()]) + .expect("certificate params"); + let cert = params.self_signed(&key_pair).expect("certificate"); + let cert_der: CertificateDer<'static> = cert.into(); + let key: PrivateKeyDer<'static> = PrivatePkcs8KeyDer::from(key_pair.serialize_der()).into(); + let config = TlsServerConfig::builder() + .single_identity(vec![cert_der.clone()], key) + .expect("identity") + .client_auth_required(vec![cert_der]) + .expect("trust roots") + .build() + .expect("provider-explicit build"); + assert_eq!(config.client_auth(), ClientAuthMode::Required); + } } diff --git a/crates/eggnet-tls/tests/neutral_tls.rs b/crates/eggnet-tls/tests/neutral_tls.rs index aa5b18aa..2963ac9c 100644 --- a/crates/eggnet-tls/tests/neutral_tls.rs +++ b/crates/eggnet-tls/tests/neutral_tls.rs @@ -5,8 +5,8 @@ use std::sync::Arc; use eggnet_tls::{ http_alpn_protocols, load_tls_config_with_alpn, parse_crls_pem, parse_identity_pem, parse_trust_roots_pem, ClientAuthMode, TlsError, TlsReloadHandle, TlsServerConfig, - MAX_ALPN_PROTOCOLS, MAX_ALPN_PROTOCOL_LEN, MAX_IDENTITY_CHAIN, MAX_TRUST_PEM_BYTES, - MAX_TRUST_ROOTS, + MAX_ALPN_PROTOCOLS, MAX_ALPN_PROTOCOL_LEN, MAX_IDENTITY_CHAIN, MAX_TLS_IDENTITIES, + MAX_TRUST_PEM_BYTES, MAX_TRUST_ROOTS, }; use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName}; use rustls_pki_types::pem::PemObject; @@ -349,3 +349,45 @@ async fn custom_alpn_negotiates_end_to_end() { Some(b"eggress-tunnel".as_slice()) ); } + +/// The named-identity ceiling is order-independent and excludes the optional +/// default identity; a 65th named identity is rejected. +#[test] +fn identity_ceiling_excludes_the_optional_default() { + let shared = identity("shared.test"); + + let mut builder = TlsServerConfig::builder() + .single_identity(shared.certs.clone(), shared.key.clone_key()) + .expect("default identity"); + for i in 0..MAX_TLS_IDENTITIES { + builder = builder + .add_identity( + &format!("h{i}.test"), + shared.certs.clone(), + shared.key.clone_key(), + ) + .expect("identity within the documented ceiling"); + } + let built = builder.build().expect("ceiling build"); + assert_eq!(built.identities().len(), MAX_TLS_IDENTITIES); + assert!(built.has_default_identity()); + + let mut overflow = TlsServerConfig::builder(); + for i in 0..MAX_TLS_IDENTITIES { + overflow = overflow + .add_identity( + &format!("o{i}.test"), + shared.certs.clone(), + shared.key.clone_key(), + ) + .expect("identity within the documented ceiling"); + } + assert!(matches!( + overflow.add_identity( + "overflow.test", + shared.certs.clone(), + shared.key.clone_key() + ), + Err(TlsError::TooManyIdentities) + )); +} diff --git a/crates/eggserve-bin/src/args.rs b/crates/eggserve-bin/src/args.rs index 9b933070..9a2f2099 100644 --- a/crates/eggserve-bin/src/args.rs +++ b/crates/eggserve-bin/src/args.rs @@ -54,6 +54,7 @@ pub struct Args { max_connections: Option, max_file_streams: Option, max_in_flight_requests: Option, + /// Header-read timeout; also the documented TLS handshake bound. header_read_timeout: Option, connection_total_timeout: Option, handler_timeout: Option, @@ -837,6 +838,9 @@ impl Args { } if let Some(v) = self.header_read_timeout { limits.header_read_timeout = v; + // One documented bound covers both phases: a slow or stalled TLS + // client must not outlive the header-read window. + limits.tls_handshake_timeout = v; } if let Some(v) = self.connection_total_timeout { limits.connection_total_timeout = v; @@ -902,7 +906,7 @@ pub fn print_usage() { println!(" --max-connections Max concurrent connections (default: 64)"); println!(" --max-file-streams Max concurrent file streams (default: 32)"); println!(" --max-in-flight-requests Max concurrent service executions (default: 64)"); - println!(" --header-timeout Header read timeout in seconds (default: 10)"); + println!(" --header-timeout Header read and TLS handshake timeout (default: 10)"); println!(" --connection-total-timeout Total connection lifetime timeout in seconds (default: 60)"); println!(" --handler-timeout Handler invocation timeout in seconds (default: 30)"); println!(" --body-read-timeout Request body read timeout in seconds (default: 30)"); @@ -1259,13 +1263,13 @@ mod tests { #[test] fn bind_and_port_separate_flags() { - let args = parse(&["--bind", "192.168.1.1:3000"]).unwrap(); + let args = parse(&["--bind", "192.168.1.1:3000", "--public"]).unwrap(); assert_eq!(args.bind, "192.168.1.1:3000".parse().unwrap()); } #[test] fn bind_host_only_preserves_default_port() { - let args = parse(&["--bind", "192.168.1.1"]).unwrap(); + let args = parse(&["--bind", "192.168.1.1", "--public"]).unwrap(); assert_eq!(args.bind.ip(), "192.168.1.1".parse::().unwrap()); assert_eq!(args.bind.port(), 8000); } @@ -1702,6 +1706,14 @@ mod tests { assert_eq!(limits.max_file_streams, 64); } + #[test] + fn header_timeout_also_bounds_tls_handshakes() { + let args = parse(&["--header-timeout", "4"]).unwrap(); + let limits = args.limits().unwrap(); + assert_eq!(limits.header_read_timeout, Duration::from_secs(4)); + assert_eq!(limits.tls_handshake_timeout, Duration::from_secs(4)); + } + #[test] fn plan164_limits_override_defaults() { let args = parse(&[ diff --git a/crates/eggserve-core/src/server/config/runtime.rs b/crates/eggserve-core/src/server/config/runtime.rs index dd87a090..ff80923b 100644 --- a/crates/eggserve-core/src/server/config/runtime.rs +++ b/crates/eggserve-core/src/server/config/runtime.rs @@ -393,9 +393,10 @@ impl RuntimeConfig { /// [`crate::server::RuntimeState::try_new`] / [`crate::server::ServerBuilder::build`], /// which all enforce it. /// - /// Checks the shared runtime kernel plus `ResponsePolicy`. Feature-gated - /// TLS has no additional scalar invariants beyond presence; handshake - /// timeout is part of the shared kernel. + /// Checks the shared runtime kernel, `ResponsePolicy`, the HTTP/2 and + /// HTTP/3 policies, and TLS ALPN coherence. A TLS configuration (static + /// or the current reload snapshot) that advertises `h2` requires HTTP/2 + /// to be enabled in a build that supports it. /// /// Services may lower request-body ceilings but cannot raise this runtime /// hard ceiling. @@ -424,9 +425,54 @@ impl RuntimeConfig { if self.http3.enabled { self.http3.validate()?; } + // A TLS configuration must not advertise h2 to a runtime that cannot + // serve it; otherwise the handshake succeeds and the connection is + // dropped afterwards (accept.rs rejects the negotiated protocol). + #[cfg(all(feature = "tls", feature = "http2"))] + if !self.http2.enabled + && self + .effective_tls_config() + .is_some_and(|tls| Self::tls_advertises_h2(&tls)) + { + return Err(crate::server::errors::ServerError::Config( + "TLS ALPN advertises h2 but http2.enabled is false".into(), + )); + } + #[cfg(all(feature = "tls", not(feature = "http2")))] + if self + .effective_tls_config() + .is_some_and(|tls| Self::tls_advertises_h2(&tls)) + { + return Err(crate::server::errors::ServerError::Config( + "TLS ALPN advertises h2 but this build has no http2 feature".into(), + )); + } Ok(()) } + /// The TLS configuration new handshakes will read: the reload snapshot + /// when configured, otherwise the static compatibility configuration. + #[cfg(feature = "tls")] + fn effective_tls_config(&self) -> Option> { + if let Some(handle) = &self.tls_reload_handle { + Some(handle.current()) + } else { + self.tls_config.clone() + } + } + + /// Whether a TLS configuration advertises the H2 ALPN protocol. + /// + /// Shared with the server handle's reload coherence check so build/start + /// validation and swap-time validation use the same advertisement test. + #[cfg(feature = "tls")] + pub(crate) fn tls_advertises_h2(config: &rustls::ServerConfig) -> bool { + config + .alpn_protocols + .iter() + .any(|protocol| protocol.as_slice() == b"h2".as_slice()) + } + /// Project shared runtime values into a [`RuntimeConfig`] (Plan 179 Track D). /// /// Single helper for the `ServeConfig` bridge so field-by-field diff --git a/crates/eggserve-core/src/server/config/tls.rs b/crates/eggserve-core/src/server/config/tls.rs index 59d72e68..5d869974 100644 --- a/crates/eggserve-core/src/server/config/tls.rs +++ b/crates/eggserve-core/src/server/config/tls.rs @@ -5,6 +5,8 @@ //! `crate::tls`. This module is the protocol owner for future TLS-specific //! defaults/validation; shared constraints stay in `crate::runtime_limits`. //! No new knobs are added by the split; builder setters stay on -//! [`super::RuntimeConfigBuilder`] in the parent facade. +//! [`super::RuntimeConfigBuilder`] in the parent facade. ALPN coherence +//! between the effective TLS configuration and the HTTP/2 capability is +//! enforced by the parent runtime validator (`runtime::RuntimeConfig::validate`). //! Plan 203 identity/reload semantics are unchanged. diff --git a/crates/eggserve-core/src/server/handle.rs b/crates/eggserve-core/src/server/handle.rs index ddc2549e..98e02aa7 100644 --- a/crates/eggserve-core/src/server/handle.rs +++ b/crates/eggserve-core/src/server/handle.rs @@ -31,6 +31,11 @@ use tokio::sync::broadcast; use crate::server::errors::{ServerError, ShutdownResult}; use crate::server::lifecycle::Lifecycle; +#[cfg(all(feature = "tls", feature = "http2"))] +const H2_ALPN_CONFLICT: &str = "TLS ALPN advertises h2 but http2.enabled is false"; +#[cfg(all(feature = "tls", not(feature = "http2")))] +const H2_ALPN_CONFLICT: &str = "TLS ALPN advertises h2 but this build has no http2 feature"; + /// Handle to a running server instance. /// /// This type is experimental and its API may change without notice. @@ -54,6 +59,10 @@ pub struct ServerHandle { ops: crate::ops::OpsContext, #[cfg(feature = "tls")] tls_reload: Option, + /// Whether this runtime serves HTTP/2, captured at start so a reload swap + /// can reject an ALPN advertisement the accept loop cannot serve. + #[cfg(feature = "tls")] + tls_h2_enabled: bool, } impl std::fmt::Debug for ServerHandle { @@ -105,6 +114,8 @@ impl ServerHandle { ops, #[cfg(feature = "tls")] tls_reload: None, + #[cfg(feature = "tls")] + tls_h2_enabled: false, } } @@ -116,6 +127,7 @@ impl ServerHandle { lifecycle: std::sync::Arc, ops: crate::ops::OpsContext, tls_reload: Option, + tls_h2_enabled: bool, ) -> Self { Self { endpoints, @@ -124,30 +136,38 @@ impl ServerHandle { lifecycle, ops, tls_reload, + tls_h2_enabled, } } /// Atomically replace TLS identity/trust for new handshakes (Plan 203 F). /// - /// All-or-nothing: build the replacement first (validation happens in - /// `TlsServerConfigBuilder::build`); this swap never fails and never - /// touches established sessions. Returns an error when the server has no - /// reload handle (plaintext or legacy `tls_config`-only servers). + /// Build the replacement first (`TlsServerConfigBuilder::build` validates + /// it). The swap then rejects a snapshot that advertises `h2` while this + /// runtime cannot serve HTTP/2, leaving the live snapshot unchanged; + /// otherwise it never touches established sessions. Returns an error when + /// the server has no reload handle (plaintext or legacy `tls_config`-only + /// servers). #[cfg(feature = "tls")] pub fn replace_tls_config( &self, next: std::sync::Arc, ) -> Result<(), crate::server::errors::ServerError> { - self.tls_reload - .as_ref() - .map(|h| { - h.replace(next); - }) - .ok_or_else(|| { - crate::server::errors::ServerError::Config( - "TLS reload not configured for this server".into(), - ) - }) + let Some(reload) = self.tls_reload.as_ref() else { + return Err(crate::server::errors::ServerError::Config( + "TLS reload not configured for this server".into(), + )); + }; + // `accept_tls` would otherwise complete the handshake and drop the + // connection after observing a negotiated protocol the runtime cannot + // serve. Reject before the swap so the previous identity stays live. + if !self.tls_h2_enabled && crate::server::RuntimeConfig::tls_advertises_h2(&next) { + return Err(crate::server::errors::ServerError::Config( + H2_ALPN_CONFLICT.into(), + )); + } + reload.replace(next); + Ok(()) } /// Replace from a validated [`crate::tls::TlsServerConfig`]. @@ -160,6 +180,10 @@ impl ServerHandle { } /// Current TLS snapshot for observability/tests, if TLS is configured. + /// + /// Replacing through the returned handle bypasses this server's runtime + /// coherence check; prefer [`Self::replace_tls_config`] or + /// [`Self::replace_tls_server_config`]. #[cfg(feature = "tls")] pub fn tls_reload_handle(&self) -> Option { self.tls_reload.clone() diff --git a/crates/eggserve-core/src/server/mod.rs b/crates/eggserve-core/src/server/mod.rs index 29e3b776..62e00f3b 100644 --- a/crates/eggserve-core/src/server/mod.rs +++ b/crates/eggserve-core/src/server/mod.rs @@ -688,6 +688,10 @@ impl Server { #[cfg(feature = "tls")] let tls_reload_for_handle = runtime_config.tls_reload_handle.clone(); + #[cfg(all(feature = "tls", feature = "http2"))] + let tls_h2_for_handle = runtime_config.http2.enabled; + #[cfg(all(feature = "tls", not(feature = "http2")))] + let tls_h2_for_handle = false; let config = Arc::new(runtime_config); let runtime_state = Arc::new(RuntimeState::with_ops(&config, ops.clone())?); let connection_semaphore = Arc::new(tokio::sync::Semaphore::new(config.max_connections)); @@ -774,6 +778,7 @@ impl Server { lifecycle, ops, tls_reload_for_handle, + tls_h2_for_handle, ); #[cfg(not(feature = "tls"))] let handle = diff --git a/crates/eggserve-core/tests/tls_identity.rs b/crates/eggserve-core/tests/tls_identity.rs index 0a1d0720..0a99934f 100644 --- a/crates/eggserve-core/tests/tls_identity.rs +++ b/crates/eggserve-core/tests/tls_identity.rs @@ -1139,3 +1139,102 @@ async fn alpn_parity_survives_reload() { handle.shutdown(); let _ = handle.wait().await; } + +/// H2 must not be advertised unless the runtime serves it; the static +/// configuration and the current reload snapshot are both checked. +#[cfg(feature = "http2")] +#[test] +fn tls_alpn_h2_requires_runtime_http2() { + use eggserve_core::server::Http2Config; + + let a = make_identity(vec!["localhost"]); + let tls = TlsServerConfig::builder() + .single_identity(a.certs.clone(), a.key.clone_key()) + .expect("identity") + .http2(true) + .build() + .expect("h2 config"); + assert!(tls.alpn_protocols().contains(&b"h2".to_vec())); + + let disabled = Http2Config { + enabled: false, + ..Default::default() + }; + let config = eggserve_core::server::RuntimeConfig::builder() + .bind("127.0.0.1:0".parse().unwrap()) + .http2(disabled.clone()) + .tls_config(tls.into_server_config()) + .build() + .expect("builder"); + let error = config.validate().unwrap_err().to_string(); + assert!(error.contains("http2.enabled"), "{error}"); + + let reload = TlsReloadHandle::from_tls_server_config(&tls); + let config = eggserve_core::server::RuntimeConfig::builder() + .bind("127.0.0.1:0".parse().unwrap()) + .http2(disabled) + .tls_reload_handle(reload) + .build() + .expect("builder"); + let error = config.validate().unwrap_err().to_string(); + assert!(error.contains("http2.enabled"), "{error}"); +} + +/// A reload through the running server must not install an h2 advertisement +/// the accept loop cannot serve; the previous identity stays live. +#[cfg(feature = "http2")] +#[tokio::test] +async fn reload_rejects_h2_alpn_when_http2_disabled() { + use eggserve_core::server::Http2Config; + + let a = make_identity(vec!["localhost"]); + let http1 = TlsServerConfig::builder() + .single_identity(a.certs.clone(), a.key.clone_key()) + .expect("identity") + .http2(false) + .build() + .expect("http/1.1 config"); + let reload = TlsReloadHandle::from_tls_server_config(&http1); + let config = eggserve_core::server::RuntimeConfig::builder() + .bind("127.0.0.1:0".parse().unwrap()) + .http2(Http2Config { + enabled: false, + ..Default::default() + }) + .tls_reload_handle(reload) + .build() + .expect("builder"); + let server = Server::builder().runtime(config).build().unwrap(); + let handle = server.start_with_service(echo_service()).await.unwrap(); + handle.ready().await.unwrap(); + + let h2 = TlsServerConfig::builder() + .single_identity(a.certs.clone(), a.key.clone_key()) + .expect("identity") + .http2(true) + .build() + .expect("h2 config"); + let error = handle + .replace_tls_server_config(&h2) + .expect_err("h2 ALPN must be rejected at swap time"); + assert!(error.to_string().contains("http2.enabled"), "{error}"); + + // The rejected swap left the live HTTP/1.1 identity in place. + let response = tls_get( + handle.local_addr(), + client_config_for(std::slice::from_ref(&a.cert_der_bytes), None), + "localhost", + GET_CLOSE, + ) + .await + .expect("http/1.1 after rejected reload"); + assert!(String::from_utf8_lossy(&response).starts_with("HTTP/1.1 200")); + + // A coherent snapshot is still accepted. + handle + .replace_tls_server_config(&http1) + .expect("coherent reload"); + + handle.shutdown(); + let _ = handle.wait().await; +} diff --git a/crates/eggserve-h3/src/config.rs b/crates/eggserve-h3/src/config.rs index 83e8d211..a8daaa91 100644 --- a/crates/eggserve-h3/src/config.rs +++ b/crates/eggserve-h3/src/config.rs @@ -7,6 +7,9 @@ use std::time::Duration; +/// Largest value representable by a QUIC VarInt (2^62 - 1). +const QUIC_VARINT_MAX: u64 = (1 << 62) - 1; + /// EggServe-owned HTTP/3 and QUIC resource limits. /// /// HTTP/3 is experimental. The defaults keep the product disabled until a @@ -84,8 +87,17 @@ impl Http3Config { "must leave room for H3 control and QPACK streams", )); } - if self.stream_receive_window == 0 || self.connection_receive_window == 0 { - return Err(invalid("receive_window", "must be greater than zero")); + if self.stream_receive_window == 0 || self.stream_receive_window > QUIC_VARINT_MAX { + return Err(invalid( + "stream_receive_window", + "must be between 1 and 2^62-1 bytes", + )); + } + if self.connection_receive_window == 0 || self.connection_receive_window > QUIC_VARINT_MAX { + return Err(invalid( + "connection_receive_window", + "must be between 1 and 2^62-1 bytes", + )); } if self.connection_receive_window < self.stream_receive_window { return Err(invalid( @@ -96,8 +108,13 @@ impl Http3Config { if self.send_window == 0 || self.max_send_buf_size == 0 { return Err(invalid("send_window", "must be greater than zero")); } - if self.max_idle_timeout.is_zero() { - return Err(invalid("max_idle_timeout", "must be greater than zero")); + if self.max_idle_timeout.is_zero() + || self.max_idle_timeout.as_millis() > u128::from(QUIC_VARINT_MAX) + { + return Err(invalid( + "max_idle_timeout", + "must be between 1ms and 2^62-1ms", + )); } if self.max_pending_handshakes == 0 { return Err(invalid( @@ -114,3 +131,49 @@ impl Http3Config { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::{Http3Config, QUIC_VARINT_MAX}; + use std::time::Duration; + + #[test] + fn quic_window_bounds_are_validated() { + let too_large = Http3Config { + stream_receive_window: QUIC_VARINT_MAX + 1, + ..Default::default() + }; + let error = too_large.validate().unwrap_err().to_string(); + assert!(error.contains("http3.stream_receive_window"), "{error}"); + + let too_large = Http3Config { + connection_receive_window: QUIC_VARINT_MAX + 1, + ..Default::default() + }; + let error = too_large.validate().unwrap_err().to_string(); + assert!(error.contains("http3.connection_receive_window"), "{error}"); + + let at_limit = Http3Config { + stream_receive_window: QUIC_VARINT_MAX, + connection_receive_window: QUIC_VARINT_MAX, + ..Default::default() + }; + assert!(at_limit.validate().is_ok()); + } + + #[test] + fn quic_idle_timeout_bound_is_validated() { + let too_large = Http3Config { + max_idle_timeout: Duration::from_millis(QUIC_VARINT_MAX + 1), + ..Default::default() + }; + let error = too_large.validate().unwrap_err().to_string(); + assert!(error.contains("http3.max_idle_timeout"), "{error}"); + + let at_limit = Http3Config { + max_idle_timeout: Duration::from_millis(QUIC_VARINT_MAX), + ..Default::default() + }; + assert!(at_limit.validate().is_ok()); + } +} diff --git a/crates/eggserve-h3/src/quic.rs b/crates/eggserve-h3/src/quic.rs index 6b6a67e1..c3521340 100644 --- a/crates/eggserve-h3/src/quic.rs +++ b/crates/eggserve-h3/src/quic.rs @@ -25,10 +25,14 @@ pub fn load_quic_server_config( use eggnet_tls::TlsError; let (certs, key) = eggnet_tls::load_identity(cert_path, key_path)?; - let mut tls = rustls::ServerConfig::builder_with_protocol_versions(&[&rustls::version::TLS13]) - .with_no_client_auth() - .with_single_cert(certs, key) - .map_err(|e| TlsError::InvalidKey(e.to_string()))?; + let mut tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(|e| TlsError::InvalidCryptoProvider(e.to_string()))? + .with_no_client_auth() + .with_single_cert(certs, key) + .map_err(|e| TlsError::InvalidKey(e.to_string()))?; tls.alpn_protocols = vec![b"h3".to_vec()]; tls.max_early_data_size = 0; let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(Arc::new(tls)) @@ -39,17 +43,26 @@ pub fn load_quic_server_config( .max_concurrent_bidi_streams(quinn::VarInt::from_u32(config.max_concurrent_bidi_streams)) .max_concurrent_uni_streams(quinn::VarInt::from_u32(config.max_concurrent_uni_streams)) .stream_receive_window( - quinn::VarInt::try_from(config.stream_receive_window) - .map_err(|_| TlsError::InvalidKey("stream receive window too large".into()))?, + quinn::VarInt::try_from(config.stream_receive_window).map_err(|_| { + TlsError::InvalidTransportConfig( + "stream_receive_window exceeds the QUIC VarInt range".into(), + ) + })?, ) .receive_window( - quinn::VarInt::try_from(config.connection_receive_window) - .map_err(|_| TlsError::InvalidKey("connection receive window too large".into()))?, + quinn::VarInt::try_from(config.connection_receive_window).map_err(|_| { + TlsError::InvalidTransportConfig( + "connection_receive_window exceeds the QUIC VarInt range".into(), + ) + })?, ) .send_window(config.send_window) .max_idle_timeout(Some( - quinn::IdleTimeout::try_from(config.max_idle_timeout) - .map_err(|_| TlsError::InvalidKey("idle timeout too large".into()))?, + quinn::IdleTimeout::try_from(config.max_idle_timeout).map_err(|_| { + TlsError::InvalidTransportConfig( + "max_idle_timeout exceeds the QUIC VarInt range".into(), + ) + })?, )); let mut server = quinn::ServerConfig::with_crypto(Arc::new(crypto)); diff --git a/crates/eggserve-python/src/server/runtime.rs b/crates/eggserve-python/src/server/runtime.rs index 30bb310f..394f4933 100644 --- a/crates/eggserve-python/src/server/runtime.rs +++ b/crates/eggserve-python/src/server/runtime.rs @@ -172,10 +172,6 @@ impl PyServer { forwarded_standard: bool, forwarded_legacy: bool, ) -> PyResult { - // rustls can be built with more than one provider through the - // workspace's feature-unified dependency graph. Select the same - // ring provider used by the CLI before constructing TLS config. - let _ = rustls::crypto::ring::default_provider().install_default(); let bind_addr: SocketAddr = (bind, port) .to_socket_addrs() .map_err(|_| { diff --git a/docs/cli.md b/docs/cli.md index ca947c10..2b7f7f87 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -98,7 +98,7 @@ Hyper exposes no aggregate header-byte, request-target, or request-line knob: th | Flag | Description | Default | |------|-------------|---------| -| `--header-timeout SECS` | Header read timeout (seconds) | `10` | +| `--header-timeout SECS` | Header read and TLS handshake timeout (seconds) | `10` | | `--connection-total-timeout SECS` | Total connection lifetime timeout (seconds) | `60` | | `--handler-timeout SECS` | Handler invocation timeout (seconds) | `30` | | `--body-read-timeout SECS` | Request body read timeout (seconds) | `30` | diff --git a/docs/deployment.md b/docs/deployment.md index 7e7894ae..1a66d7f9 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -113,7 +113,7 @@ Independent budgets for connections, in-flight service work, parser memory, and Notes: - **Reverse-proxy production** favors persistent connections, bounded parser memory, meaningful service concurrency, and idle/write-stall defense. Raise the total lifetime into the hours so it acts purely as defense-in-depth; the idle and write timers bound routine use. Keep `header-timeout` at or above the proxy's keep-alive gap, otherwise Hyper closes healthy idle connections and they count as header timeouts. -- **Direct TLS** uses the same core bounds plus the existing TLS handshake budget (10s code default; no CLI flag). +- **Direct TLS** uses the same core bounds plus the TLS handshake budget, which follows `--header-timeout` (10s by default). Raising or lowering the header window moves the handshake bound with it. - **Embedded anonymity-sensitive** uses stricter open-connection, header, keep-alive, request-count, and write-stall bounds suitable for resource-constrained direct origins. This is still not rate limiting: all clients share the same generic resource budgets — there are no per-IP/client/user token buckets, authentication quotas, or reputation logic anywhere in the core. - Every production claim must name a profile from the production profiles defined in this guide. Hardened profiles must not allow symlink following. diff --git a/docs/security-policy.md b/docs/security-policy.md index b669f446..3c19a19a 100644 --- a/docs/security-policy.md +++ b/docs/security-policy.md @@ -156,7 +156,7 @@ supported. The TLS feature is optional and not included in the default build. For public-facing deployments, a reverse proxy (Caddy, nginx, Traefik) is usually preferred over native TLS. -TLS handshakes are bounded by the same timeout as HTTP header reads (`--header-timeout`, default 10 seconds). A slow or stalled TLS client cannot tie up a connection beyond this window. +TLS handshakes are bounded by the same timeout as HTTP header reads (`--header-timeout` sets both deadlines; default 10 seconds). A slow or stalled TLS client cannot tie up a connection beyond this window. ## Compatibility mode diff --git a/docs/timeout-reference.md b/docs/timeout-reference.md index e665ce53..01bc8c51 100644 --- a/docs/timeout-reference.md +++ b/docs/timeout-reference.md @@ -7,7 +7,7 @@ This document defines every timeout and lifecycle deadline in the eggserve runti | # | Name | Config field | Default | Clock starts | Progress resets | What constitutes progress | Enforcement owner | Terminal behavior | Cleanup | |---|------|-------------|---------|-------------|----------------|--------------------------|-------------------|-------------------|---------| | 1 | Listener backoff | *(internal)* | 1–500ms exponential | On accept error | On each backoff step | Successful accept or different error kind | `eggserve_server::accept_error` (shared by both accept loops) | Error classified as fatal → break accept loop | Backoff state resets on success | -| 2 | TLS handshake timeout | `tls_handshake_timeout` | 10s | TCP accept (TLS path) | No | N/A | `accept_tls()` in accept loop | Handshake aborted, connection dropped | Stream/acceptor dropped | +| 2 | TLS handshake timeout | `tls_handshake_timeout` | 10s | TCP accept, after the optional PROXY preamble | No | N/A | `accept_tls()` in accept loop | Handshake aborted, connection dropped | Stream/acceptor dropped | | 3 | Request-header timeout | `header_read_timeout` | 10s | HTTP/1 connection created | No | Complete header block received | Hyper `http1::Builder::header_read_timeout` | 408 Request Timeout | Hyper closes connection | | 4 | Request-body timeout | `body_read_timeout` | 30s | Body ingestion begins | No | Body fully consumed (all frames read) | `serve_connection_with_service()` | 408 Request Timeout response | Body dropped, connection kept alive | | 5 | Handler timeout | `handler_timeout` | 30s | Service `call()` invoked | No | Service future completes | `tokio::time::timeout` in `serve_connection_with_service()` | 504 Gateway Timeout response | Service future dropped | @@ -38,10 +38,10 @@ and shutdown limits continue to apply. ### 2. TLS handshake timeout -- **Clock starts**: TCP connection accepted on TLS-enabled listener. +- **Clock starts**: TCP connection accepted on TLS-enabled listener (after the optional PROXY preamble, which has its own timeout). - **Progress resets**: No — this is a one-shot deadline. - **Progress definition**: N/A (single operation). -- **Enforcement**: `tokio::time::timeout(tls_handshake_timeout, tls_acceptor.accept(stream))`. +- **Enforcement**: `tokio::time::timeout(tls_handshake_timeout, tls_acceptor.accept(stream))`. The CLI `--header-timeout` sets this field together with `header_read_timeout`; Rust callers may set it independently. - **Terminal behavior**: Handshake aborted, connection dropped. No event emitted beyond `TlsHandshakeTimeout`. - **Cleanup**: TCP stream and TLS acceptor dropped. diff --git a/docs/tls.md b/docs/tls.md index 9955656a..14105ae1 100644 --- a/docs/tls.md +++ b/docs/tls.md @@ -1,6 +1,6 @@ # TLS Support -eggserve supports optional native TLS termination via [rustls](https://docs.rs/rustls). TLS is behind a feature flag and is **not** included in the default build. The reusable identity, trust, client-authentication, and reload substrate is the neutral [`eggnet-tls`](../architecture/eggnet-tls.md) crate; EggServe re-exports it through `eggserve_core::tls` while retaining only transport and HTTP/3-specific assembly. +eggserve supports optional native TLS termination via [rustls](https://docs.rs/rustls). TLS is behind a feature flag and is **not** included in the default build. Every TLS configuration is built with rustls's ring crypto provider explicitly, so applications never need to install a process-default `CryptoProvider`; a dependency graph that also enables `aws-lc-rs` cannot turn configuration construction into a panic. The reusable identity, trust, client-authentication, and reload substrate is the neutral [`eggnet-tls`](../architecture/eggnet-tls.md) crate; EggServe re-exports it through `eggserve_core::tls` while retaining only transport and HTTP/3-specific assembly. ## When to use native TLS @@ -134,8 +134,12 @@ Handshake and admission: - Slow clients cannot occupy unlimited tasks (connection semaphore + per-handshake deadline; permits released exactly once). Selection/verification performs no unbounded blocking work. Errors use fixed sanitized categories and never echo - rustls internals to clients. H2 ALPN derives from `RuntimeConfig.http2.enabled`; - H3 uses a separate TLS 1.3/`h3` QUIC config (see below). + rustls internals to clients. A TLS configuration that advertises `h2` must + agree with `RuntimeConfig.http2.enabled` (and with the compiled `http2` + feature); the runtime rejects a contradictory static configuration at + build/start and rejects a contradictory snapshot when the server handle swaps + it in, instead of completing the handshake and dropping the connection. H3 + uses a separate TLS 1.3/`h3` QUIC config (see below). Atomic reload: @@ -157,9 +161,13 @@ handle.replace_tls_server_config(&next)?; // new handshakes only; established ke ``` - Immutable validated objects + atomic snapshot read by new handshakes; failed - builds never touch live state. No filesystem watcher. H3 rotation requires - endpoint replacement/drain (Quinn `set_server_config` handoff); TCP reload does - not atomically rotate H3 — see “H3 coherence”. + builds never touch live state. `ServerHandle::replace_tls_config` / + `replace_tls_server_config` additionally reject a snapshot whose ALPN the + runtime cannot serve, leaving the previous identity live. Replacing through + the raw `TlsReloadHandle` returned by `ServerHandle::tls_reload_handle` + bypasses that check. No filesystem watcher. H3 rotation requires endpoint + replacement/drain (Quinn `set_server_config` handoff); TCP reload does not + atomically rotate H3 — see “H3 coherence”. Session resumption and 0-RTT: @@ -185,7 +193,7 @@ Python projection: ## Handshake timeout -TLS handshakes are bounded by `tls_handshake_timeout` (CLI `--header-timeout` surface, default 10 seconds; `RuntimeConfig.tls_handshake_timeout`). A client that opens a TCP connection but never completes the TLS handshake will hold a connection permit for at most that duration; after timeout the connection is dropped silently. The connection-permit semaphore prevents an unbounded number of pending handshakes, and the per-handshake timeout prevents a single slow client from holding a permit indefinitely. Permits recover after timeout; new handshakes succeed. +TLS handshakes are bounded by `tls_handshake_timeout` (CLI `--header-timeout`, default 10 seconds; Rust callers also set `RuntimeConfig.tls_handshake_timeout` directly). The CLI flag sets both `header_read_timeout` and `tls_handshake_timeout`, so one documented window covers both phases. A client that opens a TCP connection but never completes the TLS handshake will hold a connection permit for at most that duration; after timeout the connection is dropped silently. The connection-permit semaphore prevents an unbounded number of pending handshakes, and the per-handshake timeout prevents a single slow client from holding a permit indefinitely. Permits recover after timeout; new handshakes succeed. ## Certificate requirements diff --git a/plans/closure/tls-identity/321-tls-substrate-corrective.md b/plans/closure/tls-identity/321-tls-substrate-corrective.md new file mode 100644 index 00000000..0e07b2a8 --- /dev/null +++ b/plans/closure/tls-identity/321-tls-substrate-corrective.md @@ -0,0 +1,141 @@ +# TLS Identity Milestone 321 - Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-identity/321-tls-substrate-corrective.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-identity-roadmap.md#7` + +Repository baseline reviewed: `26649bd` (working tree; changes not committed by this agent) + +Implementation commits or pull requests: + +- not yet committed (working tree on `26649bd`; commit is a user-owned action) + +## 1. Executive finding + +The five reviewed TLS seam defects are corrected and each has a regression test that fails on the pre-fix behavior: provider-explicit construction, ALPN/HTTP2 coherence validation, the documented header/TLS timeout coupling, the order-independent SNI identity ceiling, and typed H3 QUIC transport-bound errors. Every milestone-owned lane passes, including the Python crate check and clippy, the 1.89 MSRV check, and the H3 feature lanes. + +The broad wrapper `./scripts/verify.sh fast` does not complete on this macOS host because of two pre-existing failures in untouched crates (details in section 10); the equivalent remaining lanes were run directly and are recorded below. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Construction never depends on a process-default rustls provider | `eggnet-tls` unit test `construction_does_not_require_a_process_default_provider`; test graph compiles both `ring` and `aws-lc-rs` | pass | Pre-fix this test panics in `ServerConfig::builder()`. | +| TLS ALPN agrees with HTTP/2 availability | `tls_identity::tls_alpn_h2_requires_runtime_http2` (static config and reload snapshot) | pass | Pre-fix `validate()` returned `Ok`; the accept loop dropped the connection after the handshake. | +| `--header-timeout` bounds TLS handshakes | `args::tests::header_timeout_also_bounds_tls_handshakes`; `docs/tls.md`, `docs/security-policy.md`, `docs/deployment.md`, `docs/cli.md`, `docs/timeout-reference.md` updated | pass | Pre-fix only `header_read_timeout` moved. | +| Named-identity ceiling is order-independent | `neutral_tls::identity_ceiling_excludes_the_optional_default` | pass | Default-first now accepts 64 named identities; the 65th named identity is rejected. | +| H3 transport bounds are validated and typed | `Http3Config` unit tests for `stream_receive_window`, `connection_receive_window`, `max_idle_timeout`; `quic.rs` uses `InvalidTransportConfig` | pass | Pre-fix out-of-range values surfaced as `invalid private key`. | + +## 3. Production implementation evidence + +- `crates/eggnet-tls/src/lib.rs`: one `crypto_provider()` helper (ring) now serves `build_single_cert_config`, `TlsServerConfigBuilder::build`, `WebPkiClientVerifier::builder_with_provider`, and key-pair validation. Added `TlsError::{InvalidCryptoProvider, InvalidTransportConfig}`. `add_identity` no longer counts the optional default against `MAX_TLS_IDENTITIES`. +- `crates/eggserve-h3/src/quic.rs`: explicit ring provider plus TLS 1.3 protocol versions; VarInt/IdleTimeout range failures use `InvalidTransportConfig`. +- `crates/eggserve-h3/src/config.rs`: `Http3Config::validate` enforces the QUIC VarInt ceiling for both receive windows and the idle timeout, naming the field. +- `crates/eggserve-core/src/server/config/runtime.rs`: `RuntimeConfig::validate` checks the effective TLS configuration (static or current reload snapshot) for an `h2` advertisement when HTTP/2 is disabled or the build lacks the feature. +- `crates/eggserve-bin/src/args.rs`: `--header-timeout` sets both `header_read_timeout` and `tls_handshake_timeout`; usage text updated. Two Plan 320 bind-parsing tests gained the now-required `--public` acknowledgment (out-of-scope incidental; see section 10). +- `crates/eggserve-python/src/server/runtime.rs`: removed the process-global `install_default()` workaround now that every construction path is provider-explicit. +- Documentation: `docs/tls.md`, `docs/security-policy.md`, `docs/deployment.md`, `docs/cli.md`, `docs/timeout-reference.md`, `architecture/eggnet-tls.md`, `CHANGELOG.md`. + +## 4. Verification executed + +### Commands run + +```bash +cargo fmt --all -- --check +git diff --check +python3 scripts/check-crate-topology.py +cargo test -p eggnet-tls +cargo test -p eggserve-h3 +cargo test -p eggserve-core --features tls --test tls_identity +cargo test -p eggserve-core --features http2,tls --test tls_identity +cargo test -p eggserve-core --features http2,tls +cargo test -p eggserve-core --features http3,tls +cargo test -p eggserve-bin --features tls +cargo test -p eggserve-bin --features http2,tls +cargo test -p eggserve-bin --features http3,tls +cargo clippy -p eggnet-tls --all-targets -- -D warnings +cargo clippy -p eggserve-h3 --all-targets -- -D warnings +cargo clippy -p eggserve-core --features http2,tls --lib --tests -- -D warnings +cargo clippy -p eggserve-core --features http3,tls --lib --tests -- -D warnings +cargo clippy -p eggserve-bin --features tls --lib --bins --tests -- -D warnings +cargo clippy -p eggserve-bin --features http2,tls --lib --bins --tests -- -D warnings +cargo clippy --workspace --lib --bins --tests -- -D warnings +cargo check --manifest-path crates/eggserve-python/Cargo.toml --locked +cargo clippy --manifest-path crates/eggserve-python/Cargo.toml --lib -- -D warnings +cargo +1.89 check -p eggserve-core --all-targets --features http2,tls +cargo check --manifest-path fuzz/Cargo.toml --bins --locked +cargo clippy --manifest-path fuzz/Cargo.toml --bins -- -D warnings +./scripts/verify.sh fast # stopped on a pre-existing unrelated test +cargo test --workspace # stopped on a pre-existing macOS-only test +``` + +### Results + +- `eggnet-tls`: 3 unit + 9 integration tests passed, including the provider and identity-ceiling regressions. +- `eggserve-h3`: 15 unit tests passed, including both QUIC bound tests. +- Core TLS identity: 16 tests passed without `http2`; 18 passed with `http2,tls`, including `tls_alpn_h2_requires_runtime_http2`. +- Core suites with `http2,tls` and `http3,tls`: exit 0. +- CLI suites: `--features tls` ran 145 tests across six targets with 0 failures (includes the 12-test TLS abuse lane); `http2,tls` and `http3,tls` lanes exited 0. +- Clippy: every listed lane exited 0, including workspace-wide and the excluded Python crate. +- Python crate `cargo check --locked` and clippy: exit 0. +- MSRV `cargo +1.89 check`: exit 0. +- Topology gate, formatting, `git diff --check`, fuzz check/clippy: pass. +- `./scripts/verify.sh fast`: exit 101 at `eggserve-server` test `app_bounded_body_accepts_and_over_limit_rejects` (ConnectionReset, macOS); never reached later lanes, which were run manually. +- `cargo test --workspace`: exit 101 at the pre-existing `eggserve-static` test `fs::tests::resolve_child_directory_retains_canonical_path` (macOS `/private/var` canonicalization). + +## 5. Invariant review + +- TLS defaults are unchanged: no 0-RTT, TLS 1.3-only QUIC, rustls default ticket policy. +- The ring provider was already the key-validation provider; handshakes now use the same provider instead of a process default. +- CLI and Python remain single-identity; Python remains HTTP/1.1-only; no new capability tier is claimed. +- No key/certificate bytes are added to errors, Debug output, events, or logs; the new errors name configuration fields. +- Bounded metadata (SNI 253, chain 8 x 64 KiB), trust/CRL bounds, and safe defaults are untouched. + +## 6. Failure and recovery review + +- Static configuration contradictions fail at `RuntimeConfig::validate` (called by `ServerBuilder::build` and `Server::start`). +- A reload that introduces an `h2` advertisement on an HTTP/2-disabled runtime is rejected by the per-connection `validate()` call, so connections fail closed; established sessions are untouched. **Correction (milestone 322):** an h2-negotiating client does not reach that validator, because `accept_tls` drops the connection first; the swap-time guard in milestone 322 is the enforcement point. +- Provider selection is stateless and deterministic; no new lock or shared state. +- The identity-cap change does not alter handshake or reload behavior. + +## 7. Migration and compatibility review + +- `TlsError` gains two variants (`InvalidCryptoProvider`, `InvalidTransportConfig`). This is a 0.x diagnostic adjustment; no crate version is bumped in this milestone. +- `--header-timeout` now also bounds TLS handshakes, matching the already-published security policy. An operator lowering the flag tightens both phases; raising it relaxes both. +- Removing the Python process-global provider install has no observable TLS behavior change because construction is explicit. +- No configuration field, default, or public builder method is added or removed. + +## 8. Security review + +- Removes a process-abort path on valid credentials in multi-provider dependency graphs. +- Rejects protocol advertisement the runtime cannot serve, instead of a post-handshake drop. +- Keeps the documented 64 named-identity resource ceiling order-independent. +- The QUIC transport error no longer masquerades as a private-key failure. + +## 9. Documentation and operations + +Updated `docs/tls.md`, `docs/security-policy.md`, `docs/deployment.md`, `docs/cli.md`, `docs/timeout-reference.md`, `architecture/eggnet-tls.md`, and `CHANGELOG.md`. The timeout reference now records the PROXY-preamble ordering and the CLI coupling. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| medium | `eggserve-server` test `app_bounded_body_accepts_and_over_limit_rejects` fails on this macOS host with `ConnectionReset` at the client `read_to_end` (line 205) | `./scripts/verify.sh fast` cannot complete locally | Fix separately in `direct-h1-runtime`: tolerate the reset or assert the 413 on a platform-stable read path. Untouched by this milestone and reproduces alone. | +| low | `eggserve-static` test `resolve_child_directory_retains_canonical_path` fails because macOS resolves `/var` to `/private/var` | `cargo test --workspace` cannot be green locally | Fix separately in `static-confinement` by comparing canonicalized temp paths. Untouched by this milestone. | +| low | Two Plan 320 bind-parsing tests (`bind_and_port_separate_flags`, `bind_host_only_preserves_default_port`) lacked the `--public` acknowledgment required by the baseline gate | The CLI lib suite failed before this milestone's changes | Corrected here by adding `--public`; test intent is preserved. | + +## 11. Roadmap disposition + +Milestone 321 is closed; no hard dependency blocks the next TLS identity or H2/H3 milestone. The two platform-test findings are owned by their respective subsystem roadmaps. + +## 12. Registry updates + +- `plans/registry.md`: TLS identity milestone 321 marked closed with this record; next milestone number 322. +- `plans/subsystems/tls-identity-roadmap.md`: milestone 321 marked closed. +- `plans/implementation/tls-identity/321-tls-substrate-corrective.md`: status implemented. diff --git a/plans/closure/tls-identity/322-reload-alpn-coherence.md b/plans/closure/tls-identity/322-reload-alpn-coherence.md new file mode 100644 index 00000000..7e353f9c --- /dev/null +++ b/plans/closure/tls-identity/322-reload-alpn-coherence.md @@ -0,0 +1,112 @@ +# TLS Identity Milestone 322 - Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-identity/322-reload-alpn-coherence.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-identity-roadmap.md#7` (Milestone 322) + +Repository baseline reviewed: `26649bd` plus the milestone 321 working-tree changes (nothing committed by the agent) + +Implementation commits or pull requests: + +- not yet committed (working tree; commit is a user-owned action) + +## 1. Executive finding + +Milestone 321's ALPN/runtime guarantee is now enforced at the server-owned reload swap. A running server whose HTTP/2 capability is disabled rejects an h2-advertising TLS snapshot before it becomes live, so the accept loop no longer completes a handshake only to drop the connection for every h2-capable client. The regression test fails on the 321 behavior because `replace_tls_server_config` returned `Ok`. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| The reload swap rejects a contradictory snapshot | `tls_identity::reload_rejects_h2_alpn_when_http2_disabled` | pass | Pre-fix the swap returned `Ok` and the next h2 handshake completed before being dropped. | +| A rejected swap leaves the live identity in service | same test: HTTP/1.1 request after the rejected swap returns 200 | pass | The guard runs before `TlsReloadHandle::replace`. | +| A coherent reload is still accepted | same test: final `replace_tls_server_config(&http1)` | pass | Only the h2 advertisement is rejected. | +| H2-enabled servers still accept h2 reloads | existing `alpn_parity_survives_reload` | pass | Runtime capability is captured at start. | + +## 3. Production implementation evidence + +- `crates/eggserve-core/src/server/handle.rs`: `ServerHandle` captures `tls_h2_enabled`; `replace_tls_config` rejects an h2 advertisement before the swap with `ServerError::Config`; the `tls_reload_handle` doc records the raw-handle bypass. +- `crates/eggserve-core/src/server/mod.rs`: the capability is projected from `runtime_config.http2.enabled` at start (false when the `http2` feature is absent). +- `crates/eggserve-core/src/server/config/runtime.rs`: `tls_advertises_h2` is `pub(crate)` and shared by build/start validation and the swap check. +- `crates/eggserve-core/tests/tls_identity.rs`: `reload_rejects_h2_alpn_when_http2_disabled`. +- Documentation: `docs/tls.md`, `CHANGELOG.md`, `architecture/eggnet-tls.md`. + +## 4. Verification executed + +### Commands run + +```bash +cargo fmt --all -- --check +cargo test -p eggserve-core --features http2,tls --test tls_identity +cargo test -p eggserve-core --features tls --test tls_identity +cargo test -p eggserve-core --features http2,tls +cargo clippy -p eggserve-core --features http2,tls --lib --tests -- -D warnings +cargo clippy -p eggserve-core --features tls --lib --tests -- -D warnings +cargo check -p eggserve-core +cargo check -p eggserve-bin --features http2,tls +git diff --check +python3 scripts/check-crate-topology.py +``` + +### Results + +- Core TLS identity with `http2,tls`: 19 passed, including `reload_rejects_h2_alpn_when_http2_disabled`. +- Core TLS identity with `tls` only: 16 passed; the h2-only regression is correctly not compiled. +- Full `eggserve-core` suite with `http2,tls`: exit 0 across every target. +- Clippy for `http2,tls` and for `tls` only: exit 0. +- Default `eggserve-core` check and `eggserve-bin` `http2,tls` check: exit 0 (the default check still prints the pre-existing Cargo `unused_dependencies` warning for `thiserror`). +- `cargo doc -D warnings` is not a repository gate; it reports pre-existing unresolved private-item links in untouched modules and none in this change. + +## 5. Invariant review + +- Reload remains all-or-nothing: the check precedes the swap, and the live `Arc` is untouched on rejection. +- Established connections keep their session; the accept-loop h2 rejection remains as defense in depth. +- The error is a fixed configuration category naming the contradiction; it carries no key or certificate bytes. +- The neutral `eggnet-tls` surface, TLS defaults, and capability tiers are unchanged. + +## 6. Failure and recovery review + +- A contradictory server-owned reload now fails at the call site and leaves the previous identity serving. +- A contradictory snapshot installed through the raw `TlsReloadHandle` is still dropped by `accept_tls` after the handshake; no request is parsed and the connection permit is released. +- The guard reads only captured state and the incoming snapshot; it adds no lock or shared mutable state. + +## 7. Migration and compatibility review + +- `replace_tls_config` can now return a configuration error for an input the 321 behavior accepted. The handle is experimental; this is a correctness fix with no signature change. +- No public item is added or removed. The neutral `TlsReloadHandle` API is unchanged. +- Operators replacing through `ServerHandle` get the guarantee; the raw-handle bypass is documented rather than removed. + +## 8. Security review + +- Closes the gap where a reload could make every h2-capable client complete a handshake (including client-certificate verification under mTLS) and then be dropped. +- The swap is checked before mutation, so a rejected snapshot cannot degrade the live listener. +- The remaining bypass requires the embedding application to ignore the documented accessor guidance; it stays fail-closed at the accept loop and cannot cause request smuggling or protocol confusion. + +## 9. Documentation and operations + +- `docs/tls.md` states the build/start and swap-time behavior and the raw-handle bypass. +- `architecture/eggnet-tls.md` includes the swap in the compatibility-runtime validation. +- `CHANGELOG.md` Unreleased ALPN bullet covers the swap. +- The 321 closure and implementation records carry a correction note pointing here. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | `ServerHandle::tls_reload_handle` still returns the neutral handle, whose `replace` bypasses the capability check | An embedding application that ignores the doc can install a contradictory snapshot | Accepted and documented; making the neutral handle runtime-aware is deferred to keep `eggnet-tls` protocol-neutral. | + +## 11. Roadmap disposition + +Milestone 322 is closed. The TLS identity roadmap's completion definition now includes the reload swap. No hard dependency blocks the next TLS identity or H2/H3 milestone. + +## 12. Registry updates + +- `plans/registry.md`: milestone 322 marked closed with this record; next milestone number 323. +- `plans/subsystems/tls-identity-roadmap.md`: milestone 322 marked closed. +- `plans/implementation/tls-identity/322-reload-alpn-coherence.md`: status implemented. diff --git a/plans/implementation/tls-identity/321-tls-substrate-corrective.md b/plans/implementation/tls-identity/321-tls-substrate-corrective.md new file mode 100644 index 00000000..5b13411a --- /dev/null +++ b/plans/implementation/tls-identity/321-tls-substrate-corrective.md @@ -0,0 +1,214 @@ +# TLS Identity Milestone 321 - TLS substrate corrective + +Status: implemented + +Repository baseline: `26649bd` (branch `plan-320-public-bind-acknowledgment-hardening`, clean tree) + +Source roadmap: + +- `plans/subsystems/tls-identity-roadmap.md#7` (Milestone 321) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` (neutral `eggnet-tls` ownership) +- `plans/000-long-term-specification.md#3` (invariants) +- `plans/000-long-term-specification.md#4` (TLS identity remains experimental) +- `plans/001-terminology-and-domain-model.md#subsystem-names-stable` (subsystem vocabulary) + +Applicable ADRs: + +- none + +Primary class: invariant + +## 1. Objective + +Remove five defects found by a capability review of the TLS surface at the baseline, without changing TLS tiers, safe defaults, or the single-identity CLI/Python surface. + +## 2. Why this milestone is ready + +There is no hard dependency: all five defects are in already-landed infrastructure. Each defect has a concrete code path and a deterministic test that fails before the fix (provider selection, ALPN/runtime disagreement, CLI limit projection, identity cap, QUIC VarInt bounds). + +## 3. Current implementation evidence + +- `crates/eggnet-tls/src/lib.rs` builds rustls configurations with `ServerConfig::builder()` (lines 274 and 730) and `WebPkiClientVerifier::builder()` (line 765). `validate_key_pair` already uses the ring provider explicitly (line 326). +- `crates/eggserve-h3/src/quic.rs` uses `builder_with_protocol_versions` (line 28) and maps VarInt/IdleTimeout range failures to `TlsError::InvalidKey` (lines 41-53). +- `crates/eggserve-core/src/server/config/runtime.rs` states that TLS has no extra scalar invariants (line 397); `crates/eggserve-core/src/server/accept.rs` drops an h2-negotiated connection when `http2.enabled` is false (lines 846-861). +- `crates/eggserve-bin/src/args.rs` maps `--header-timeout` only to `header_read_timeout` (lines 838-840). +- `crates/eggnet-tls/src/lib.rs` counts the optional default identity in the `add_identity` cap (line 575) but `default_identity` has no cap check (line 597). +- `crates/eggserve-h3/src/config.rs` validates QUIC windows only for non-zero (lines 71-115). +- Documentation conflicts: `docs/tls.md#137` claims ALPN derives from the runtime flag; `docs/tls.md#188` and `docs/security-policy.md#159` claim `--header-timeout` bounds the TLS handshake while `docs/deployment.md#116` says there is no CLI flag. + +## 4. Invariants that must not regress + +- Identity/trust/CRL parsing remains bounded and fails before readiness. +- No application 0-RTT; TLS 1.3-only QUIC; default rustls ticket policy. +- The CLI and Python remain single-identity; Python remains HTTP/1.1-only. +- No key/certificate bytes in errors, Debug, events, or logs. +- Accepted metadata remains bounded (SNI 253, chain 8 x 64 KiB). +- H1 is unaffected; H2/H3 remain experimental. + +## 5. Scope + +### In scope + +- Explicit ring-provider construction in `eggnet-tls` and `eggserve-h3`; removal of the Python process-global workaround. +- Runtime validation that the effective TLS ALPN set agrees with HTTP/2 availability. +- `--header-timeout` also setting `tls_handshake_timeout` (and matching docs). +- Order-independent named-SNI identity cap with the optional default separate. +- H3 VarInt/IdleTimeout upper-bound validation and a typed transport error. +- Focused tests and documentation updates. + +### Explicitly out of scope + +- New CLI flags (for example a dedicated `--tls-handshake-timeout`). +- Tier promotion, ACME/OCSP/watchers, mTLS on the CLI/Python, H3 SNI metadata. +- Any change to TLS defaults, cipher policy, or the supported version range. + +## 6. Required production changes + +### Crates and ownership + +`eggnet-tls` owns provider selection; `eggserve-h3` uses an explicit ring provider for its TLS 1.3 QUIC config; `eggserve-core` owns the ALPN/runtime coherence check; `eggserve-bin` owns the CLI projection. + +### Config and policy + +Add a private `crypto_provider()` helper in `eggnet-tls` returning `Arc` and use it in both server builders and the WebPKI verifier builder. Add `TlsError::{InvalidCryptoProvider, InvalidTransportConfig}` for non-key failures. + +### Protocol and compatibility + +In `RuntimeConfig::validate`, reject a TLS configuration (static or current reload snapshot) whose ALPN contains `h2` when the build has no `http2` feature or when `http2.enabled` is false. + +### Runtime and concurrency + +Validation is repeated on the connection path (existing `config.validate()` call) so a reload snapshot is checked against the live runtime flag; existing connections are untouched. + +### Frontend or operator surface (CLI / Python) + +`Args::limits()` sets both `header_read_timeout` and `tls_handshake_timeout` from `--header-timeout`. Remove the Python `install_default()` side effect because every construction path is now provider-explicit. + +### Security and confinement + +No new exposure; the changes remove a panic, a protocol mismatch, a resource-bound inconsistency, and a misleading error. + +### Documentation and static guards + +Update `docs/tls.md`, `docs/security-policy.md`, `docs/deployment.md`, `docs/cli.md`, `docs/timeout-reference.md`, `architecture/eggnet-tls.md`, and `CHANGELOG.md`. + +## 7. Ordered work packages + +### Work package A - Provider determinism + +Intent: configuration construction never panics because of an unrelated provider in the graph. + +Required changes: `eggnet-tls` helper plus three builder call sites; H3 QUIC builder; remove the Python global install. + +Acceptance evidence: a unit test builds an identity and a client-auth verifier without installing a process default, in a test binary where both providers are enabled. + +### Work package B - ALPN/runtime coherence + +Intent: contradictory configuration is rejected before serving. + +Required changes: `RuntimeConfig::validate` checks the effective ALPN set for h2 against `http2.enabled` and the compiled feature. + +Acceptance evidence: builder tests for static and reload configurations; the error names the contradiction. + +### Work package C - CLI timeout truth + +Intent: the documented security bound is real. + +Required changes: `Args::limits()` sets both timeouts; usage text and docs updated. + +Acceptance evidence: an args test asserts both limits equal the flag value. + +### Work package D - Identity cap + +Intent: the documented named-identity ceiling is order-independent. + +Required changes: `add_identity` no longer counts the optional default; constant docs state the default is separate. + +Acceptance evidence: 64 named identities build with a default configured first; a 65th add fails with `TooManyIdentities`. + +### Work package E - H3 transport bounds and typing + +Intent: out-of-range QUIC settings fail with a field-named transport error. + +Required changes: `Http3Config::validate` bounds windows and idle timeout to the QUIC VarInt range; `quic.rs` uses `InvalidTransportConfig`. + +Acceptance evidence: unit tests for each field; the error message does not say private key. + +## 8. Failure, cancellation, restart, and contention semantics + +Static validation fails `Server::build`/`start`. A reload that introduces an h2 advertisement on an H2-disabled runtime is rejected on the next connection validation (fail closed); established connections are unaffected. **Correction (milestone 322):** the TLS accept path rejects the h2 negotiation before the per-connection validator runs, so 322 enforces the check at `ServerHandle`'s reload swap. Provider selection is deterministic and stateless, so concurrent construction and reload are unchanged. The identity-cap change does not alter handshake behavior. + +## 9. Compatibility and migration + +- `TlsError` gains two variants. The crate is 0.x and this is a diagnostic correction; no version bump is part of this milestone. +- `--header-timeout` now also bounds TLS handshakes, matching the already-published security policy. Operators who relied on the 10-second handshake budget while lowering the header timeout will get the configured (smaller) value. +- Python's process-global provider installation is removed; the observable TLS behavior is unchanged because the substrate uses ring explicitly. +- No configuration field is added or removed. + +## 10. Required tests + +### Focused unit tests + +- `eggnet-tls`: provider-explicit build with client auth and no installed default; identity-cap order independence. +- `eggserve-bin`: `--header-timeout` sets both limits. +- `eggserve-h3`: window and idle-timeout upper bounds (and zero/unbounded messages). + +### Integration tests + +- `eggserve-core/tests/tls_identity.rs`: h2 ALPN with `http2.enabled=false` rejected for both `tls_config` and a reload handle. + +### Contention and cancellation tests + +Not applicable; no new concurrency primitive. Reload all-or-nothing semantics stay covered by the existing tests. + +### Security and negative tests + +Provider test runs with both rustls providers enabled in the test graph; ALPN negative tests fail closed; H3 bounds reject `u64::MAX`. + +## 11. Required verification commands + +```bash +cargo fmt --all -- --check +cargo test -p eggnet-tls +cargo test -p eggserve-h3 +cargo test -p eggserve-bin --features tls +cargo test -p eggserve-core --features tls --test tls_identity +cargo test -p eggserve-core --features http2,tls --test tls_identity +cargo clippy -p eggnet-tls -p eggserve-h3 -p eggserve-core -p eggserve-bin --all-targets --features http2,tls -- -D warnings +python3 scripts/check-crate-topology.py +./scripts/verify.sh fast +``` + +Python crate: `cargo check --manifest-path crates/eggserve-python/Cargo.toml --locked` where the environment allows it. + +## 12. Documentation updates + +- `docs/tls.md`: ALPN/runtime validation; handshake timeout surface; provider determinism. +- `docs/security-policy.md`: keep the header-timeout statement now that it is true. +- `docs/deployment.md`: direct-TLS timeout note. +- `docs/cli.md`, `docs/timeout-reference.md`: flag semantics. +- `architecture/eggnet-tls.md`: explicit provider and runtime ALPN validation. +- `CHANGELOG.md`: Unreleased entry. + +## 13. Acceptance criteria + +1. `load_tls_config`, `TlsServerConfigBuilder::build`, and `load_quic_server_config` succeed with both rustls providers compiled and no process default installed. +2. A configuration advertising `h2` while HTTP/2 is disabled or unavailable is rejected by `RuntimeConfig::validate`/`Server::build`, for both `tls_config` and a reload handle, with a message naming the contradiction. +3. `--header-timeout N` produces `header_read_timeout == tls_handshake_timeout == N`, and the docs name that surface. +4. With a default identity configured first, 64 named identities are accepted and a 65th is rejected; the reverse order behaves identically. +5. Out-of-range QUIC windows/idle timeout are rejected by `Http3Config::validate` with the field named, and no transport-bound failure is reported as `invalid private key`. + +## 14. Stop conditions + +Stop and report if: a fix requires changing TLS defaults or capability tiers; the provider change requires a new dependency; the Python crate cannot be checked in this environment; topology ownership would move; or a test cannot be made deterministic without weakening an invariant. + +## 15. Closure evidence required + +Exact commands and outcomes for the focused and broad gates, the before/after regression evidence for each finding, docs diff, and a statement of anything not run (for example the Python crate check). + +## 16. Handoff notes + +The checkout has no `target/` directory, so the first build is cold. `eggserve-python` is excluded from the workspace and has its own lockfile. Tests must not rely on a previously installed process default: the provider regression test deliberately does not install one. Preserve unrelated user changes; the worktree is clean at the baseline. diff --git a/plans/implementation/tls-identity/322-reload-alpn-coherence.md b/plans/implementation/tls-identity/322-reload-alpn-coherence.md new file mode 100644 index 00000000..d2adab6f --- /dev/null +++ b/plans/implementation/tls-identity/322-reload-alpn-coherence.md @@ -0,0 +1,154 @@ +# TLS Identity Milestone 322 - Reload ALPN coherence + +Status: implemented + +Repository baseline: `26649bd` plus the milestone 321 working-tree changes (branch `plan-320-public-bind-acknowledgment-hardening`; nothing committed by the agent) + +Source roadmap: + +- `plans/subsystems/tls-identity-roadmap.md#7` (Milestone 322) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` (neutral `eggnet-tls` ownership) +- `plans/000-long-term-specification.md#3` (invariants) +- `plans/000-long-term-specification.md#4` (TLS identity remains experimental) +- `plans/001-terminology-and-domain-model.md#subsystem-names-stable` (subsystem vocabulary) + +Applicable ADRs: + +- none + +Primary class: invariant + +## 1. Objective + +Make milestone 321's ALPN/runtime guarantee true at the server-owned reload swap: a running server must not accept a TLS snapshot that advertises `h2` when its runtime cannot serve HTTP/2. + +## 2. Why this milestone is ready + +321 already added the shared h2 advertisement test and the build/start validation. A security review of that change found the remaining path: `ServerHandle::replace_tls_config` wrote the snapshot into the reload handle without any runtime-coherence check, and the per-connection validator the 321 records relied on is not reached for an h2-negotiating client. The fix is local to `eggserve-core` and needs no new dependency. + +## 3. Current implementation evidence + +- `crates/eggserve-core/src/server/handle.rs`: `replace_tls_config` wrote the snapshot through `TlsReloadHandle::replace` with no capability check. +- `crates/eggserve-core/src/server/accept.rs`: `accept_tls` completes the handshake and returns `None` when the negotiated ALPN is `h2` and `h2_enabled` is false, before the HTTP driver runs. +- `crates/eggserve-core/src/server/connection/mod.rs`: the per-connection `config.validate()` lives inside `serve_http_connection_with_id_and_protocol`, so an h2-negotiating client never reaches it. +- `plans/closure/tls-identity/321-tls-substrate-corrective.md`: section 6 claimed the per-connection validator caught a contradictory reload; that holds only for clients that negotiate `http/1.1`. + +## 4. Invariants that must not regress + +- Reload stays all-or-nothing: a rejected swap leaves the live snapshot unchanged. +- Established sessions keep their session; new handshakes read the current snapshot atomically. +- The accept-loop ALPN rejection stays as defense in depth. +- The error names the contradiction and never includes key or certificate bytes. +- The neutral `eggnet-tls` surface is unchanged. + +## 5. Scope + +### In scope + +- Capture the runtime's HTTP/2 capability on `ServerHandle` at start. +- Reject an h2 advertisement at the server-owned reload swap. +- Share the ALPN predicate between build/start validation and the swap. +- Regression test, user docs, and planning records. + +### Explicitly out of scope + +- Making the neutral `TlsReloadHandle` runtime-aware. +- Removing or changing `ServerHandle::tls_reload_handle`. +- New CLI/Python flags or changed reload semantics. + +## 6. Required production changes + +- `RuntimeConfig::tls_advertises_h2` becomes `pub(crate)` and serves both validation points. +- `ServerHandle` stores `tls_h2_enabled` (TLS builds), set from `runtime_config.http2.enabled` at start and false when the `http2` feature is absent. +- `replace_tls_config` returns `ServerError::Config` for an h2-advertising snapshot while HTTP/2 is disabled; the swap does not happen. +- The `tls_reload_handle` doc states that replacing through the raw handle bypasses the server check. + +## 7. Ordered work packages + +### Work package A - Capture and guard + +Intent: the swap cannot install a protocol advertisement the accept loop cannot serve. + +Required changes: handle field and constructor parameter, swap-time check, module wiring in `Server::start`. + +Acceptance evidence: an h2 snapshot is rejected before the live snapshot changes. + +### Work package B - Regression test + +Intent: the pre-fix behavior fails deterministically. + +Required changes: `tls_identity::reload_rejects_h2_alpn_when_http2_disabled`. + +Acceptance evidence: the test fails because `replace_tls_server_config` returns `Ok` before the fix. + +### Work package C - Documentation and records + +Intent: the documented guarantee matches the enforced one. + +Required changes: `docs/tls.md`, `CHANGELOG.md`, `architecture/eggnet-tls.md`, roadmap, registry, and a correction note in the 321 closure. + +## 8. Failure, cancellation, restart, and contention semantics + +A rejected swap returns `Err` and mutates nothing; the next handshake still sees the previous identity. A contradictory snapshot installed through the raw handle is still rejected after the handshake by the accept loop (fail closed, no request parsed). Existing connections are untouched, and the reload lock is unaffected by a rejection. + +## 9. Compatibility and migration + +- `replace_tls_config` now returns a configuration error for an input it previously accepted. The handle type is experimental and this is a correctness fix. +- No method is added or removed; `ServerHandle` is not constructible outside the crate. +- The neutral `eggnet-tls` API and the `TlsReloadHandle` semantics are unchanged. + +## 10. Required tests + +### Integration tests + +- Start a server with `http2.enabled = false`, reject an h2 snapshot, prove the live HTTP/1.1 identity still serves, then accept a coherent reload. +- The existing `reload_changes_new_handshakes_not_established`, `alpn_parity_survives_reload`, `concurrent_reload_handshake_race_safe`, and `failed_reload_preserves_old` stay green. + +### Feature-shape tests + +`tls` without `http2` and `http2,tls` both compile and pass, because the conflict message is selected by feature. + +## 11. Required verification commands + +```bash +cargo fmt --all -- --check +cargo test -p eggserve-core --features http2,tls --test tls_identity +cargo test -p eggserve-core --features tls --test tls_identity +cargo test -p eggserve-core --features http2,tls +cargo clippy -p eggserve-core --features http2,tls --lib --tests -- -D warnings +cargo clippy -p eggserve-core --features tls --lib --tests -- -D warnings +cargo check -p eggserve-bin --features http2,tls +git diff --check +python3 scripts/check-crate-topology.py +``` + +## 12. Documentation updates + +- `docs/tls.md`: ALPN guarantee at build/start and at the reload swap; the raw-handle bypass. +- `CHANGELOG.md`: the Unreleased ALPN bullet names the swap. +- `architecture/eggnet-tls.md`: compatibility-runtime validation includes the swap. +- `plans/subsystems/tls-identity-roadmap.md` and `plans/registry.md`: milestone 322. +- `plans/closure/tls-identity/321-tls-substrate-corrective.md`: correction note for the per-connection claim. + +## 13. Acceptance criteria + +1. A server with HTTP/2 disabled rejects an h2 snapshot at `replace_tls_config` / `replace_tls_server_config`, and the error names `http2.enabled`. +2. The live snapshot is unchanged after a rejected swap and HTTP/1.1 still serves. +3. A coherent reload is still accepted. +4. An HTTP/2-enabled server still accepts an h2 reload (existing parity test). +5. The `tls` and `http2,tls` shapes both compile and pass. + +## 14. Stop conditions + +Stop and report if the guard needs a new dependency or public type, if it cannot leave the live snapshot unchanged, or if enforcing it would require changing the neutral `eggnet-tls` reload API. + +## 15. Closure evidence required + +Exact commands and outcomes, the regression test name, the protected behavior (live snapshot, coherent reload), and the disclosed raw-handle bypass. + +## 16. Handoff notes + +The raw `TlsReloadHandle` remains a documented bypass; making the neutral handle capability-aware is deferred because `eggnet-tls` must stay protocol-neutral. The broad `./scripts/verify.sh fast` wrapper still stops at the pre-existing macOS `eggserve-server` failure recorded in the 321 closure. diff --git a/plans/registry.md b/plans/registry.md index 87e353b2..a41b6aa0 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -9,7 +9,7 @@ Canonical direction remains in: - `plans/002-long-term-roadmap.md` - `plans/003-planning-process.md` -New milestone numbers continue from `321`. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. +New milestone numbers continue from `323`. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. ## Status vocabulary @@ -34,6 +34,7 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | Planning governance | active | `plans/subsystems/planning-governance-roadmap.md` | 314 publication-state staleness sweep | Milestones 1 and 302 closed. Reopened: six surfaces still describe the published 0.4.0 line as pending, including the agent-facing skill. Interface dependency: 304's closure record supplies the facts. | | Python facade | active | `plans/subsystems/python-facade-roadmap.md` | 311 directory-listing renderer consolidation | New roadmap. Milestone 311 is closed: the bridge's second listing renderer is gone and the 1 MiB response-byte ceiling now applies to the Python path. | | CLI, ops, and observability | active | `plans/subsystems/cli-ops-observability-roadmap.md` | 320 public-bind acknowledgment hardening (closed) | 312–320 closed. 320 hardened the CLI/Python public-bind gate so any non-loopback address requires `--public`/`public=True`; docs no longer claim `--public` alone expands to `0.0.0.0`. | +| TLS identity | active | `plans/subsystems/tls-identity-roadmap.md` | 322 reload ALPN coherence (closed) | 321 corrected five seam defects at `26649bd` (provider panic, ALPN/runtime disagreement, CLI timeout mismatch, identity-cap order dependence, H3 transport-bound diagnostics) without a tier or default change. Its follow-up security review found that a running server's reload swap still accepted an h2 advertisement on an HTTP/2-disabled runtime; 322 enforces the check at the swap with the previous identity live. Closures: `plans/closure/tls-identity/321-tls-substrate-corrective.md`, `plans/closure/tls-identity/322-reload-alpn-coherence.md`. | | Docs architecture (overview index + deep dives) | closed | `plans/subsystems/docs-architecture-roadmap.md` | 301 closed (overview + deep dives refreshed to 0.4.0 baseline) | Trace: `plans/closure/docs-architecture/293-architecture-overview-deep-dive-refresh.md`. Interface: closed 294–299 code state + Plan 300 publication as review input. | ## Dependency-ready implementation plans @@ -68,6 +69,8 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | CLI, ops, and observability | 318 | closed | `plans/implementation/cli-ops-observability/318-rustls-floor-and-testpypi-staging.md` | The manifest `rustls` floor is raised from `0.23.45` to `0.23.46` in the workspace table and in the excluded Python crate. The resolution does not move — all three lockfiles and the resolved feature sets are unchanged — but a consumer pinned to `=0.23.45` can no longer unify to the vulnerable release alongside these crates. The guard `docs/dependency-policy.md` already required but that never existed now does: gate rule `check_plan318_rustls_floor`. Closure: `plans/closure/cli-ops-observability/318-rustls-floor-and-testpypi-staging.md`. | | CLI, ops, and observability | 319 | closed | `plans/implementation/cli-ops-observability/319-static-0-5-1-patch-release-and-doc-sweep.md` | `eggserve-static` is bumped to `0.5.1` with the NT directory-buffer fixes the published `0.5.0` still carried; the dependent crates' caret requirements already accept it and are unchanged. `docs/release-contract.md` and five `architecture/` deep dives no longer name the superseded `0.4.0` line's versions. The six factually-wrong doc comments an audit found in Plan 313's 539-item remediation are corrected. Closure: `plans/closure/cli-ops-observability/319-static-0-5-1-patch-release-and-doc-sweep.md`. | | CLI, ops, and observability | 320 | closed | `plans/implementation/cli-ops-observability/320-public-bind-acknowledgment-hardening.md` | Done; closure: `plans/closure/cli-ops-observability/320-public-bind-acknowledgment-hardening.md`. Non-loopback binds require `--public`/`public=True`; docs match acknowledgment-only semantics. | +| TLS identity | 321 | closed | `plans/implementation/tls-identity/321-tls-substrate-corrective.md` | The five reviewed defects are corrected with regression tests; Python/MSRV/clippy lanes pass. Closure: `plans/closure/tls-identity/321-tls-substrate-corrective.md`. Two pre-existing macOS-only test failures in untouched crates are recorded there. | +| TLS identity | 322 | closed | `plans/implementation/tls-identity/322-reload-alpn-coherence.md` | `ServerHandle::replace_tls_config` now rejects an h2-advertising snapshot when the runtime cannot serve HTTP/2, before the swap, leaving the previous identity live; `tls_identity::reload_rejects_h2_alpn_when_http2_disabled` fails on the 321 behavior. The raw `TlsReloadHandle` accessor remains a documented bypass. Closure: `plans/closure/tls-identity/322-reload-alpn-coherence.md`. | ## Blocked work diff --git a/plans/subsystems/tls-identity-roadmap.md b/plans/subsystems/tls-identity-roadmap.md new file mode 100644 index 00000000..f5103bf8 --- /dev/null +++ b/plans/subsystems/tls-identity-roadmap.md @@ -0,0 +1,165 @@ +# TLS Identity Roadmap + +Status: active + +Long-term references: + +- `plans/000-long-term-specification.md#2` (architectural ownership: `eggnet-tls` is the neutral rustls identity substrate) +- `plans/000-long-term-specification.md#3` (invariants) +- `plans/000-long-term-specification.md#4` (TLS identity remains experimental) +- `plans/001-terminology-and-domain-model.md#subsystem-names-stable` (subsystem vocabulary: `tls-identity`) +- `plans/002-long-term-roadmap.md` (dependency notes) + +Related ADRs: + +- none (the substrate boundary is defined by `plans/000` section 2 and `architecture/eggnet-tls.md`) + +## 1. Purpose and ownership boundary + +Owns the server-side TLS identity substrate: bounded PEM loading, certificate/key pairing validation, SNI exact/wildcard/default resolution, WebPKI client authentication with explicit trust roots and CRLs, ALPN validation, immutable `TlsServerConfig` snapshots, atomic reload handles, and the QUIC identity assembly `eggserve-h3` derives from that substrate. + +Owns: `crates/eggnet-tls/` (identity, trust, client auth, reload, ALPN) and the TLS-specific assembly in `crates/eggserve-h3/src/quic.rs`. + +Consumes: `eggserve-core` for the compatibility facade (`eggserve_core::tls` re-export), accept-loop integration, runtime configuration validation, and the CLI/Python frontends. Never owns HTTP framing, listener lifecycle, proxy routing, or application TLS policy. + +## 2. Work classification + +### Invariants + +- Certificate/key pairing and all bounded inputs fail before readiness, never at the first hostile handshake. +- TLS configuration construction never depends on the process-default rustls `CryptoProvider`; the ring provider is explicit. +- A TLS configuration must not advertise an ALPN protocol the runtime cannot serve in its current configuration. +- Conservative defaults remain: no application 0-RTT, no stateful tickets, no implicit revocation without CRLs. +- Accepted ALPN and verified metadata remain bounded and sanitized; no key material is logged. + +### Capabilities + +- Single-identity TLS for the CLI and Python `HTTPSServer`/`ThreadingHTTPSServer`. +- Rust SNI multi-identity, optional/required WebPKI client authentication, and atomic reload for new handshakes. +- Experimental H2 ALPN on the compatibility server and experimental H3/QUIC identity assembly. + +### Infrastructure + +- Bounded PEM/trust/CRL parsing and identity bounds. +- `TlsServerConfigBuilder`, `TlsReloadHandle`, and the `eggserve_core::tls` facade. +- Runtime ALPN/runtime-flag coherence validation. + +### Polish + +- Typed, non-misleading error categories for QUIC transport bounds. +- Documentation that matches the executable CLI and runtime behavior. + +## 3. Non-goals + +- No ACME, certificate discovery/watching, OCSP stapling, KMS signing, or secret storage. +- No Python certificate-verification callback and no client certificates on the Python facade. +- No tier promotion for SNI/mTLS/reload or H2/H3; `server`/TLS-identity remain experimental. +- No second TLS implementation outside `eggnet-tls`/`eggserve-h3`. +- No CLI multi-identity or mTLS flags. + +## 4. Current state + +The substrate is implemented and tested: bounded identity/trust/CRL parsing, exact and single-level wildcard SNI with an optional default, `ClientAuthMode::{Disabled, Optional, Required}`, atomic reload, neutral ALPN construction, and a separate TLS 1.3-only `h3` QUIC config. The CLI remains single-identity; Python remains single-identity HTTP/1.1-only. + +A capability review at baseline `26649bd` found five defects at the seams: + +1. `eggnet-tls` and `eggserve-h3` construct rustls configurations through the process-default provider, which panics when the dependency graph enables both `ring` and `aws-lc-rs` and no default has been installed. +2. The compatibility server does not validate that a TLS configuration's ALPN advertisement agrees with `RuntimeConfig.http2.enabled`; an h2 advertisement on an H2-disabled runtime completes the handshake and then drops the connection. +3. `--header-timeout` is documented as the TLS handshake bound but only sets the header-read timeout. +4. The SNI identity cap counts the optional default identity and is enforced in one builder method only, making the documented ceiling order-dependent. +5. H3 QUIC window/idle-timeout bounds are not validated to the QUIC VarInt range and are reported through `TlsError::InvalidKey`, misdiagnosing transport configuration as certificate material. + +The follow-up security review of 321 found one more seam: a running server's reload swap accepted an h2 advertisement while HTTP/2 was disabled, and the accept loop then completed every h2 client's handshake before dropping it. Milestone 322 enforces the coherence check at the swap. + +## 5. Target architecture + +Every rustls server configuration is built with an explicit `Arc` (ring), matching the provider already used for key/cert pairing. The compatibility runtime validates the effective TLS ALPN set (static or reload snapshot) against its HTTP/2 capability before serving, and the server handle rejects a contradictory snapshot at the reload swap. The CLI's documented header timeout governs both header reads and TLS handshakes. The identity builder enforces one order-independent ceiling for named SNI identities, with the optional default separate. H3 validates transport bounds in `Http3Config::validate` and reports transport-specific failures through a dedicated typed error. + +## 6. Dependency graph + + Milestone 321 TLS substrate corrective (closed) + | + +--> Milestone 322 reload ALPN coherence (closed) + | + +--> future SNI/mTLS capability milestones (soft) + `--> H2/H3 transport milestones (soft; ALPN coherence shared) + +Milestone 321 has no hard dependency; milestone 322 takes 321's shared ALPN predicate as an interface dependency and is closed. + +## 7. Milestones + +### Milestone 321 - TLS substrate corrective + +Class: invariant + +Objective: remove the five seam defects above without changing TLS capability tiers, defaults, or the single-identity CLI/Python surface. + +Dependencies: none (hard); `eggserve-core` compatibility facade is the interface. + +Deliverable boundary: `eggnet-tls`, the core runtime validator, the CLI limit projection, the H3 QUIC assembler, focused tests, and the matching docs. + +User or operator value: no process abort on valid credentials in multi-provider builds; no silent h2 connection drops from contradictory configuration; the documented handshake timeout actually applies; documented identity limits are order-independent; H3 transport misconfiguration is diagnosed correctly. + +Exit conditions: all acceptance criteria in `plans/implementation/tls-identity/321-tls-substrate-corrective.md` pass and the closure record is written. + +Deferred work: H3 SNI metadata exposure; mTLS/SNI CLI flags; any tier promotion. + +### Milestone 322 - Reload ALPN coherence + +Class: invariant + +Objective: enforce 321's ALPN/runtime coherence at the server handle's reload swap, so a running server never accepts an h2 advertisement it cannot serve. + +Dependencies: 321 (interface: the shared ALPN predicate); the `eggserve-core` compatibility facade. + +Deliverable boundary: `ServerHandle` capability capture and swap guard, one regression test, docs, and the 321 correction note. + +User or operator value: a contradictory certificate rotation is rejected at the call site with the previous identity still live, instead of silently failing every h2 client after a completed handshake. + +Exit conditions: the acceptance criteria in `plans/implementation/tls-identity/322-reload-alpn-coherence.md` pass and this closure record is written. + +Deferred work: making the neutral `TlsReloadHandle` runtime-aware; the raw accessor remains a documented bypass. + +## 8. Cross-cutting requirements + +### Protocol and compatibility + +Static TLS configuration and reload snapshots are both validated against the runtime's HTTP/2 capability. A configuration that advertises `h2` while H2 is disabled or unavailable is rejected rather than accepted and dropped after the handshake. + +### Security and authorization + +Provider determinism removes a startup abort; ALPN validation prevents protocol confusion; the identity-cap correction keeps the documented certificate/key resource ceiling; no key material or rustls internals are exposed. + +### Concurrency, cancellation, and recovery + +Reload remains all-or-nothing for new handshakes; per-connection validation reads the current snapshot atomically. Existing connections keep their session. + +### Observability and audit + +TLS failures remain fixed sanitized categories. The new validation errors name the configuration field, never certificate bytes. + +### Documentation and operations + +`docs/tls.md`, `docs/security-policy.md`, `docs/deployment.md`, `docs/cli.md`, `docs/timeout-reference.md`, and `architecture/eggnet-tls.md` must match the executable behavior. + +## 9. Verification strategy + +Focused crate tests for each fix, the existing TLS identity/abuse/neutral suites, `cargo fmt --check`, clippy `-D warnings` for the changed crates, and `scripts/check-crate-topology.py`. `./scripts/verify.sh fast` is the broad routine gate; the TLS-only bin tests and H3 suites run where CI would run them. + +## 10. Risks and decision points + +- Adding a `TlsError` variant is a public-enum change in a 0.x crate; it is intentional so transport configuration is not reported as a private-key failure. No ADR is required for this 0.x diagnostic correction. +- Coupling `--header-timeout` to `tls_handshake_timeout` preserves the documented security policy; a future dedicated flag would supersede it through a new milestone. +- The raw `TlsReloadHandle` accessor remains a documented bypass of the swap check; enforcing it there would couple the neutral substrate to EggServe's HTTP/2 policy. +- Downstream graphs that enable `aws-lc-rs` in production remain supported because the substrate no longer consults the process default. + +## 11. Completion definition + +The subsystem is complete when configuration construction is provider-deterministic, ALPN/runtime coherence is enforced at validation and at the server reload swap, the documented CLI bound is real, identity limits are order-independent, H3 transport bounds are validated and typed, and the closure record contains the exact commands and outcomes. + +## 12. Milestone status + +| Milestone | Status | Implementation plan | Closure record | Blockers | +|---|---|---|---|---| +| 321 | closed | `plans/implementation/tls-identity/321-tls-substrate-corrective.md` | `plans/closure/tls-identity/321-tls-substrate-corrective.md` | none | +| 322 | closed | `plans/implementation/tls-identity/322-reload-alpn-coherence.md` | `plans/closure/tls-identity/322-reload-alpn-coherence.md` | none | From 269d7664b26c72f5d6a6f73b3dff2354b373cacd Mon Sep 17 00:00:00 2001 From: CI Test Date: Thu, 26 Nov 2026 03:24:39 +0000 Subject: [PATCH 3/3] Plan 327 follow-up: name the H3 send-buffer field in validation errors Http3Config::validate checked send_window and max_send_buf_size in one arm and always reported http3.send_window, so a zero send buffer produced a false field attribution for a field that was valid. Split the check into per-field arms, matching the http2.max_send_buf_size diagnostic, and cover both branches with zero_send_buf_size_names_its_own_field. The 327 closure record gains a post-closure note recording the correction and the remaining open low finding: max_send_buf_size is bounded only below, and send_window has no upper bound although quinn documents it as the per-connection retained-write memory cap. Verified before commit: cargo fmt --all -- --check, cargo test -p eggserve-h3, cargo clippy -p eggserve-h3 --all-targets -D warnings, and cargo test -p eggserve-core --features http3,tls --lib. --- crates/eggserve-h3/src/config.rs | 25 ++++++++++++++++++- .../327-tls-substrate-corrective.md | 12 +++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/eggserve-h3/src/config.rs b/crates/eggserve-h3/src/config.rs index a8daaa91..0c261e9b 100644 --- a/crates/eggserve-h3/src/config.rs +++ b/crates/eggserve-h3/src/config.rs @@ -105,9 +105,12 @@ impl Http3Config { "must be at least stream_receive_window", )); } - if self.send_window == 0 || self.max_send_buf_size == 0 { + if self.send_window == 0 { return Err(invalid("send_window", "must be greater than zero")); } + if self.max_send_buf_size == 0 { + return Err(invalid("max_send_buf_size", "must be greater than zero")); + } if self.max_idle_timeout.is_zero() || self.max_idle_timeout.as_millis() > u128::from(QUIC_VARINT_MAX) { @@ -161,6 +164,26 @@ mod tests { assert!(at_limit.validate().is_ok()); } + /// A zero send buffer must be reported against `max_send_buf_size`. + /// The earlier combined check blamed `send_window` for either field. + #[test] + fn zero_send_buf_size_names_its_own_field() { + let zero_buffer = Http3Config { + max_send_buf_size: 0, + ..Default::default() + }; + let error = zero_buffer.validate().unwrap_err().to_string(); + assert!(error.contains("http3.max_send_buf_size"), "{error}"); + assert!(!error.contains("send_window"), "{error}"); + + let zero_window = Http3Config { + send_window: 0, + ..Default::default() + }; + let error = zero_window.validate().unwrap_err().to_string(); + assert!(error.contains("http3.send_window"), "{error}"); + } + #[test] fn quic_idle_timeout_bound_is_validated() { let too_large = Http3Config { diff --git a/plans/closure/tls-identity/327-tls-substrate-corrective.md b/plans/closure/tls-identity/327-tls-substrate-corrective.md index 0712f2e5..b66c1b24 100644 --- a/plans/closure/tls-identity/327-tls-substrate-corrective.md +++ b/plans/closure/tls-identity/327-tls-substrate-corrective.md @@ -139,3 +139,15 @@ Milestone 327 is closed; no hard dependency blocks the next TLS identity or H2/H - `plans/registry.md`: TLS identity milestone 327 marked closed with this record; next milestone number 329. - `plans/subsystems/tls-identity-roadmap.md`: milestone 327 marked closed. - `plans/implementation/tls-identity/327-tls-substrate-corrective.md`: status implemented. + +## 13. Post-closure correction (review follow-up) + +- `crates/eggserve-h3/src/config.rs`: the send-buffer check combined `send_window` + and `max_send_buf_size` and always named `http3.send_window`, so a zero + `max_send_buf_size` produced a false field attribution. Split into two arms + (matching `http2.rs`), with `zero_send_buf_size_names_its_own_field` covering + both branches. +- Open low finding: `max_send_buf_size` is bounded only below (`> 0`), and + `send_window` has no upper bound even though quinn documents it as the + per-connection retained-write memory cap. The H3 knobs are Rust-API only (no + CLI or Python surface), and the defaults stay at 4 MiB / 256 KiB.