hyprstream_core/mac/public_exemptions.rs
1//! Reviewed registry of HTTP routes intentionally exempt from native MAC
2//! mediation — the "public / declassifier exemption registry" (issue #1273,
3//! epic #1267, audit item `NEW-PUBLIC-EXEMPTIONS`).
4//!
5//! # Why this exists
6//! Native MAC ([`crate::mac`]) is the mandatory floor: every object path must
7//! be mediated by a verified subject `SecurityContext` and a trusted object
8//! label before use. Activation's "all non-exempt paths mediated" claim is only
9//! enforceable if the set of intentionally-unmediated routes is *explicit and
10//! reviewed*, not implicit. Without a registry, a newly added public route can
11//! silently become a bypass — exactly the drift this module prevents.
12//!
13//! # Contract (do not circumvent)
14//! 1. **A route defaults to mediated.** Any HTTP route not listed in
15//! [`PUBLIC_EXEMPTIONS`] must sit behind the protected (auth-mediated)
16//! router. Once the MAC PEP is installed there is no permissive mode
17//! ([`crate::mac`] is fail-closed per #547); "public" is an opt-in,
18//! reviewed exemption, never a default.
19//! 2. **The public routers are built from this registry.** [`crate::server`]
20//! constructs its public route set by
21//! iterating [`PUBLIC_EXEMPTIONS`] for its face, so adding an unmediated
22//! route requires adding a reviewed [`PublicExemption`] entry plus a handler
23//! arm — two review surfaces, no silent addition.
24//! 3. **The drift test pins the live set to the registry.**
25//! `public_exemptions_match_live_routes` asserts registry self-consistency,
26//! handler-enum parity, per-face wiring, and that the public/protected split
27//! is live (registry paths answer without auth; a protected path does not).
28//!
29//! # Scope and dependencies
30//! This registry covers genuinely no-auth public routes: health metadata,
31//! `.well-known` discovery, and pre-credential browser provisioning.
32//! OAuth2.1 protocol endpoints (token,
33//! authorize, jwks, device, SCIM …) are the *credential-issuance control
34//! plane* that MAC sits beneath, not tenant-object access; they remain out of
35//! scope here and are tracked separately. Real MAC enforcement remains dormant
36//! (uninstalled, so dispatch permits as a pre-activation pass-through) pending
37//! production clearance provenance (#698). Once installed, the PEP is
38//! fail-closed. This registry is the activation-gate structure that ships now
39//! so the exempt set is locked.
40//!
41//! [#547]: https://github.com/hyprstream/hyprstream/issues/547
42//! [#698]: https://github.com/hyprstream/hyprstream/issues/698
43//! [#1267]: https://github.com/hyprstream/hyprstream/issues/1267
44//! [#1273]: https://github.com/hyprstream/hyprstream/issues/1273
45
46/// HTTP method of an exempt route. Only the methods used by public routes are
47/// represented; anything else must go through the protected router.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum RouteMethod {
50 Get,
51 Post,
52}
53
54/// Why a route is intentionally unmediated. Used by activation review to
55/// confirm each exemption is a narrow, justified carve-out.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57pub enum ExemptionCategory {
58 /// Liveness / health metadata. No tenant data, no object access.
59 Health,
60 /// Published discovery or capability metadata (`.well-known`, wire-plane
61 /// table). Public by design so clients can bootstrap before authenticating.
62 PublicMetadata,
63 /// Pre-credential bootstrap (browser provisioning before any identity
64 /// exists). Rate-limited; carries no tenant object.
65 Bootstrap,
66 /// Stateless cryptographic verification returning only pass/fail plus the
67 /// content-verified identifier. Never echoes request bytes past the check.
68 CryptographicVerification,
69}
70
71/// Which HTTP face serves the exempt route. Each face builds its public router
72/// from its own slice of [`PUBLIC_EXEMPTIONS`]; the drift test cross-checks
73/// every face against the registry.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub enum HttpFace {
76 /// The main Axum app ([`crate::server::create_app`]).
77 MainApp,
78}
79
80/// Tag identifying which handler serves an exempt route. The public-router
81/// builders match exhaustively on this, so wiring a new route requires both a
82/// [`PublicExemption`] entry and a handler arm — the double review touch that
83/// keeps the exempt set from silently growing.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85pub enum PublicRouteHandler {
86 /// `GET /` and `GET /health` — health metadata.
87 HealthCheck,
88 /// `GET /.well-known/oauth-protected-resource` — RFC 9728 metadata.
89 OauthProtectedResourceMetadata,
90 /// `GET /.well-known/export9p` — 9P export discovery metadata.
91 Export9pMetadata,
92 /// `GET /.well-known/planes` — wire-plane discovery table.
93 WirePlanesMetadata,
94 /// `GET /9p` — 9P-over-WebSocket export (mount ticket rides the URL query).
95 NinepWebSocket,
96 /// `GET /.well-known/hyprstream/browser-provisioning/:service` — bootstrap.
97 BrowserProvisioning,
98}
99
100/// One reviewed public/declassifier exemption. Every field is `&'static` so the
101/// registry is a compile-time constant and the drift test needs no allocation.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct PublicExemption {
104 /// Stable, unique kebab-case identifier (the key the router builder looks
105 /// up). Changing an id is a reviewed change; reuse across routes is a drift
106 /// error caught by [`validate`].
107 pub id: &'static str,
108 /// Face that owns the route. See [`HttpFace`].
109 pub face: HttpFace,
110 /// HTTP method.
111 pub method: RouteMethod,
112 /// Axum path pattern exactly as wired (e.g. `"/health"`,
113 /// `"/.well-known/hyprstream/browser-provisioning/:service"`).
114 pub path: &'static str,
115 /// Reviewed justification category. See [`ExemptionCategory`].
116 pub category: ExemptionCategory,
117 /// Handler that serves this route. See [`PublicRouteHandler`].
118 pub handler: PublicRouteHandler,
119 /// One-line human justification for why native MAC is intentionally absent
120 /// here. Must be non-empty; [`validate`] rejects empties.
121 pub justification: &'static str,
122}
123
124/// The authoritative, reviewed registry. This is the single source of truth for
125/// which HTTP routes bypass native MAC mediation.
126///
127/// **To add a public route:** append a [`PublicExemption`] here with a reviewed
128/// justification, add the matching handler arm to the owning face's builder,
129/// then update the drift test's expected snapshot. All three edits in one PR.
130pub static PUBLIC_EXEMPTIONS: &[PublicExemption] = &[
131 PublicExemption {
132 id: "root-health",
133 face: HttpFace::MainApp,
134 method: RouteMethod::Get,
135 path: "/",
136 category: ExemptionCategory::Health,
137 handler: PublicRouteHandler::HealthCheck,
138 justification: "Liveness probe; returns service name + version only, no tenant data.",
139 },
140 PublicExemption {
141 id: "health",
142 face: HttpFace::MainApp,
143 method: RouteMethod::Get,
144 path: "/health",
145 category: ExemptionCategory::Health,
146 handler: PublicRouteHandler::HealthCheck,
147 justification: "Liveness probe; returns service name + version only, no tenant data.",
148 },
149 PublicExemption {
150 id: "oauth-protected-resource",
151 face: HttpFace::MainApp,
152 method: RouteMethod::Get,
153 path: "/.well-known/oauth-protected-resource",
154 category: ExemptionCategory::PublicMetadata,
155 handler: PublicRouteHandler::OauthProtectedResourceMetadata,
156 justification: "RFC 9728 metadata advertising the authorization server; needed before a client can authenticate.",
157 },
158 PublicExemption {
159 id: "export9p",
160 face: HttpFace::MainApp,
161 method: RouteMethod::Get,
162 path: "/.well-known/export9p",
163 category: ExemptionCategory::PublicMetadata,
164 handler: PublicRouteHandler::Export9pMetadata,
165 justification: "9P export discovery metadata; clients resolve the mount selector from this before presenting a ticket.",
166 },
167 PublicExemption {
168 id: "wire-planes",
169 face: HttpFace::MainApp,
170 method: RouteMethod::Get,
171 path: "/.well-known/planes",
172 category: ExemptionCategory::PublicMetadata,
173 handler: PublicRouteHandler::WirePlanesMetadata,
174 justification: "Wire-plane discovery table (#821); enumerates non-file planes, no tenant objects.",
175 },
176 PublicExemption {
177 id: "ninep-ws",
178 face: HttpFace::MainApp,
179 method: RouteMethod::Get,
180 path: "/9p",
181 category: ExemptionCategory::PublicMetadata,
182 handler: PublicRouteHandler::NinepWebSocket,
183 justification: "9P-over-WebSocket upgrade; the mount ticket rides the URL query (browser WS cannot set headers) and is validated inside the handler.",
184 },
185 PublicExemption {
186 id: "browser-provisioning",
187 face: HttpFace::MainApp,
188 method: RouteMethod::Get,
189 path: "/.well-known/hyprstream/browser-provisioning/:service",
190 category: ExemptionCategory::Bootstrap,
191 handler: PublicRouteHandler::BrowserProvisioning,
192 justification: "Pre-credential browser bootstrap before any identity exists; independently rate-limited, carries no tenant object.",
193 },
194];
195
196impl PublicExemption {
197 /// (method, path) tuple, the key used for uniqueness checks.
198 fn route_key(&self) -> (HttpFace, RouteMethod, &'static str) {
199 (self.face, self.method, self.path)
200 }
201}
202
203/// Yields the registry entries owned by `face`, in declaration order.
204pub fn for_face(face: HttpFace) -> impl Iterator<Item = &'static PublicExemption> {
205 PUBLIC_EXEMPTIONS.iter().filter(move |e| e.face == face)
206}
207
208/// Looks up an exemption by id. Router builders use this to reference the
209/// reviewed path/method rather than a string literal, so a typo or unregistered
210/// route is caught at startup instead of silently bypassing MAC.
211///
212/// Panics if `id` is not in the registry — a public route must be registered.
213pub fn require(face: HttpFace, id: &str) -> &'static PublicExemption {
214 PUBLIC_EXEMPTIONS
215 .iter()
216 .find(|e| e.face == face && e.id == id)
217 .unwrap_or_else(|| panic!("public exemption {id:?} not registered for face {face:?}"))
218}
219
220/// Error raised by [`validate`] when the registry has drifted from its contract.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub enum RegistryError {
223 DuplicateId(&'static str),
224 DuplicateRoute(HttpFace, RouteMethod, &'static str),
225 EmptyJustification(&'static str),
226 UnknownFaceHandler(&'static str),
227}
228
229impl std::fmt::Display for RegistryError {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231 match self {
232 Self::DuplicateId(id) => write!(f, "duplicate exemption id {id:?}"),
233 Self::DuplicateRoute(face, method, path) => {
234 write!(f, "duplicate route {method:?} {path:?} on face {face:?}")
235 }
236 Self::EmptyJustification(id) => {
237 write!(f, "exemption {id:?} has an empty justification")
238 }
239 Self::UnknownFaceHandler(id) => {
240 write!(
241 f,
242 "exemption {id:?} references a handler unused by its declared face"
243 )
244 }
245 }
246 }
247}
248
249impl std::error::Error for RegistryError {}
250
251/// Validates the registry against its contract:
252/// - unique ids and unique (face, method, path) routes,
253/// - non-empty justifications,
254/// - each handler appears only under the face that owns it.
255///
256/// Returns the first [`RegistryError`] found, or `Ok(())`. The drift test calls
257/// this and also checks the builder wiring is consistent with the result.
258pub fn validate() -> Result<(), RegistryError> {
259 let mut seen_ids = std::collections::HashSet::new();
260 let mut seen_routes = std::collections::HashSet::new();
261 for e in PUBLIC_EXEMPTIONS {
262 if !seen_ids.insert(e.id) {
263 return Err(RegistryError::DuplicateId(e.id));
264 }
265 if !seen_routes.insert(e.route_key()) {
266 return Err(RegistryError::DuplicateRoute(e.face, e.method, e.path));
267 }
268 if e.justification.trim().is_empty() {
269 return Err(RegistryError::EmptyJustification(e.id));
270 }
271 if !handler_belongs_to_face(e.handler, e.face) {
272 return Err(RegistryError::UnknownFaceHandler(e.id));
273 }
274 }
275 Ok(())
276}
277
278/// `true` if `handler` is wired by the builder that owns `face`. Keeps a
279/// face's handler from leaking into another face's builder.
280pub(crate) const fn handler_belongs_to_face(handler: PublicRouteHandler, face: HttpFace) -> bool {
281 match face {
282 HttpFace::MainApp => matches!(
283 handler,
284 PublicRouteHandler::HealthCheck
285 | PublicRouteHandler::OauthProtectedResourceMetadata
286 | PublicRouteHandler::Export9pMetadata
287 | PublicRouteHandler::WirePlanesMetadata
288 | PublicRouteHandler::NinepWebSocket
289 | PublicRouteHandler::BrowserProvisioning
290 ),
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 #![allow(clippy::unwrap_used, clippy::expect_used)]
297
298 use super::*;
299
300 /// The registry must satisfy its own contract.
301 #[test]
302 fn registry_is_self_consistent() {
303 validate().expect("PUBLIC_EXEMPTIONS must be self-consistent");
304 }
305
306 /// Every [`PublicRouteHandler`] variant is referenced by at least one
307 /// registry entry, so adding a handler without an entry (or an entry
308 /// without a handler arm) is caught here.
309 #[test]
310 fn every_handler_variant_is_registered() {
311 let all = [
312 PublicRouteHandler::HealthCheck,
313 PublicRouteHandler::OauthProtectedResourceMetadata,
314 PublicRouteHandler::Export9pMetadata,
315 PublicRouteHandler::WirePlanesMetadata,
316 PublicRouteHandler::NinepWebSocket,
317 PublicRouteHandler::BrowserProvisioning,
318 ];
319 for h in all {
320 let referenced = PUBLIC_EXEMPTIONS.iter().any(|e| e.handler == h);
321 assert!(
322 referenced,
323 "PublicRouteHandler::{h:?} has no registry entry; add one or remove the variant"
324 );
325 }
326 }
327
328 /// The main-app face owns exactly the routes it wires (snapshot). Updating
329 /// the registry requires updating this expected set in the same PR — the
330 /// explicit review touchpoint that prevents silent drift.
331 #[test]
332 fn main_app_face_snapshot_is_pinned() {
333 let main: Vec<(&'static str, RouteMethod, &'static str)> = for_face(HttpFace::MainApp)
334 .map(|e| (e.id, e.method, e.path))
335 .collect();
336 let expected = [
337 ("root-health", RouteMethod::Get, "/"),
338 ("health", RouteMethod::Get, "/health"),
339 (
340 "oauth-protected-resource",
341 RouteMethod::Get,
342 "/.well-known/oauth-protected-resource",
343 ),
344 ("export9p", RouteMethod::Get, "/.well-known/export9p"),
345 ("wire-planes", RouteMethod::Get, "/.well-known/planes"),
346 ("ninep-ws", RouteMethod::Get, "/9p"),
347 (
348 "browser-provisioning",
349 RouteMethod::Get,
350 "/.well-known/hyprstream/browser-provisioning/:service",
351 ),
352 ];
353 assert_eq!(
354 main, expected,
355 "main-app public face drifted from the reviewed snapshot"
356 );
357 }
358
359 /// `require` must resolve every id the builders reference, and reject an
360 /// unregistered id — the startup gate that blocks an unregistered route.
361 #[test]
362 fn require_resolves_registered_and_rejects_unknown() {
363 assert_eq!(require(HttpFace::MainApp, "health").path, "/health");
364 }
365
366 #[test]
367 #[should_panic(expected = "not registered")]
368 fn require_panics_for_unregistered_id() {
369 let _ = require(HttpFace::MainApp, "definitely-not-registered");
370 }
371}