Skip to main content

hyprstream_core/services/oauth/
deployment_well_known.rs

1//! Deployment static well-known endpoints (#1137 / #1136 serving half).
2//!
3//! The DID-anchored trust bootstrap (#1143) fetches four public,
4//! integrity-anchored documents from the deployment's did:web host:
5//!
6//! - `/.well-known/did.json` — the deployment DID document (alsoKnownAs →
7//!   cluster `did:at9p`, exactly one Ed25519 Multikey deployment CA,
8//!   Iroh/QUIC transport reach);
9//! - `/.well-known/at9p/<cid>.cbor` — the cluster at9p genesis capsule
10//!   (self-certifying: BLAKE3-512 over its canonical bytes IS the DID);
11//! - `/.well-known/deployment/registry-service.jwt` — the current CA-signed
12//!   registry deployment credential (one-hour freshness profile).
13//! - `/.well-known/deployment/deployment-authority.log.json` — the current
14//!   root-anchored authority log. Its head must equal the node's separately
15//!   provisioned OS-owned anti-rollback checkpoint.
16//!
17//! None of these are secret: every one is verified by the fetcher (GATE
18//! canon → hash → sig for the capsule; mutual alsoKnownAs attestation for
19//! the document; CA signature + numeric-date profile for the credential).
20//! Serving them is therefore plain static-file work — but it must happen
21//! SOMEWHERE, and the OAuth service is the deliberate choice: it already
22//! terminates the did:web document surface (`/.well-known/did.json`), and it
23//! is the only genuinely dual-stack (HTTP + RPC) service in the mesh, so the
24//! deployment's `did:web` host can terminate here directly (e.g. via the
25//! stack's Caddy reverse proxy).
26//!
27//! The operator provisions a deployment well-known directory:
28//!
29//! ```text
30//! <dir>/did.json
31//! <dir>/at9p/<cid>.cbor
32//! <dir>/deployment/deployment-authority.log.json
33//! <dir>/deployment/registry-service.jwt   (refreshed hourly by the CA holder)
34//! ```
35//!
36//! Files are re-read on EVERY request so the external credential-refresh
37//! agent needs no service restart. Missing/unreadable files are 404 — the
38//! bootstrap fails closed, never on stale in-memory copies.
39
40use std::path::{Path, PathBuf};
41
42use axum::{
43    extract::{Path as AxumPath, State},
44    http::{header, StatusCode},
45    response::{IntoResponse, Response},
46    routing::get,
47    Router,
48};
49use tokio::io::AsyncReadExt;
50
51/// Capsule cap, matching the client's `MAX_CAPSULE_BYTES`.
52const MAX_CAPSULE_BYTES: u64 = 4 * 1024 * 1024;
53/// Registry credential cap, matching the client's `MAX_CREDENTIAL_BYTES`.
54const MAX_CREDENTIAL_BYTES: u64 = 64 * 1024;
55/// DID document cap (a deployment document is a few KiB of JSON).
56const MAX_DID_DOC_BYTES: u64 = 1024 * 1024;
57
58/// Mount the deployment well-known routes. Always registered; each handler
59/// 404s when no deployment directory is configured, so an OAuth instance
60/// that is not the deployment terminator answers exactly like one where the
61/// material is absent — no information about configuration leaks.
62pub fn router<S>(deployment_dir: Option<PathBuf>) -> Router<S>
63where
64    S: Clone + Send + Sync + 'static,
65{
66    Router::new()
67        .route("/.well-known/did.json", get(serve_did_document))
68        .route("/.well-known/at9p/:cid.cbor", get(serve_capsule))
69        .route(
70            "/.well-known/deployment/registry-service.jwt",
71            get(serve_registry_credential),
72        )
73        .route(
74            "/.well-known/deployment/deployment-authority.log.json",
75            get(serve_authority_log),
76        )
77        .with_state(deployment_dir)
78}
79
80/// Serve the deployment directory's `did.json`. Mounted only in deployment
81/// mode (see `create_app`): a missing document 404s — deployment mode was
82/// explicitly selected, so a missing document is an operator error, never a
83/// reason to silently serve the dynamic node document the bootstrap would
84/// rightly reject.
85async fn serve_did_document(State(deployment_dir): State<Option<PathBuf>>) -> Response {
86    let Some(ref dir) = deployment_dir else {
87        return StatusCode::NOT_FOUND.into_response();
88    };
89    serve_file(
90        &dir.join("did.json"),
91        "application/did+json",
92        MAX_DID_DOC_BYTES,
93    )
94    .await
95}
96
97async fn serve_capsule(
98    State(deployment_dir): State<Option<PathBuf>>,
99    AxumPath(cid): AxumPath<String>,
100) -> Response {
101    let cid = match cid.strip_suffix(".cbor") {
102        Some(cid) => cid,
103        None => return StatusCode::NOT_FOUND.into_response(),
104    };
105    // The client constrains the CID to lowercase alphanumerics before it ever
106    // builds this URL; mirror that here so the parameter can never become a
107    // path-traversal primitive.
108    if cid.is_empty()
109        || !cid
110            .bytes()
111            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
112    {
113        return StatusCode::NOT_FOUND.into_response();
114    }
115    let Some(ref dir) = deployment_dir else {
116        return StatusCode::NOT_FOUND.into_response();
117    };
118    serve_file(
119        &dir.join("at9p").join(format!("{cid}.cbor")),
120        "application/cbor",
121        MAX_CAPSULE_BYTES,
122    )
123    .await
124}
125
126async fn serve_registry_credential(State(deployment_dir): State<Option<PathBuf>>) -> Response {
127    let Some(ref dir) = deployment_dir else {
128        return StatusCode::NOT_FOUND.into_response();
129    };
130    serve_file(
131        &dir.join("deployment").join("registry-service.jwt"),
132        "application/jwt",
133        MAX_CREDENTIAL_BYTES,
134    )
135    .await
136}
137
138async fn serve_authority_log(State(deployment_dir): State<Option<PathBuf>>) -> Response {
139    let Some(ref dir) = deployment_dir else {
140        return StatusCode::NOT_FOUND.into_response();
141    };
142    serve_file(
143        &dir.join("deployment").join("deployment-authority.log.json"),
144        "application/json",
145        MAX_CREDENTIAL_BYTES,
146    )
147    .await
148}
149
150/// Read and serve one file with a hard size cap. Any failure — missing,
151/// unreadable, oversize — is a plain 404: these endpoints reveal nothing
152/// about filesystem state beyond existence, and the bootstrap treats every
153/// one of them as "no deployment material served."
154async fn serve_file(path: &Path, content_type: &'static str, max_bytes: u64) -> Response {
155    match read_capped(path, max_bytes).await {
156        Ok(bytes) => (
157            StatusCode::OK,
158            [
159                (header::CONTENT_TYPE, content_type),
160                (header::CACHE_CONTROL, "no-store"),
161            ],
162            bytes,
163        )
164            .into_response(),
165        Err(error) => {
166            tracing::warn!(path = %path.display(), %error, "deployment well-known read failed");
167            StatusCode::NOT_FOUND.into_response()
168        }
169    }
170}
171
172async fn read_capped(path: &Path, max_bytes: u64) -> anyhow::Result<Vec<u8>> {
173    let file = tokio::fs::File::open(path).await?;
174    let mut limited = file.take(max_bytes + 1);
175    let mut bytes = Vec::new();
176    limited.read_to_end(&mut bytes).await?;
177    anyhow::ensure!(
178        bytes.len() <= max_bytes as usize,
179        "file exceeds {max_bytes}-byte limit"
180    );
181    Ok(bytes)
182}