Skip to main content

hyprstream_core/config/
mod.rs

1//! Unified configuration system for Hyprstream
2//!
3//! This module provides a layered configuration architecture:
4//! - `HyprConfig`: Root configuration combining all subsystems
5//! - `ServerConfig`: HTTP server configuration (network, CORS, TLS)
6//! - Model and runtime configs for ML inference
7
8pub mod server;
9
10// Re-export main configuration types
11pub use server::{
12    CorsConfig, NinepCanonicalReadConfig, SamplingParamDefaults, ServerConfig, ServerConfigBuilder,
13};
14
15// The records/repository RDS binding type lives in `hyprstream-pds` so the
16// discovery crate's accepted-state authority shares the same audited
17// resolution and verify-full validation code. Re-exported here so every
18// existing `crate::config::RdsConfig` path keeps resolving.
19pub use hyprstream_pds::rds::RdsConfig;
20
21// Inference-facing config types moved to `hyprstream-inference` (Wave B decomposition);
22// re-exported here so every existing `crate::config::...` path keeps resolving.
23pub use hyprstream_inference::config::{
24    default_lora_rank, default_target_modules, FinishReason, GenerationConfig, GenerationResult,
25    HyprstreamTrainingConfig, ModelConfig, RuntimeConfig, TTTMetrics, TTTTrainingConfig,
26    TrainingMode,
27};
28
29// Export root configuration and builder (defined below in this module)
30// Note: HyprConfig and HyprConfigBuilder are exported automatically as pub structs
31
32use crate::storage::paths::StoragePaths;
33use config::{Config, ConfigError, Environment, File};
34use serde::{Deserialize, Serialize};
35use std::path::{Path, PathBuf};
36use std::sync::OnceLock;
37use zeroize::{Zeroize, Zeroizing};
38
39/// Process-wide validated configuration snapshot (#1585).
40///
41/// Binary startup installs the configuration it parsed and validated (from an
42/// explicit `--config` file or the default locations) into this write-once
43/// slot BEFORE any resolver, factory, or service thread runs. Every later
44/// [`HyprConfig::load()`] — including the reloads inside service factories and
45/// network modules that used to re-read XDG defaults and silently drop an
46/// explicit `--config` deployment's settings — then observes that one pinned
47/// snapshot instead of re-deriving a divergent configuration.
48///
49/// The slot is immutable once written: there is no runtime mutation path, and
50/// the snapshot replaces an unchanged-contract reload rather than authorizing
51/// anything by itself (checkpoint, trust, Policy, and service-key validation
52/// all stay exactly where they were). Tests that need a different
53/// configuration run in isolated child processes.
54static PINNED_CONFIG: OnceLock<HyprConfig> = OnceLock::new();
55
56/// Install the process-wide validated configuration snapshot (write-once).
57///
58/// Returns `true` when this call installed the snapshot; `false` when an
59/// earlier install won (first write wins, matching the
60/// `install_envelope_verify_config` precedent). Callers at the single binary
61/// startup site may ignore the result.
62pub fn install_pinned_config(config: HyprConfig) -> bool {
63    PINNED_CONFIG.set(config).is_ok()
64}
65
66/// The installed validated configuration snapshot, if startup pinned one.
67pub fn pinned_config() -> Option<&'static HyprConfig> {
68    PINNED_CONFIG.get()
69}
70
71/// Canonical absolute provenance of the operator's explicit config selector
72/// (CLI `--config` or the `HYPRSTREAM_CONFIG` env), installed by binary
73/// startup before the first load (#1585). Library code that launches services
74/// (bootstrap, wizard) forwards exactly this value to
75/// [`crate::cli::handle_service_start`] so children load the same file;
76/// `None` means defaults-resolution. Write-once, like the snapshot.
77static EXPLICIT_CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();
78
79/// Install the canonical explicit config selector provenance (write-once).
80pub fn install_explicit_config_path(path: PathBuf) -> bool {
81    EXPLICIT_CONFIG_PATH.set(path).is_ok()
82}
83
84/// The canonical explicit selector, if the operator supplied one.
85pub fn explicit_config_path() -> Option<&'static PathBuf> {
86    EXPLICIT_CONFIG_PATH.get()
87}
88
89/// Unified configuration for the Hyprstream system
90#[derive(Debug, Clone, Serialize, Deserialize, Default)]
91pub struct HyprConfig {
92    /// HTTP server configuration
93    #[serde(default)]
94    pub server: ServerConfig,
95
96    /// Model configuration
97    #[serde(default)]
98    pub model: ModelConfig,
99
100    /// Standalone CPU inference service configuration (#1236/#1247).
101    #[serde(default)]
102    pub inference: InferenceServerConfig,
103
104    /// Runtime execution settings
105    #[serde(default)]
106    pub runtime: RuntimeConfig,
107
108    /// Text generation parameters
109    #[serde(default)]
110    pub generation: GenerationConfig,
111
112    /// LoRA adapter settings
113    #[serde(default)]
114    pub lora: LoraAppConfig,
115
116    /// Storage paths configuration
117    #[serde(default)]
118    pub storage: StorageConfig,
119
120    /// Git storage and P2P transport configuration
121    #[serde(default)]
122    pub git2db: git2db::config::Git2DBConfig,
123
124    /// Worker service configuration (optional)
125    ///
126    /// When present, the WorkerService will be started for container/sandbox management.
127    /// This enables Kata-based isolated workload execution.
128    #[serde(default)]
129    pub worker: Option<hyprstream_workers::config::WorkerConfig>,
130
131    /// Service management configuration
132    ///
133    /// Controls which services are started at startup in ipc-systemd mode.
134    #[serde(default)]
135    pub services: ServicesConfig,
136
137    /// JWT token configuration
138    #[serde(default)]
139    pub token: TokenConfig,
140
141    /// OpenAI-compatible HTTP API configuration
142    #[serde(default)]
143    pub oai: OAIConfig,
144
145    /// HuggingFace-XET CAS HTTP face configuration (epic #654)
146    #[serde(default)]
147    pub xet: XetConfig,
148
149    /// Arrow Flight SQL server configuration
150    #[serde(default)]
151    pub flight: FlightConfig,
152
153    /// MCP service configuration (HTTP/SSE for Model Context Protocol)
154    #[serde(default)]
155    pub mcp: MCPConfig,
156
157    /// OAuth 2.1 authorization server configuration
158    #[serde(default)]
159    pub oauth: OAuthConfig,
160
161    /// Credentials storage backend (user profiles, pubkeys, refresh tokens).
162    #[serde(default)]
163    pub credentials: CredentialsConfig,
164
165    /// StreamService configuration (buffer sizes, TTL, etc.)
166    #[serde(default)]
167    pub streaming: StreamingConfig,
168
169    /// RPC transport server tunables (stream cap, connection cap, timeouts).
170    ///
171    /// All values default to the process-wide constants in `hyprstream-rpc`
172    /// (`DEFAULT_STREAM_LIMIT=64`, `DEFAULT_CONNECTION_LIMIT=256`, etc.).
173    /// Override via `[rpc]` in the config file or `HYPRSTREAM__RPC__*` env vars.
174    #[serde(default)]
175    pub rpc: RpcServerConfig,
176
177    /// TLS configuration for HTTP services (OAI, OAuth, MCP)
178    ///
179    /// Enabled by default. Auto-generates self-signed cert when paths are unset.
180    /// Per-service `tls_cert`/`tls_key` overrides take precedence.
181    #[serde(default)]
182    pub tls: TlsConfig,
183
184    /// Account identity configuration (epic #1158, A3 / #1162).
185    ///
186    /// Names the deployment-chosen account zone, the zone-scoped DNS-01
187    /// credential, and the wildcard address targets. `Default` is the
188    /// **unconfigured** state — when the operator sets no `[account]` section,
189    /// did:web minting and DNS-01 wildcard TLS issuance degrade sanely (clear
190    /// error, no panic, no synthesized default zone name).
191    #[serde(default)]
192    pub account: crate::account::AccountZoneConfig,
193
194    /// QUIC/WebTransport configuration
195    ///
196    /// Enabled by default. Services expose a WebTransport endpoint alongside ZMQ,
197    /// allowing browsers to connect directly via HTTP/3 + QUIC.
198    /// Set `enabled = false` to disable.
199    #[serde(default)]
200    pub quic: QuicConfig,
201
202    /// Event proxy service configuration
203    #[serde(default)]
204    pub event: EventServiceConfig,
205
206    /// Registry service configuration
207    #[serde(default)]
208    pub registry: RegistryServiceConfig,
209
210    /// Policy service configuration
211    #[serde(default)]
212    pub policy: PolicyServiceConfig,
213
214    /// Discovery service configuration
215    #[serde(default)]
216    pub discovery: DiscoveryServiceConfig,
217
218    /// TUI display server configuration
219    #[serde(default)]
220    pub tui: TuiServiceConfig,
221
222    /// Metrics service configuration (DuckDB/DataFusion ingest + query)
223    #[serde(default)]
224    pub metrics: MetricsConfig,
225
226    /// Hex-encoded Ed25519 node signing key bytes (bypasses OS keyring lookup).
227    ///
228    /// **TEST USE ONLY.** Set via `HYPRSTREAM__SIGNING_KEY` env var to inject a
229    /// pre-generated key in isolated test environments where a keyring daemon is
230    /// unavailable. Never set this in production config files.
231    #[serde(default, skip_serializing)]
232    pub signing_key: Option<String>,
233
234    /// Persistent secrets storage configuration.
235    ///
236    /// Controls where signing keys and TLS materials are read from and written to.
237    /// On systemd, overridden at runtime by
238    /// `HYPRSTREAM__SECRETS__PATH=%d` in the service unit (pointing to the
239    /// systemd credentials directory).
240    #[serde(default)]
241    pub secrets: SecretsConfig,
242
243    /// Public self-certifying cluster identity pin used by the explicit
244    /// DID-anchored deployment trust source (#1136).
245    /// Must be configured together with `cluster_did_web`.
246    #[serde(default)]
247    pub cluster_at9p_did: Option<String>,
248
249    /// Public did:web alias/discovery anchor paired with `cluster_at9p_did`.
250    #[serde(default)]
251    pub cluster_did_web: Option<String>,
252
253    /// Optional extra TLS root certificate (PEM file) for private-PKI
254    /// deployments whose did:web host terminates TLS with an internal CA
255    /// (#1137). ADDITIVE — public WebPKI roots remain enabled; an unreadable
256    /// or malformed file fails the bootstrap rather than degrading.
257    #[serde(default)]
258    pub cluster_anchor_root_cert: Option<PathBuf>,
259
260    /// When `true`, this node is REMOTE from the cluster's Discovery service:
261    /// the DID-anchored bootstrap dials the did:web-advertised network
262    /// transport and requires a signed liveness ping before installing the
263    /// resolver (#1137). When `false` (default — same-node fabric, e.g. the
264    /// metal stack's containers sharing the IPC volume), a lazy local
265    /// discovery client is used, matching the OS-owned path's posture.
266    #[serde(default)]
267    pub cluster_remote_node: bool,
268
269    /// Phase-1 cellular-ledger local-enforcer configuration (epic #922, #925).
270    ///
271    /// Only present when the `ledger` cargo feature is enabled; `enabled`
272    /// defaults to `false` so the scheduler quota path is unchanged until an
273    /// operator opts in. The whole subsystem fails closed when disabled.
274    #[cfg(feature = "ledger")]
275    #[serde(default)]
276    pub ledger: crate::services::ledger::LedgerConfig,
277
278    /// Records/repository RDS (Multi-AZ Postgres) configuration (#1257).
279    ///
280    /// This is the records role's TOML-only binding. It is not a generic or
281    /// shared credential interface: deployment renders this role's explicit
282    /// URL and CA paths into `[rds]`. When unset, the record store falls back
283    /// to its local backend (RocksDB); when set, the Postgres backend is
284    /// selected and is FATAL-on-unavailable — never a silent local fallback.
285    ///
286    /// **D2 invariant** (`ARCH-recursive-federation-verdict-fable.md`): the
287    /// signed, content-addressed record/op-log bytes remain the authoritative
288    /// source of truth; the RDS rows are a projection-free KV shell over those
289    /// exact signed bytes, never a normalization of them.
290    #[serde(default)]
291    pub rds: RdsConfig,
292
293    /// Postgres URL for the durable ledger backend (PAY-01 #1389).
294    /// When set and the `postgres-ledger` feature is compiled, the factory
295    /// constructs PostgresLedger. When empty/unset, MemLedger is used (dev/test).
296    #[cfg(feature = "postgres-ledger")]
297    #[serde(default)]
298    pub ledger_postgres_url: Option<String>,
299
300    /// Connection pool size for the PostgresLedger backend. Default 4.
301    #[cfg(feature = "postgres-ledger")]
302    #[serde(default)]
303    pub ledger_postgres_pool_size: Option<usize>,
304}
305
306/// Persistent secrets storage configuration.
307///
308/// Determines the directory used for reading and writing persistent secret key
309/// material: signing keys and TLS certificates/keys.
310///
311/// On systemd, the generated service unit sets
312/// `Environment=HYPRSTREAM__SECRETS__PATH=%d` so that at runtime `path` resolves
313/// to the systemd credentials directory (non-swappable ramfs, access-restricted).
314///
315/// On non-systemd systems the default (`<config_dir>/credentials`) is used.
316#[derive(Debug, Clone, Serialize, Deserialize, Default)]
317pub struct SecretsConfig {
318    /// Override the directory from which secret files are read (and written on
319    /// first run).  `None` → resolved at runtime to `<config_dir>/credentials`.
320    #[serde(default)]
321    pub path: Option<PathBuf>,
322}
323
324impl SecretsConfig {
325    /// Resolve the secrets directory from this config section only.
326    ///
327    /// Most callers should use `HyprConfig::resolve_secrets_dir()` or
328    /// `HyprConfig::resolve_secrets_dir_for()` so env/config/XDG precedence is
329    /// applied uniformly for all secret material.
330    pub fn resolve_dir(&self, config_dir: &Path) -> PathBuf {
331        self.path
332            .clone()
333            .unwrap_or_else(|| config_dir.join("credentials"))
334    }
335
336    /// Return the default secrets directory when no config is available.
337    ///
338    /// Routes through `StoragePaths` so `XDG_CONFIG_HOME` is respected
339    /// consistently with every other directory in the application. This is
340    /// fail-closed: there is no implicit `/etc` fallback.
341    pub fn default_dir() -> anyhow::Result<PathBuf> {
342        let storage = StoragePaths::new()
343            .map_err(|e| anyhow::anyhow!("failed to initialize XDG storage paths: {e}"))?;
344        let config_dir = storage
345            .config_dir()
346            .map_err(|e| anyhow::anyhow!("failed to resolve XDG config directory: {e}"))?;
347        Ok(config_dir.join("credentials"))
348    }
349}
350
351/// TLS configuration for HTTP services (OAI, OAuth, MCP).
352///
353/// When `cert_path`/`key_path` are unset, a self-signed ECDSA P-256 certificate
354/// is auto-generated at startup with 365-day validity. Per-service overrides
355/// (`tls_cert`/`tls_key` on OAI/OAuth/MCP configs) take precedence.
356///
357/// # Example TOML
358///
359/// ```toml
360/// [tls]
361/// mode = "self-signed"   # or "acme", "acme-dns01", or "files"
362/// server_name = "localhost"
363/// # ACME (HTTP-01/TLS-ALPN-01) mode:
364/// # acme_domain = "node.example.com"
365/// # acme_contact = "mailto:ops@example.com"
366/// # acme_cache_dir = "/var/lib/hyprstream/acme"
367/// # ACME DNS-01 wildcard mode (epic #1158 / A3 — the account zone):
368/// # mode = "acme-dns01"
369/// # [account]
370/// # zone = "acct.example.com"
371/// # dns01_credential = "ref:secretstore/account-zone-token"
372/// ```
373#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
374#[serde(rename_all = "kebab-case")]
375pub enum TlsMode {
376    /// Auto-generate a self-signed certificate at startup (dev/air-gapped only).
377    #[default]
378    SelfSigned,
379    /// Obtain a certificate automatically via ACME (RFC 8555) — Let's Encrypt
380    /// or step-ca. Uses HTTP-01/TLS-ALPN-01 for a single named domain
381    /// (`acme_domain`). Does **not** support wildcard issuance.
382    Acme,
383    /// DNS-01 wildcard issuance for the deployment's account zone (epic #1158,
384    /// A3 / #1162). Obtains a `*.<apex>` certificate using the zone-scoped
385    /// credential configured under `[account]`. Wildcards cannot use HTTP-01;
386    /// DNS-01 is the only validation method public CAs accept for `*.<apex>`.
387    ///
388    /// When the account zone is unconfigured this mode **degrades sanely** to
389    /// the existing self-signed/files materials — it never panics and never
390    /// synthesizes a zone name (one-way door #1).
391    AcmeDns01,
392    /// Load certificate and key from `cert_path`/`key_path` (operator-managed).
393    Files,
394}
395
396#[derive(Debug, Clone, Serialize, Deserialize)]
397pub struct TlsConfig {
398    /// Whether TLS is enabled for HTTP services (defaults to true)
399    #[serde(default = "default_tls_enabled")]
400    pub enabled: bool,
401
402    /// TLS provisioning mode. Defaults to `self-signed` when cert_path/key_path are unset.
403    #[serde(default)]
404    pub mode: TlsMode,
405
406    /// Path to TLS certificate (PEM). Used when mode = "files".
407    #[serde(default)]
408    pub cert_path: Option<PathBuf>,
409
410    /// Path to TLS private key (PEM). Used when mode = "files".
411    #[serde(default)]
412    pub key_path: Option<PathBuf>,
413
414    /// Server name for TLS certificate (self-signed CN or ACME domain).
415    #[serde(default = "default_tls_server_name")]
416    pub server_name: String,
417
418    /// ACME: domain to obtain a certificate for. Required when mode = "acme".
419    #[serde(default)]
420    pub acme_domain: Option<String>,
421
422    /// ACME: contact email URI, e.g. "mailto:ops@example.com".
423    #[serde(default)]
424    pub acme_contact: Option<String>,
425
426    /// ACME: directory URL. Defaults to Let's Encrypt production.
427    /// Set to a step-ca or Pebble URL for self-hosted ACME.
428    #[serde(default)]
429    pub acme_directory: Option<String>,
430
431    /// ACME: directory for certificate cache and account keys.
432    #[serde(default)]
433    pub acme_cache_dir: Option<PathBuf>,
434}
435
436impl Default for TlsConfig {
437    fn default() -> Self {
438        Self {
439            enabled: true,
440            mode: TlsMode::SelfSigned,
441            cert_path: None,
442            key_path: None,
443            server_name: default_tls_server_name(),
444            acme_domain: None,
445            acme_contact: None,
446            acme_directory: None,
447            acme_cache_dir: None,
448        }
449    }
450}
451
452impl TlsConfig {
453    /// Effective TLS mode, resolving legacy cert_path/key_path into Files mode.
454    pub fn effective_mode(&self) -> TlsMode {
455        // Explicit mode overrides; legacy cert_path/key_path implies Files.
456        if self.mode != TlsMode::SelfSigned {
457            return self.mode.clone();
458        }
459        if self.cert_path.is_some() && self.key_path.is_some() {
460            return TlsMode::Files;
461        }
462        TlsMode::SelfSigned
463    }
464
465    /// Check if self-signed certificate should be generated.
466    pub fn use_self_signed(&self) -> bool {
467        self.effective_mode() == TlsMode::SelfSigned
468    }
469}
470
471fn default_tls_enabled() -> bool {
472    true
473}
474fn default_tls_server_name() -> String {
475    "localhost".to_owned()
476}
477
478/// QUIC/WebTransport transport configuration.
479///
480/// Enables WebTransport alongside ZMQ for browser-direct RPC.
481/// When `cert_path` is empty, a self-signed certificate is generated at startup.
482///
483/// # Example TOML
484///
485/// ```toml
486/// [quic]
487/// enabled = true
488/// bind_addr = "0.0.0.0:4433"
489/// server_name = "localhost"
490/// cert_path = ""
491/// key_path = ""
492/// ```
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
494#[serde(rename_all = "kebab-case")]
495pub enum NativeNetworkProfile {
496    #[default]
497    Compatibility,
498    NetworkIrohRequired,
499}
500
501#[derive(Debug, Clone, Serialize, Deserialize)]
502pub struct QuicConfig {
503    /// Whether QUIC/WebTransport is enabled (defaults to true)
504    #[serde(default = "default_quic_enabled")]
505    pub enabled: bool,
506
507    /// Address to bind the WebTransport server
508    #[serde(default = "default_quic_bind_addr")]
509    pub bind_addr: String,
510
511    /// Server name for TLS certificate (used in self-signed cert generation)
512    #[serde(default = "default_quic_server_name")]
513    pub server_name: String,
514
515    /// Path to TLS certificate (PEM). Empty = generate self-signed.
516    #[serde(default)]
517    pub cert_path: String,
518
519    /// Path to TLS private key (PEM). Empty = generate self-signed.
520    #[serde(default)]
521    pub key_path: String,
522
523    /// #410/#282: bind an iroh substrate (ALPNs `hyprstream-rpc/1` + `moql`)
524    /// as the PRIMARY production transport, in parallel with the quinn/WebTransport
525    /// endpoint (kept for back-compat). Iroh is ON by default — it provides
526    /// node_id-addressed (pkarr/N0-DNS-discoverable) federation reach, NAT
527    /// traversal, self-certifying Ed25519 identity, and PQ-hybrid key exchange.
528    /// Opt out with `[quic] iroh = false` to run quinn-only (legacy). Native-only.
529    #[serde(default = "default_iroh_enabled")]
530    pub iroh: bool,
531
532    /// Explicit native deployment profile. `network-iroh-required` forbids a
533    /// native QUIC/local fallback but does not disable the browser edge.
534    #[serde(default)]
535    pub native_network_profile: NativeNetworkProfile,
536
537    /// Separate Event producer grants, keyed by service NAME (not DID) so the
538    /// allowlist survives service-identity churn. Admission resolves the peer
539    /// DID → service name through the accepted-state authority, then checks
540    /// name membership. Tenant membership alone grants no ingress; an empty
541    /// set leaves every peer read-only. Names must be registered factory
542    /// services — validation fails at startup otherwise.
543    ///
544    /// #1652: this replaces the DID-valued grant list, and native admission
545    /// tenants are no longer configured at all — the former DID-keyed
546    /// `moql_subject_tenants` map embedded deployment DIDs in this write-once
547    /// file and went stale at every service-identity re-initialization. The
548    /// tenant is now DERIVED at admission time from the checkpointed
549    /// accepted-state store (accepted state ∩ the factory roster ⇒ `local`,
550    /// foreign records denied); see `hyprstream_discovery::admission_roster`.
551    /// A leftover `[quic.moql_subject_tenants]` table in an old file is
552    /// ignored.
553    #[serde(default)]
554    pub event_publishers: std::collections::BTreeSet<String>,
555
556    /// Explicit remote Streams ingress, separate from Event permissions.
557    /// Deliberately empty by design (#1652): no production writer emits it, an
558    /// empty set cannot go stale, and admitted native peers stay read-only on
559    /// Streams. Unlike `event_publishers` this stays DID-keyed — it is unused
560    /// policy, so re-keying it by service name is deferred to its first real
561    /// use. Non-empty entries name peer DIDs.
562    #[serde(default)]
563    pub stream_publishers: std::collections::BTreeSet<String>,
564
565    /// #358: the producer-chosen moq RELAY this node rendezvouses through, as a
566    /// dialable URI (`https://host:port` for the relay's WebTransport `/moq`
567    /// endpoint, or an iroh node URI). Empty = direct-only (the baseline). When
568    /// set, every QUIC-enabled service advertises a `Role::Relay` reach and links
569    /// its streaming origin UP to the relay, so neither publisher nor subscriber
570    /// need be directly reachable by the other. Default deployments point this at
571    /// the node's PDS / federation anchor (the `#atproto_pds` DID service entry).
572    #[serde(default)]
573    pub relay: String,
574}
575
576impl Default for QuicConfig {
577    fn default() -> Self {
578        Self {
579            enabled: true,
580            bind_addr: default_quic_bind_addr(),
581            server_name: default_quic_server_name(),
582            cert_path: String::new(),
583            key_path: String::new(),
584            iroh: default_iroh_enabled(),
585            native_network_profile: NativeNetworkProfile::Compatibility,
586            event_publishers: Default::default(),
587            stream_publishers: Default::default(),
588            relay: String::new(),
589        }
590    }
591}
592
593impl QuicConfig {
594    pub fn iroh_required(&self) -> bool {
595        self.native_network_profile == NativeNetworkProfile::NetworkIrohRequired
596    }
597
598    pub fn validate_native_network_profile(&self) -> anyhow::Result<()> {
599        if self.iroh_required() {
600            anyhow::ensure!(
601                self.enabled,
602                "network-iroh-required requires [quic] enabled = true so native Iroh can bind"
603            );
604            anyhow::ensure!(
605                self.iroh,
606                "network-iroh-required rejects [quic] iroh = false"
607            );
608        }
609        Ok(())
610    }
611
612    /// #1652: `event_publishers` is keyed by service NAME. A name that is not
613    /// a registered factory service can never match an admitted peer, so it is
614    /// rejected loudly here — at startup, not as a silent read-only surprise
615    /// (this is also what catches a stale DID-valued list from a pre-#1652
616    /// config file: DIDs are not factory names).
617    pub fn validate_admission_policy(&self) -> anyhow::Result<()> {
618        for name in &self.event_publishers {
619            anyhow::ensure!(
620                hyprstream_service::get_factory(name).is_some(),
621                "quic.event_publishers lists {name:?}, which is not a registered service name; \
622                 entries are factory service names (not DIDs) since #1652"
623            );
624        }
625        Ok(())
626    }
627
628    /// Parse bind_addr into a SocketAddr.
629    pub fn socket_addr(&self) -> anyhow::Result<std::net::SocketAddr> {
630        self.bind_addr
631            .parse()
632            .map_err(|e| anyhow::anyhow!("invalid quic.bind_addr '{}': {}", self.bind_addr, e))
633    }
634
635    /// Check if self-signed certificate should be generated.
636    ///
637    /// Warns when only one of cert_path/key_path is set (misconfiguration).
638    pub fn use_self_signed(&self) -> bool {
639        match (self.cert_path.is_empty(), self.key_path.is_empty()) {
640            (true, true) => true,
641            (false, false) => false,
642            (false, true) => {
643                tracing::warn!(
644                    "quic.cert_path is set but quic.key_path is missing — generating self-signed cert"
645                );
646                true
647            }
648            (true, false) => {
649                tracing::warn!(
650                    "quic.key_path is set but quic.cert_path is missing — generating self-signed cert"
651                );
652                true
653            }
654        }
655    }
656
657    /// Generate or load TLS materials, returning `(cert_der, key_der)`.
658    ///
659    /// `key_der` is wrapped in `Zeroizing` to ensure it is zeroed on drop.
660    ///
661    /// For self-signed certs, loads persisted ECDSA P-256 materials from the secrets
662    /// directory (generating on first run) with ≤14 day validity, as required by
663    /// WebTransport `serverCertificateHashes` (W3C spec).
664    ///
665    /// QUIC uses a separate cert (`quic-cert`) from the HTTP cert (`tls-cert`) because
666    /// WebTransport requires ≤14-day validity while HTTP allows 365 days.
667    /// Load TLS materials for QUIC/WebTransport.
668    ///
669    /// Returns a certificate **chain** (leaf first, then intermediates/CA) and the
670    /// private key. When loading from PEM files, all certificates in the file are
671    /// included — this allows CA-signed certs (e.g. mkcert) to work by bundling
672    /// the leaf + CA cert in a single PEM file.
673    pub fn load_tls_materials(&self) -> anyhow::Result<(Vec<Vec<u8>>, Zeroizing<Vec<u8>>)> {
674        if self.use_self_signed() {
675            let secrets_dir = HyprConfig::resolve_secrets_dir()?;
676            // Use quic-specific secret names so QUIC and HTTP certs have different
677            // validity windows without stomping each other's files.
678            let materials = crate::auth::identity_store::load_or_generate_tls_materials_named(
679                &secrets_dir,
680                &self.server_name,
681                14,
682                "quic-key",
683                "quic-cert",
684            )?;
685            // Self-signed: chain is just the leaf cert
686            Ok((vec![materials.cert_der], materials.key_der))
687        } else {
688            // Load from files
689            let cert_pem = std::fs::read(&self.cert_path).map_err(|e| {
690                anyhow::anyhow!("failed to read cert_path '{}': {}", self.cert_path, e)
691            })?;
692            let key_pem = std::fs::read(&self.key_path).map_err(|e| {
693                anyhow::anyhow!("failed to read key_path '{}': {}", self.key_path, e)
694            })?;
695
696            // Parse ALL certs from PEM (leaf + intermediates + CA)
697            let cert_chain: Vec<Vec<u8>> = rustls_pemfile::certs(&mut &cert_pem[..])
698                .collect::<Result<Vec<_>, _>>()
699                .map_err(|e| anyhow::anyhow!("invalid certificate PEM: {}", e))?
700                .into_iter()
701                .map(|c| c.to_vec())
702                .collect();
703            if cert_chain.is_empty() {
704                return Err(anyhow::anyhow!(
705                    "no certificate found in {}",
706                    self.cert_path
707                ));
708            }
709
710            let key_der = Zeroizing::new(
711                rustls_pemfile::private_key(&mut &key_pem[..])
712                    .map_err(|e| anyhow::anyhow!("invalid key PEM: {}", e))?
713                    .ok_or_else(|| anyhow::anyhow!("no private key found in {}", self.key_path))?
714                    .secret_der()
715                    .to_vec(),
716            );
717
718            Ok((cert_chain, key_der))
719        }
720    }
721
722    /// Build a `QuicLoopConfig` for use with `RequestLoop`.
723    ///
724    /// Optionally embeds RFC 9728 Protected Resource Metadata so HTTP/3 clients
725    /// can discover the OAuth authorization server for this QUIC endpoint.
726    pub fn to_loop_config(
727        &self,
728        service_name: &str,
729        oauth_issuer_url: Option<&str>,
730    ) -> anyhow::Result<hyprstream_rpc::service::QuicLoopConfig> {
731        let addr = self.socket_addr()?;
732        let (cert_chain, key_der) = self.load_tls_materials()?;
733        let meta_json = oauth_issuer_url.map(|issuer| {
734            let meta = crate::services::oauth::protected_resource_metadata(
735                &format!("https://{}/{}", self.server_name, service_name),
736                issuer,
737            );
738            serde_json::to_vec(&meta).unwrap_or_default()
739        });
740        Ok(hyprstream_rpc::service::QuicLoopConfig {
741            announcement_cancellation: tokio_util::sync::CancellationToken::new(),
742            cert_chain,
743            key_der,
744            bind_addr: addr,
745            server_name: self.server_name.clone(),
746            protected_resource_json: meta_json,
747            on_quic_bound: None,
748            // #410: iroh is the primary production transport (on by default).
749            // This minimal builder mirrors the daemon bootstrap default; the
750            // full `QuicSharedConfig` path in `main.rs` honours `[quic] iroh`.
751            iroh_enabled: self.iroh,
752            iroh_required: self.iroh_required(),
753            on_iroh_bound: None,
754            // #358: relay rendezvous is provisioned by the daemon bootstrap
755            // (`QuicSharedConfig`), not this minimal builder. Direct-only here.
756            moq_relay: None,
757            moq_relay_server_identity: None,
758            // #1027: admission material is provisioned by the daemon bootstrap
759            // (`QuicSharedConfig`), not this minimal builder.
760            moq_admission: None,
761            moq_ingress_authorizer: None,
762            moq_admission_proof: None,
763        })
764    }
765}
766
767fn default_quic_enabled() -> bool {
768    true
769}
770/// #410: iroh substrate is the PRIMARY production transport — on by default.
771/// The quinn-only baseline is the legacy path; opt out with `[quic] iroh = false`.
772fn default_iroh_enabled() -> bool {
773    true
774}
775fn default_quic_bind_addr() -> String {
776    "0.0.0.0:4433".to_owned()
777}
778fn default_quic_server_name() -> String {
779    "localhost".to_owned()
780}
781
782/// JWT token issuance configuration
783#[derive(Debug, Clone, Serialize, Deserialize)]
784pub struct TokenConfig {
785    #[serde(default = "default_token_ttl")]
786    pub default_ttl_seconds: u32,
787
788    #[serde(default = "default_max_token_ttl")]
789    pub max_ttl_seconds: u32,
790}
791
792impl Default for TokenConfig {
793    fn default() -> Self {
794        Self {
795            default_ttl_seconds: 172_800, // 48 hours
796            max_ttl_seconds: 172_800,     // 48 hours
797        }
798    }
799}
800
801fn default_token_ttl() -> u32 {
802    172_800
803} // 48 hours
804fn default_max_token_ttl() -> u32 {
805    172_800
806} // 48 hours
807
808/// OpenAI-compatible HTTP API configuration
809#[derive(Debug, Clone, Serialize, Deserialize)]
810pub struct OAIConfig {
811    /// Host address for HTTP server
812    #[serde(default = "default_oai_host")]
813    pub host: String,
814
815    /// Port for HTTP server
816    #[serde(default = "default_oai_port")]
817    pub port: u16,
818
819    /// External URL for this server (used in OAuth metadata and WWW-Authenticate headers).
820    /// Auto-derived from host:port if not set.
821    #[serde(default)]
822    pub external_url: Option<String>,
823
824    /// TLS certificate path (optional)
825    #[serde(default)]
826    pub tls_cert: Option<PathBuf>,
827
828    /// TLS private key path (optional)
829    #[serde(default)]
830    pub tls_key: Option<PathBuf>,
831
832    /// Request timeout in seconds
833    #[serde(default = "default_oai_timeout")]
834    pub request_timeout_secs: u64,
835
836    /// CORS configuration
837    #[serde(default)]
838    pub cors: server::CorsConfig,
839
840    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
841    #[serde(default)]
842    pub quic_port: Option<u16>,
843}
844
845impl Default for OAIConfig {
846    fn default() -> Self {
847        Self {
848            host: default_oai_host(),
849            port: default_oai_port(),
850            external_url: None,
851            tls_cert: None,
852            tls_key: None,
853            request_timeout_secs: default_oai_timeout(),
854            cors: server::CorsConfig::default(),
855            quic_port: None,
856        }
857    }
858}
859
860impl OAIConfig {
861    /// Get the resource URL, using external_url if set, otherwise deriving from host:port.
862    /// Auto-derives `https://` when global TLS is enabled.
863    pub fn resource_url(&self) -> String {
864        if let Some(ref url) = self.external_url {
865            url.clone()
866        } else {
867            let scheme = if HyprConfig::load().map(|c| c.tls.enabled).unwrap_or(false) {
868                "https"
869            } else {
870                "http"
871            };
872            let host = resource_url_host(&self.host);
873            format!("{scheme}://{host}:{}", self.port)
874        }
875    }
876}
877
878fn resource_url_host(bind_host: &str) -> &str {
879    if bind_host == "0.0.0.0" {
880        "localhost"
881    } else {
882        bind_host
883    }
884}
885
886fn default_oai_host() -> String {
887    "0.0.0.0".to_owned()
888}
889fn default_oai_port() -> u16 {
890    6789
891}
892fn default_oai_timeout() -> u64 {
893    300
894}
895
896/// XetService configuration — HuggingFace-XET CAS HTTP face.
897///
898/// When listed in `[services] startup`, exposes the HF-XET CAS wire routes (`/get_xorb/{hash}/`,
899/// `/v1/reconstructions/{hash}`, `/v1/chunks/{key}`, `/v1/xorbs/{key}`,
900/// `/v1/shards`) so a standard xet-enabled git repo can point its CAS endpoint
901/// at hyprstream as an alternative XET backend to HuggingFace. See epic #654.
902#[derive(Debug, Clone, Serialize, Deserialize)]
903pub struct XetConfig {
904    /// Host address for the HTTP server.
905    #[serde(default = "default_xet_host")]
906    pub host: String,
907
908    /// Port for the HTTP server. Default 6792 (oai=6789, mcp=6790, oauth=6791).
909    #[serde(default = "default_xet_port")]
910    pub port: u16,
911
912    /// External URL for this server (JWT audience / metadata). Auto-derived from
913    /// host:port when unset, mirroring `OAIConfig::resource_url`.
914    #[serde(default)]
915    pub external_url: Option<String>,
916
917    /// TLS certificate path (optional; falls back to the global `[tls]` config).
918    #[serde(default)]
919    pub tls_cert: Option<PathBuf>,
920
921    /// TLS private key path (optional; falls back to the global `[tls]` config).
922    #[serde(default)]
923    pub tls_key: Option<PathBuf>,
924}
925
926impl Default for XetConfig {
927    fn default() -> Self {
928        Self {
929            host: default_xet_host(),
930            port: default_xet_port(),
931            external_url: None,
932            tls_cert: None,
933            tls_key: None,
934        }
935    }
936}
937
938impl XetConfig {
939    /// Resource URL used as the JWT audience for this server. Uses `external_url`
940    /// when set, else derives `scheme://host:port` (https when global TLS is on),
941    /// mirroring `OAIConfig::resource_url`.
942    pub fn resource_url(&self) -> String {
943        if let Some(ref url) = self.external_url {
944            url.clone()
945        } else {
946            let scheme = if HyprConfig::load().map(|c| c.tls.enabled).unwrap_or(false) {
947                "https"
948            } else {
949                "http"
950            };
951            let host = if self.host == "0.0.0.0" {
952                "localhost"
953            } else {
954                &self.host
955            };
956            format!("{scheme}://{host}:{}", self.port)
957        }
958    }
959}
960
961fn default_xet_host() -> String {
962    "0.0.0.0".to_owned()
963}
964fn default_xet_port() -> u16 {
965    6792
966}
967
968/// /// Arrow Flight SQL server configuration
969#[derive(Debug, Clone, Serialize, Deserialize)]
970pub struct FlightConfig {
971    /// Host address for Flight SQL server
972    #[serde(default = "default_flight_host")]
973    pub host: String,
974
975    /// Port for Flight SQL server
976    #[serde(default = "default_flight_port")]
977    pub port: u16,
978
979    /// External resource URL used as the exact JWT audience.
980    #[serde(default)]
981    pub external_url: Option<String>,
982
983    /// Default dataset to serve (optional)
984    #[serde(default)]
985    pub default_dataset: Option<String>,
986
987    /// TLS certificate path (optional)
988    #[serde(default)]
989    pub tls_cert: Option<PathBuf>,
990
991    /// TLS private key path (optional)
992    #[serde(default)]
993    pub tls_key: Option<PathBuf>,
994
995    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
996    #[serde(default)]
997    pub quic_port: Option<u16>,
998}
999
1000impl Default for FlightConfig {
1001    fn default() -> Self {
1002        Self {
1003            host: default_flight_host(),
1004            port: default_flight_port(),
1005            external_url: None,
1006            default_dataset: None,
1007            tls_cert: None,
1008            tls_key: None,
1009            quic_port: None,
1010        }
1011    }
1012}
1013
1014impl FlightConfig {
1015    /// Resource URL used as the exact Flight access-token audience.
1016    pub fn resource_url(&self) -> String {
1017        if let Some(ref url) = self.external_url {
1018            return url.clone();
1019        }
1020        let scheme = if self.tls_cert.is_some() && self.tls_key.is_some() {
1021            "https"
1022        } else {
1023            "http"
1024        };
1025        let host = resource_url_host(&self.host);
1026        format!("{scheme}://{host}:{}", self.port)
1027    }
1028}
1029
1030fn default_flight_host() -> String {
1031    "0.0.0.0".to_owned()
1032}
1033fn default_flight_port() -> u16 {
1034    50051
1035}
1036
1037/// MCP service configuration (Model Context Protocol)
1038///
1039/// This service provides an MCP-compliant interface for AI coding assistants
1040/// (Claude Code, Cursor, etc.) to interact with hyprstream via HTTP/SSE.
1041#[derive(Debug, Clone, Serialize, Deserialize)]
1042pub struct MCPConfig {
1043    /// Host address for HTTP/SSE server
1044    #[serde(default = "default_mcp_host")]
1045    pub host: String,
1046
1047    /// Port for HTTP/SSE server
1048    #[serde(default = "default_mcp_port")]
1049    pub http_port: u16,
1050
1051    /// External URL for this server (used in OAuth metadata).
1052    /// Auto-derived from host:http_port if not set.
1053    #[serde(default)]
1054    pub external_url: Option<String>,
1055
1056    /// TLS certificate path (optional, overrides global [tls])
1057    #[serde(default)]
1058    pub tls_cert: Option<PathBuf>,
1059
1060    /// TLS private key path (optional, overrides global [tls])
1061    #[serde(default)]
1062    pub tls_key: Option<PathBuf>,
1063
1064    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
1065    #[serde(default)]
1066    pub quic_port: Option<u16>,
1067
1068    /// CORS configuration for the MCP HTTP/SSE server
1069    #[serde(default)]
1070    pub cors: server::CorsConfig,
1071}
1072
1073impl Default for MCPConfig {
1074    fn default() -> Self {
1075        Self {
1076            host: default_mcp_host(),
1077            http_port: default_mcp_port(),
1078            external_url: None,
1079            tls_cert: None,
1080            tls_key: None,
1081            quic_port: None,
1082            cors: server::CorsConfig::default(),
1083        }
1084    }
1085}
1086
1087impl MCPConfig {
1088    /// Get the resource URL, using external_url if set, otherwise deriving from host:http_port.
1089    /// Auto-derives `https://` when global TLS is enabled.
1090    pub fn resource_url(&self) -> String {
1091        if let Some(ref url) = self.external_url {
1092            url.clone()
1093        } else {
1094            let scheme = if HyprConfig::load().map(|c| c.tls.enabled).unwrap_or(false) {
1095                "https"
1096            } else {
1097                "http"
1098            };
1099            let host = if self.host == "0.0.0.0" {
1100                "localhost"
1101            } else {
1102                &self.host
1103            };
1104            format!("{scheme}://{host}:{}", self.http_port)
1105        }
1106    }
1107}
1108
1109fn default_mcp_host() -> String {
1110    "0.0.0.0".to_owned()
1111}
1112fn default_mcp_port() -> u16 {
1113    6790
1114}
1115
1116/// Configuration for a trusted external OIDC issuer.
1117#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1118pub struct TrustedIssuerConfig {
1119    /// Override the JWKS URI directly (skips AS metadata discovery).
1120    /// If absent, JWKS URI is auto-discovered from `{issuer}/.well-known/oauth-authorization-server`.
1121    #[serde(default)]
1122    pub jwks_uri: Option<String>,
1123    /// How long to cache the JWKS before re-fetching (default: 300 seconds).
1124    #[serde(default = "default_jwks_cache_ttl")]
1125    pub jwks_cache_ttl_secs: u64,
1126    /// Allow plain HTTP for JWKS fetches (default: false).
1127    ///
1128    /// **SECURITY WARNING:** Enabling this allows MITM attacks on the JWKS endpoint.
1129    /// Only use for internal networks or local development. Never enable in production.
1130    #[serde(default)]
1131    pub allow_http: bool,
1132    /// Additional accepted Federate client class beside the hardcoded staging
1133    /// www pin (the TUI harness). Issuer-scoped: only consulted when this
1134    /// entry's key is the Federate issuer origin (`https://login.federate.to`).
1135    /// Absent = current behavior: the hardcoded staging client is the only
1136    /// accepted class (backward compatible).
1137    #[serde(default, skip_serializing_if = "Option::is_none")]
1138    pub federate_tui_client: Option<FederateClientClassConfig>,
1139}
1140
1141/// A second accepted Federate client class (W1: the client-side TUI harness).
1142///
1143/// Carries the same source-verification invariants as the hardcoded staging
1144/// www pin; it only selects the pinned `client_id`/`aud` and the Dex
1145/// connector pin. The `client_id` MUST NOT equal the reserved staging client
1146/// (`cyberdione-www-staging`) so the reserved-credential predicate — which
1147/// matches that exact `(iss, client_id)` pair — can never fire for this
1148/// class. This states predicate-level reservation behavior only; the output
1149/// credential profile and dispatch are owned by W1.3/W1.4.
1150#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1151pub struct FederateClientClassConfig {
1152    /// OAuth `client_id` of the public client registered at the issuer.
1153    pub client_id: String,
1154    /// Expected `aud` (single string or single-element array) of the source
1155    /// ID token for this class. Usually equal to `client_id` for a public
1156    /// OIDC client; `azp` must always equal `client_id`.
1157    pub aud: String,
1158    /// Pinned Dex `connector_id` for this class. Defaults to `atproto`.
1159    #[serde(default)]
1160    pub connector_id: Option<String>,
1161}
1162
1163fn default_jwks_cache_ttl() -> u64 {
1164    300
1165}
1166
1167/// Configuration for a trusted mesh peer's post-quantum signing identity (#157).
1168///
1169/// Admin-anchored entry binding a peer's Ed25519 mesh **signer** identity (the
1170/// envelope/COSE signer key, used as the kid anchor) to its trusted ML-DSA-65
1171/// mesh verifying key. These entries populate the process-global
1172/// `KeyedPqTrustStore` eagerly at startup; the store is immutable thereafter.
1173///
1174/// Both keys are supplied **inline**, out-of-band, as `Multikey`
1175/// `publicKeyMultibase` strings (base58btc, multicodec-prefixed) — the same
1176/// encoding the node publishes in its DID document (`#mesh` ed25519-pub `0xed01`
1177/// and `#mesh-pq` ml-dsa-65-pub `0x1211`). An operator copies a peer's
1178/// `#mesh` and `#mesh-pq` `publicKeyMultibase` values from that peer's DID doc.
1179///
1180/// This matches the `KeyedPqTrustStore` contract ("Entries MUST be established
1181/// out-of-band") and the Tiles interop admission model: only keys an operator
1182/// configured are trusted. If `mesh_peers` is empty, the store is empty and
1183/// behavior is unchanged (Hybrid fails closed for unknown peers).
1184#[derive(Debug, Clone, Serialize, Deserialize)]
1185pub struct MeshPeerConfig {
1186    /// Peer's Ed25519 mesh signer public key as a `Multikey` `publicKeyMultibase`
1187    /// string (base58btc `z…`, multicodec `ed25519-pub` `0xed01`). This is the
1188    /// kid anchor the COSE composite is verified against.
1189    pub ed25519_multibase: String,
1190    /// Peer's ML-DSA-65 mesh verifying key as a `Multikey` `publicKeyMultibase`
1191    /// string (base58btc `z…`, multicodec `ml-dsa-65-pub` `0x1211`). The trusted
1192    /// post-quantum key bound to `ed25519_multibase`.
1193    pub mldsa65_multibase: String,
1194}
1195
1196/// Protocol kind for an external OAuth/OIDC provider.
1197#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1198#[serde(rename_all = "lowercase")]
1199pub enum ProviderKind {
1200    /// Full OpenID Connect — discovery document + id_token JWT verification. Default.
1201    #[default]
1202    Oidc,
1203    /// Generic OAuth 2.0 with a userinfo endpoint. No discovery, no id_token.
1204    /// Requires `authorization_endpoint`, `token_endpoint_url`, and `userinfo_endpoint`.
1205    OAuth2,
1206}
1207
1208/// Claim field name overrides for mapping a userinfo JSON response to standard claims.
1209#[derive(Debug, Clone, Serialize, Deserialize)]
1210pub struct ClaimMapping {
1211    /// Field name for the stable subject identifier. Default: `"sub"`.
1212    /// GitHub uses `"id"` (numeric integer, coerced to string).
1213    /// Discord uses `"id"` (string snowflake).
1214    #[serde(default = "default_claim_sub")]
1215    pub sub: String,
1216    /// Field name for display name. `None` omits the name from the synthetic claims.
1217    #[serde(default = "default_claim_name")]
1218    pub name: Option<String>,
1219    /// Field name for email address. `None` omits email.
1220    #[serde(default = "default_claim_email")]
1221    pub email: Option<String>,
1222    /// Field name for the email-verified boolean.
1223    /// `None`, or a field that is absent/null in the response, is treated as `false`.
1224    #[serde(default = "default_claim_email_verified")]
1225    pub email_verified: Option<String>,
1226}
1227
1228impl Default for ClaimMapping {
1229    fn default() -> Self {
1230        Self {
1231            sub: default_claim_sub(),
1232            name: default_claim_name(),
1233            email: default_claim_email(),
1234            email_verified: default_claim_email_verified(),
1235        }
1236    }
1237}
1238
1239fn default_claim_sub() -> String {
1240    "sub".into()
1241}
1242fn default_claim_name() -> Option<String> {
1243    Some("name".into())
1244}
1245fn default_claim_email() -> Option<String> {
1246    Some("email".into())
1247}
1248fn default_claim_email_verified() -> Option<String> {
1249    Some("email_verified".into())
1250}
1251
1252/// Configuration for an external OIDC provider (login delegation).
1253///
1254/// Hyprstream acts as an OIDC Relying Party to this provider. Users authenticate
1255/// with the provider; hyprstream validates the external id_token and issues its
1256/// own JWT with scopes from the policy engine.
1257#[derive(Debug, Clone, Serialize, Deserialize)]
1258pub struct OidcProviderConfig {
1259    /// Provider protocol kind. Default: `"oidc"`.
1260    #[serde(default)]
1261    pub kind: ProviderKind,
1262    /// OIDC issuer URL. Required for `kind = "oidc"`.
1263    /// Must support `/.well-known/openid-configuration`.
1264    #[serde(default)]
1265    pub issuer_url: Option<String>,
1266    /// Authorization endpoint URL. Required for `kind = "oauth2"`.
1267    #[serde(default)]
1268    pub authorization_endpoint: Option<String>,
1269    /// Token endpoint URL. Required for `kind = "oauth2"`. Named `token_endpoint_url`
1270    /// to avoid collision with method names on OIDC metadata types.
1271    #[serde(default)]
1272    pub token_endpoint_url: Option<String>,
1273    /// Userinfo endpoint URL. Required for `kind = "oauth2"`.
1274    #[serde(default)]
1275    pub userinfo_endpoint: Option<String>,
1276    /// Whether the provider supports PKCE (`code_challenge`). Default: `true`.
1277    /// Set to `false` for providers that reject the parameter (e.g. GitHub).
1278    #[serde(default = "default_pkce_supported")]
1279    pub pkce_supported: bool,
1280    /// Claim field name overrides for mapping userinfo JSON to synthetic claims.
1281    #[serde(default)]
1282    pub claim_mapping: ClaimMapping,
1283    /// Client ID registered with the external provider.
1284    pub client_id: String,
1285    /// Client secret (optional — omit for public client with PKCE).
1286    #[serde(default)]
1287    pub client_secret: Option<String>,
1288    /// Scopes to request from the provider.
1289    #[serde(default)]
1290    pub scopes: Vec<String>,
1291    /// Display name for the login UI (e.g., "Sign in with GitHub").
1292    #[serde(default)]
1293    pub display_name: Option<String>,
1294    /// Allow plain HTTP for discovery (dev only).
1295    #[serde(default)]
1296    pub allow_http: bool,
1297    /// User identity mapping strategy.
1298    #[serde(default)]
1299    pub user_mapping: UserMappingStrategy,
1300    /// Explicit root-configured Federate owner enrollment for interactive
1301    /// OIDC. When present, the signed Federate ATProto owner DID must match
1302    /// `owner_did`, and an existing hosted account is linked atomically. When
1303    /// `username` is set the link target is fixed by trusted configuration;
1304    /// when omitted, the user must explicitly start a session-bound owner-link
1305    /// flow after signing into an existing hosted account. This never
1306    /// provisions an account.
1307    #[serde(default, skip_serializing_if = "Option::is_none")]
1308    pub federate_atproto_owner: Option<FederateAtprotoOwnerEnrollment>,
1309    /// User provisioning mode.
1310    #[serde(default)]
1311    pub provisioning: ProvisioningMode,
1312    /// Allowed email domains (when provisioning = allowlist).
1313    #[serde(default)]
1314    pub allowed_domains: Vec<String>,
1315    /// Default hyprstream scopes for auto-provisioned users.
1316    #[serde(default)]
1317    pub default_scopes: Vec<String>,
1318    /// Clock skew tolerance for JWT validation (seconds). OIDC only.
1319    #[serde(default = "default_clock_skew")]
1320    pub clock_skew_seconds: u64,
1321}
1322
1323/// Trusted deployment mapping from one Federate ATProto owner identity to an
1324/// already-enrolled local hosted account. Both values come from launcher or
1325/// operator configuration; neither is accepted from callback parameters.
1326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1327pub struct FederateAtprotoOwnerEnrollment {
1328    pub owner_did: String,
1329    #[serde(default, skip_serializing_if = "Option::is_none")]
1330    pub username: Option<String>,
1331}
1332
1333fn default_pkce_supported() -> bool {
1334    true
1335}
1336
1337impl OidcProviderConfig {
1338    pub fn effective_authorization_endpoint(&self) -> Option<&str> {
1339        self.authorization_endpoint.as_deref()
1340    }
1341
1342    pub fn effective_token_endpoint_url(&self) -> Option<&str> {
1343        self.token_endpoint_url.as_deref()
1344    }
1345
1346    pub fn effective_userinfo_endpoint(&self) -> Option<&str> {
1347        self.userinfo_endpoint.as_deref()
1348    }
1349
1350    pub fn effective_pkce_supported(&self) -> bool {
1351        self.pkce_supported
1352    }
1353
1354    pub fn effective_claim_mapping(&self) -> ClaimMapping {
1355        self.claim_mapping.clone()
1356    }
1357
1358    pub fn effective_scopes(&self) -> Vec<String> {
1359        if !self.scopes.is_empty() {
1360            return self.scopes.clone();
1361        }
1362        match self.kind {
1363            ProviderKind::Oidc => default_oidc_scopes(),
1364            ProviderKind::OAuth2 => vec![],
1365        }
1366    }
1367}
1368
1369fn default_oidc_scopes() -> Vec<String> {
1370    vec!["openid".into(), "profile".into(), "email".into()]
1371}
1372fn default_clock_skew() -> u64 {
1373    60
1374}
1375
1376/// How to map an external OIDC identity to a local hyprstream subject.
1377#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1378#[serde(rename_all = "lowercase")]
1379pub enum UserMappingStrategy {
1380    /// `provider_slug:external_sub` (e.g., `keycloak:12345`). Default.
1381    #[default]
1382    Namespaced,
1383    /// Use the `email` claim (requires `email_verified=true`).
1384    Email,
1385    /// Use a specific claim value.
1386    Claim {
1387        /// The claim name to use as the local subject.
1388        name: String,
1389    },
1390    /// Disabled legacy setting that attempted to mint path-form account DIDs.
1391    /// Configuration validation and the runtime mapping path both reject it.
1392    /// Host-form account minting is a separate design (#1163).
1393    DidWeb,
1394}
1395
1396/// Whether to auto-create users on first external login.
1397#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1398#[serde(rename_all = "lowercase")]
1399pub enum ProvisioningMode {
1400    /// Reject unknown users (admin must pre-create).
1401    #[default]
1402    Deny,
1403    /// Auto-provision on first login.
1404    Auto,
1405    /// Auto-provision only for matching `allowed_domains`.
1406    Allowlist,
1407}
1408
1409/// OAuth 2.1 authorization server configuration
1410///
1411/// Provides OAuth 2.1 (draft-ietf-oauth-v2-1-13) authorization for MCP and OAI services.
1412/// Supports RFC 7591 (Dynamic Client Registration), RFC 8414 (AS Metadata),
1413/// RFC 8707 (Resource Indicators), and Client ID Metadata Documents.
1414#[derive(Debug, Clone, Serialize, Deserialize)]
1415pub struct OAuthConfig {
1416    /// Host address for OAuth server
1417    #[serde(default = "default_oauth_host")]
1418    pub host: String,
1419
1420    /// Port for OAuth server
1421    #[serde(default = "default_oauth_port")]
1422    pub port: u16,
1423
1424    /// External URL for this server (used in metadata responses).
1425    /// Auto-derived from host:port if not set.
1426    #[serde(default)]
1427    pub external_url: Option<String>,
1428
1429    /// Default scopes granted to new clients
1430    #[serde(default = "default_oauth_scopes")]
1431    pub default_scopes: Vec<String>,
1432
1433    /// Access token TTL in seconds
1434    #[serde(default = "default_oauth_token_ttl")]
1435    pub token_ttl_seconds: u32,
1436
1437    /// Refresh token TTL in seconds (default: 72 hours)
1438    #[serde(default = "default_refresh_token_ttl")]
1439    pub refresh_token_ttl_seconds: u32,
1440
1441    /// TLS certificate path (optional, overrides global [tls])
1442    #[serde(default)]
1443    pub tls_cert: Option<PathBuf>,
1444
1445    /// TLS private key path (optional, overrides global [tls])
1446    #[serde(default)]
1447    pub tls_key: Option<PathBuf>,
1448
1449    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
1450    #[serde(default)]
1451    pub quic_port: Option<u16>,
1452
1453    /// Deployment static well-known directory (#1137 / #1136 serving half).
1454    /// When set, this OAuth instance terminates the deployment's did:web host:
1455    /// `/.well-known/did.json` serves `<dir>/did.json` (replacing the dynamic
1456    /// node document), `/.well-known/at9p/<cid>.cbor` serves the cluster at9p
1457    /// capsule, `/.well-known/deployment/deployment-authority.log.json` serves
1458    /// the current root-anchored authority log, and
1459    /// `/.well-known/deployment/registry-service.jwt` serves the current
1460    /// registry credential. All are public, integrity-anchored bytes re-read
1461    /// on every request so an external credential-refresh agent needs no
1462    /// restart.
1463    #[serde(default)]
1464    pub deployment_well_known_dir: Option<PathBuf>,
1465
1466    /// CORS configuration for the OAuth HTTP server
1467    #[serde(default = "default_oauth_cors")]
1468    pub cors: server::CorsConfig,
1469
1470    /// Trusted external OIDC issuers for federation.
1471    /// Key = issuer URL (must match JWT `iss` claim exactly).
1472    /// Value = configuration for fetching/caching that issuer's JWKS.
1473    #[serde(default)]
1474    pub trusted_issuers: std::collections::HashMap<String, TrustedIssuerConfig>,
1475
1476    /// Exact HTTPS origins permitted for authenticated `did:web` federation
1477    /// intake through the identity registration API.
1478    ///
1479    /// This is deliberately separate from CORS, OIDC issuers, and federation
1480    /// policy. Entries must be origins only (no wildcard, path, query,
1481    /// fragment, or userinfo). An empty list disables `did:web` intake while
1482    /// retaining the fixed-directory `did:plc` arm.
1483    #[serde(default)]
1484    pub identity_registration_did_web_origins: Vec<String>,
1485
1486    /// Trusted mesh peers' post-quantum signing identities (#157).
1487    /// Key = an operator-chosen peer label (informational only).
1488    /// Value = the peer's Ed25519 mesh signer key + ML-DSA-65 mesh verifying
1489    /// key, supplied inline as out-of-band `Multikey` strings. Populates the
1490    /// process-global `KeyedPqTrustStore` eagerly at startup (admin-anchored,
1491    /// immutable). Empty = empty store = unchanged behavior (Hybrid fails
1492    /// closed for unknown peers). Distinct from `trusted_issuers`.
1493    #[serde(default)]
1494    pub mesh_peers: std::collections::HashMap<String, MeshPeerConfig>,
1495
1496    /// OpenID Federation 1.0 Trust Anchor URLs (optional).
1497    /// When set, included as `authority_hints` in the entity configuration JWT,
1498    /// making this node discoverable within the named federations.
1499    /// Example: `["https://federation.example.org"]`
1500    #[serde(default)]
1501    pub authority_hints: Vec<String>,
1502
1503    /// External OIDC providers for login delegation (IdP-agnostic).
1504    ///
1505    /// Users authenticate with the external provider; hyprstream validates the
1506    /// external id_token and issues its own JWT with scopes from the policy engine.
1507    /// Separate from `trusted_issuers` which is for hyprstream federation (direct
1508    /// JWT acceptance between nodes).
1509    #[serde(default)]
1510    pub oidc_providers: std::collections::HashMap<String, OidcProviderConfig>,
1511
1512    /// Hex-encoded Ed25519 private key bytes for the local user identity (bypasses OS keyring).
1513    ///
1514    /// **TEST USE ONLY.** Set via `HYPRSTREAM__OAUTH__USER_SIGNING_KEY` env var.
1515    /// Allows the `sign-challenge` CLI and wizard to use a pre-generated key in
1516    /// isolated test environments without a keyring daemon.
1517    /// Never set this in production config files.
1518    #[serde(default, skip_serializing)]
1519    pub user_signing_key: Option<String>,
1520
1521    /// How long to cache a third-party OAuth client's JWKS fetched
1522    /// via `jwks_uri` (RFC 7591 §2.1). Applies to `private_key_jwt`
1523    /// client authentication at the token endpoint.
1524    ///
1525    /// Clients that rotate signing keys faster than this should keep
1526    /// the old key in their JWKS for at least one cache window so
1527    /// verification spans the rotation (standard JWKS rotation
1528    /// hygiene). Default: 3600 seconds (1 hour).
1529    ///
1530    /// Distinct from `trusted_issuers[*].jwks_cache_ttl_secs` (which
1531    /// configures hyprstream federation peers, not OAuth clients).
1532    #[serde(default = "default_client_jwks_uri_cache_ttl")]
1533    pub client_jwks_uri_cache_ttl_secs: u64,
1534
1535    /// How many days a JWT signing key remains in the active (issuance) slot.
1536    #[serde(default = "default_jwt_key_active_days")]
1537    pub jwt_key_active_days: u32,
1538
1539    /// How many days before active-key expiry a lead key is pre-generated.
1540    #[serde(default = "default_jwt_key_lead_days")]
1541    pub jwt_key_lead_days: u32,
1542
1543    /// How many extra days after active-key expiry the drain key remains in JWKS for verification.
1544    #[serde(default = "default_jwt_key_drain_days")]
1545    pub jwt_key_drain_days: u32,
1546
1547    /// Override active key lifetime in seconds (takes precedence over `jwt_key_active_days`).
1548    /// Intended for integration tests with short rotation cycles.
1549    #[serde(default)]
1550    pub jwt_key_active_secs: Option<u32>,
1551
1552    /// Override lead key pre-generation window in seconds (takes precedence over `jwt_key_lead_days`).
1553    #[serde(default)]
1554    pub jwt_key_lead_secs: Option<u32>,
1555
1556    /// Override drain key retention window in seconds (takes precedence over `jwt_key_drain_days`).
1557    #[serde(default)]
1558    pub jwt_key_drain_secs: Option<u32>,
1559
1560    /// Override rotation check interval in seconds (default: 21600 = 6 hours).
1561    #[serde(default)]
1562    pub jwt_key_rotation_check_secs: Option<u64>,
1563
1564    /// Enforce RFC 9126 Pushed Authorization Requests at `/oauth/authorize`.
1565    ///
1566    /// When `true`, the authorization endpoint rejects any request that does
1567    /// not arrive via a `request_uri` referencing a prior `/oauth/par` call.
1568    /// Advertised in server metadata as `require_pushed_authorization_requests`.
1569    /// Defaults to `false` for compatibility.
1570    #[serde(default)]
1571    pub require_pushed_authorization_requests: bool,
1572
1573    /// Enable the `com.atproto.*` XRPC read slice (`/xrpc/…`) served from the
1574    /// OAuth HTTP surface (#1112). Defaults to `false` — the data plane is
1575    /// inert until the operator explicitly opts in and the write path (#910)
1576    /// populates the in-process `XrpcRepoStore` with `public`-flagged snapshots.
1577    /// When `false`, the XRPC routes are not mounted at all.
1578    #[serde(default)]
1579    pub xrpc_read_slice: bool,
1580
1581    /// Enable the single, read-only public Git canary proxy on the HTTPS
1582    /// listener. The proxy forwards only the fixed `canary.git` upload-pack
1583    /// endpoints to this loopback port. The loopback backend must itself be
1584    /// configured with exactly one exported repository and no receive-pack.
1585    /// `None` leaves the public Git routes unmounted.
1586    #[serde(default)]
1587    pub public_git_canary_backend_port: Option<u16>,
1588
1589    /// Opt in one Registry-owned `ai.hyprstream.model` record to the public
1590    /// XRPC getRecord path. This is the canonical Registry UUID; the publisher
1591    /// Every other record remains behind the existing Discovery policy boundary.
1592    #[serde(default)]
1593    pub public_git_canary_registry_repo_id: Option<String>,
1594
1595    /// Exact Registry PdsPublisher DID from the operator-attested canonical
1596    /// mapping. Registry and OAuth have distinct process signing keys, so the
1597    /// OAuth key cannot be used to infer this publisher identity. Both canary
1598    /// fields must be configured together; neither is set by default.
1599    #[serde(default)]
1600    pub public_git_canary_publisher_did: Option<String>,
1601
1602    /// Read-only PLC directory used to resolve ATProto account signing keys.
1603    #[serde(default = "default_atproto_plc_directory_url")]
1604    pub atproto_plc_directory_url: String,
1605
1606    /// TTL for validated ATProto DID documents.
1607    #[serde(default = "default_atproto_did_cache_ttl")]
1608    pub atproto_did_cache_ttl_secs: u64,
1609}
1610
1611fn default_atproto_plc_directory_url() -> String {
1612    "https://plc.directory".to_owned()
1613}
1614
1615fn default_atproto_did_cache_ttl() -> u64 {
1616    3600
1617}
1618
1619fn default_oauth_cors() -> server::CorsConfig {
1620    server::CorsConfig::public()
1621}
1622
1623impl Default for OAuthConfig {
1624    fn default() -> Self {
1625        Self {
1626            host: default_oauth_host(),
1627            port: default_oauth_port(),
1628            external_url: None,
1629            default_scopes: default_oauth_scopes(),
1630            token_ttl_seconds: default_oauth_token_ttl(),
1631            refresh_token_ttl_seconds: default_refresh_token_ttl(),
1632            client_jwks_uri_cache_ttl_secs: default_client_jwks_uri_cache_ttl(),
1633            tls_cert: None,
1634            tls_key: None,
1635            quic_port: None,
1636            cors: default_oauth_cors(),
1637            trusted_issuers: std::collections::HashMap::new(),
1638            identity_registration_did_web_origins: Vec::new(),
1639            mesh_peers: std::collections::HashMap::new(),
1640            authority_hints: Vec::new(),
1641            oidc_providers: std::collections::HashMap::new(),
1642            user_signing_key: None,
1643            jwt_key_active_days: default_jwt_key_active_days(),
1644            jwt_key_lead_days: default_jwt_key_lead_days(),
1645            jwt_key_drain_days: default_jwt_key_drain_days(),
1646            jwt_key_active_secs: None,
1647            jwt_key_lead_secs: None,
1648            jwt_key_drain_secs: None,
1649            jwt_key_rotation_check_secs: None,
1650            // #1113 rev2 F6: do NOT default true globally — that breaks
1651            // existing inline non-atproto auth. PAR is enforced on the
1652            // atproto profile at the authorize handler level.
1653            require_pushed_authorization_requests: false,
1654            xrpc_read_slice: false,
1655            public_git_canary_backend_port: None,
1656            public_git_canary_registry_repo_id: None,
1657            public_git_canary_publisher_did: None,
1658            atproto_plc_directory_url: default_atproto_plc_directory_url(),
1659            atproto_did_cache_ttl_secs: default_atproto_did_cache_ttl(),
1660            deployment_well_known_dir: None,
1661        }
1662    }
1663}
1664
1665impl OAuthConfig {
1666    /// Active key lifetime in seconds (`_secs` override wins over `_days * 86400`).
1667    pub fn active_secs(&self) -> i64 {
1668        self.jwt_key_active_secs
1669            .map_or_else(|| i64::from(self.jwt_key_active_days) * 86400, i64::from)
1670    }
1671
1672    /// Lead pre-generation window in seconds.
1673    pub fn lead_secs(&self) -> i64 {
1674        self.jwt_key_lead_secs
1675            .map_or_else(|| i64::from(self.jwt_key_lead_days) * 86400, i64::from)
1676    }
1677
1678    /// Drain retention window in seconds.
1679    pub fn drain_secs(&self) -> i64 {
1680        self.jwt_key_drain_secs
1681            .map_or_else(|| i64::from(self.jwt_key_drain_days) * 86400, i64::from)
1682    }
1683
1684    /// Rotation check interval (default 6 hours).
1685    pub fn rotation_check_interval(&self) -> std::time::Duration {
1686        std::time::Duration::from_secs(self.jwt_key_rotation_check_secs.unwrap_or(6 * 3600))
1687    }
1688
1689    /// Get the configured issuer URL, preserving an explicit path when set,
1690    /// otherwise deriving it from host:port.
1691    /// Auto-derives `https://` when global TLS is enabled.
1692    pub fn issuer_url(&self) -> String {
1693        if let Some(ref url) = self.external_url {
1694            url.clone()
1695        } else {
1696            let scheme = if HyprConfig::load().map(|c| c.tls.enabled).unwrap_or(false) {
1697                "https"
1698            } else {
1699                "http"
1700            };
1701            let host = if self.host == "0.0.0.0" {
1702                "localhost"
1703            } else {
1704                &self.host
1705            };
1706            format!("{scheme}://{host}:{}", self.port)
1707        }
1708    }
1709}
1710
1711fn default_oauth_host() -> String {
1712    "0.0.0.0".to_owned()
1713}
1714fn default_oauth_port() -> u16 {
1715    6791
1716}
1717
1718/// Which backend stores account credentials.
1719///
1720/// `Pglite` selects the embedded relational store; `Postgres` selects the
1721/// networked RDS relational store. Token and device stores remain independent
1722/// RocksDB/Valkey services — neither relational UserStore implements a token
1723/// store.
1724#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1725#[serde(rename_all = "lowercase")]
1726pub enum CredentialsBackend {
1727    Rocksdb,
1728    Valkey,
1729    /// Relational UserStore on the shared #1351 PGlite substrate.
1730    Pglite,
1731    /// Networked relational UserStore on the RDS Postgres substrate.
1732    Postgres,
1733}
1734
1735fn default_credentials_backend() -> CredentialsBackend {
1736    CredentialsBackend::Pglite
1737}
1738
1739impl CredentialsBackend {
1740    /// Production must never select a backend that can persist protected
1741    /// UserStore columns as plaintext.
1742    pub fn ensure_allowed_for_build(self) -> anyhow::Result<()> {
1743        anyhow::ensure!(
1744            matches!(self, Self::Pglite | Self::Postgres),
1745            "encrypted credential storage requires credentials.backend = \"pglite\" or \"postgres\""
1746        );
1747        Ok(())
1748    }
1749}
1750
1751/// Valkey connection settings (used when `backend = "valkey"`).
1752#[derive(Debug, Clone, Serialize, Deserialize)]
1753pub struct ValkeyCredentialsConfig {
1754    #[serde(default = "default_valkey_url")]
1755    pub url: String,
1756}
1757
1758fn default_valkey_url() -> String {
1759    "redis://127.0.0.1:6379".to_owned()
1760}
1761
1762impl Default for ValkeyCredentialsConfig {
1763    fn default() -> Self {
1764        Self {
1765            url: default_valkey_url(),
1766        }
1767    }
1768}
1769
1770/// Credentials storage configuration.
1771///
1772/// Selects the backend for user profiles and pubkeys. OAuth refresh tokens use
1773/// their independent token store.
1774///
1775/// # Example TOML
1776/// ```toml
1777/// [credentials]
1778/// backend = "valkey"
1779/// [credentials.valkey]
1780/// url = "redis://127.0.0.1:6379"
1781/// ```
1782#[derive(Debug, Clone, Serialize, Deserialize)]
1783pub struct CredentialsConfig {
1784    #[serde(default = "default_credentials_backend")]
1785    pub backend: CredentialsBackend,
1786    #[serde(default)]
1787    pub valkey: ValkeyCredentialsConfig,
1788}
1789
1790impl Default for CredentialsConfig {
1791    fn default() -> Self {
1792        Self {
1793            backend: default_credentials_backend(),
1794            valkey: ValkeyCredentialsConfig::default(),
1795        }
1796    }
1797}
1798fn default_oauth_scopes() -> Vec<String> {
1799    // The DEFAULT GRANT set when a client omits `scope`. atproto transition
1800    // scopes are deliberately ABSENT — they are supported-but-explicit opt-in
1801    // scopes that activate the strict atproto profile; including them here
1802    // would silently activate the strict profile for omitted-scope requests
1803    // (#1113 rev2 F4/F6). They ARE advertised in scopes_supported (see
1804    // metadata.rs `advertised_scopes`).
1805    vec![
1806        "read:*:*".to_owned(),
1807        "infer:model:*".to_owned(),
1808        "write:*:*".to_owned(),
1809    ]
1810}
1811fn default_oauth_token_ttl() -> u32 {
1812    3600
1813}
1814fn default_refresh_token_ttl() -> u32 {
1815    2_628_000
1816} // 730 hours (~30 days)
1817fn default_client_jwks_uri_cache_ttl() -> u64 {
1818    3600
1819} // 1 hour
1820fn default_jwt_key_active_days() -> u32 {
1821    14
1822}
1823fn default_jwt_key_lead_days() -> u32 {
1824    7
1825}
1826fn default_jwt_key_drain_days() -> u32 {
1827    30
1828}
1829
1830/// StreamService configuration
1831///
1832/// RPC transport server tunables. Mirrors `hyprstream_rpc::transport::rpc_session::RpcConfig`
1833/// so operators can tune these via the config file or `HYPRSTREAM__RPC__*` env vars.
1834#[derive(Debug, Clone, Serialize, Deserialize)]
1835pub struct RpcServerConfig {
1836    /// Max concurrent in-flight bidi streams (server-wide semaphore).
1837    #[serde(default = "default_rpc_stream_limit")]
1838    pub stream_limit: usize,
1839    /// Max concurrent accepted connections per server.
1840    #[serde(default = "default_rpc_connection_limit")]
1841    pub connection_limit: usize,
1842    /// Max wall-clock seconds to read a single request frame.
1843    #[serde(default = "default_rpc_request_read_timeout_secs")]
1844    pub request_read_timeout_secs: u64,
1845    /// Max seconds for a peer's QUIC/WebTransport handshake to complete.
1846    #[serde(default = "default_rpc_handshake_timeout_secs")]
1847    pub handshake_timeout_secs: u64,
1848    /// Grace period (seconds) after writing a response for the peer to ack FIN.
1849    #[serde(default = "default_rpc_stopped_grace_secs")]
1850    pub stopped_grace_secs: u64,
1851    /// Max seconds for graceful drain on shutdown.
1852    #[serde(default = "default_rpc_drain_timeout_secs")]
1853    pub drain_timeout_secs: u64,
1854}
1855
1856impl Default for RpcServerConfig {
1857    fn default() -> Self {
1858        use hyprstream_rpc::transport::rpc_session as rpc;
1859        Self {
1860            stream_limit: rpc::DEFAULT_STREAM_LIMIT,
1861            connection_limit: rpc::DEFAULT_CONNECTION_LIMIT,
1862            request_read_timeout_secs: rpc::REQUEST_READ_TIMEOUT.as_secs(),
1863            handshake_timeout_secs: rpc::HANDSHAKE_TIMEOUT.as_secs(),
1864            stopped_grace_secs: rpc::STOPPED_GRACE.as_secs(),
1865            drain_timeout_secs: rpc::DRAIN_TIMEOUT.as_secs(),
1866        }
1867    }
1868}
1869
1870fn default_rpc_stream_limit() -> usize {
1871    hyprstream_rpc::transport::rpc_session::DEFAULT_STREAM_LIMIT
1872}
1873fn default_rpc_connection_limit() -> usize {
1874    hyprstream_rpc::transport::rpc_session::DEFAULT_CONNECTION_LIMIT
1875}
1876fn default_rpc_request_read_timeout_secs() -> u64 {
1877    hyprstream_rpc::transport::rpc_session::REQUEST_READ_TIMEOUT.as_secs()
1878}
1879fn default_rpc_handshake_timeout_secs() -> u64 {
1880    hyprstream_rpc::transport::rpc_session::HANDSHAKE_TIMEOUT.as_secs()
1881}
1882fn default_rpc_stopped_grace_secs() -> u64 {
1883    hyprstream_rpc::transport::rpc_session::STOPPED_GRACE.as_secs()
1884}
1885fn default_rpc_drain_timeout_secs() -> u64 {
1886    hyprstream_rpc::transport::rpc_session::DRAIN_TIMEOUT.as_secs()
1887}
1888
1889impl RpcServerConfig {
1890    /// Convert to the `hyprstream_rpc` wire type consumed by server builders.
1891    // TODO: wire into serve_bridged / QuinnRpcServer init paths (tracking issue #197)
1892    pub fn to_rpc_config(&self) -> hyprstream_rpc::transport::rpc_session::RpcConfig {
1893        use std::time::Duration;
1894        hyprstream_rpc::transport::rpc_session::RpcConfig {
1895            stream_limit: self.stream_limit,
1896            connection_limit: self.connection_limit,
1897            request_read_timeout: Duration::from_secs(self.request_read_timeout_secs),
1898            handshake_timeout: Duration::from_secs(self.handshake_timeout_secs),
1899            stopped_grace: Duration::from_secs(self.stopped_grace_secs),
1900            drain_timeout: Duration::from_secs(self.drain_timeout_secs),
1901        }
1902    }
1903}
1904
1905/// moq streaming plane configuration.
1906#[derive(Debug, Clone, Serialize, Deserialize)]
1907pub struct StreamingConfig {
1908    /// Deprecated ZMQ-era field — no longer used. Retained for config compat.
1909    #[serde(default = "default_max_pending_per_topic", skip_serializing)]
1910    pub max_pending_per_topic: usize,
1911
1912    /// Deprecated ZMQ-era field — no longer used. Retained for config compat.
1913    #[serde(default = "default_message_ttl_secs", skip_serializing)]
1914    pub message_ttl_secs: u64,
1915
1916    /// Deprecated ZMQ-era field — no longer used. Retained for config compat.
1917    #[serde(default = "default_compact_interval_secs", skip_serializing)]
1918    pub compact_interval_secs: u64,
1919
1920    /// StreamBlock batching configuration (rate control)
1921    ///
1922    /// Controls adaptive batching based on throughput rate.
1923    /// Higher rates → larger batches (reduced overhead).
1924    /// Lower rates → smaller batches (reduced latency).
1925    #[serde(flatten, default)]
1926    pub batching: hyprstream_rpc::streaming::BatchingConfig,
1927
1928    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
1929    #[serde(default)]
1930    pub quic_port: Option<u16>,
1931
1932    /// Timeout (seconds) waiting for the moq origin to announce a broadcast.
1933    /// Default: 10
1934    // TODO: wire into moq_stream.rs BROADCAST_ANNOUNCE_TIMEOUT constant (tracking issue #NNN)
1935    #[serde(default = "default_broadcast_announce_timeout_secs")]
1936    pub broadcast_announce_timeout_secs: u64,
1937
1938    /// Timeout (seconds) between consecutive moq Groups on a subscribed track.
1939    /// A subscriber that sees no new Group for this long treats the publisher as gone.
1940    /// Default: 30
1941    // TODO: wire into moq_stream.rs GROUP_IDLE_TIMEOUT constant (tracking issue #NNN)
1942    #[serde(default = "default_group_idle_timeout_secs")]
1943    pub group_idle_timeout_secs: u64,
1944
1945    /// Timeout (seconds) reading a single Frame from an already-opened moq Group.
1946    /// Default: 5
1947    // TODO: wire into moq_stream.rs FRAME_READ_TIMEOUT constant (tracking issue #NNN)
1948    #[serde(default = "default_frame_read_timeout_secs")]
1949    pub frame_read_timeout_secs: u64,
1950}
1951
1952impl Default for StreamingConfig {
1953    fn default() -> Self {
1954        Self {
1955            max_pending_per_topic: default_max_pending_per_topic(),
1956            message_ttl_secs: default_message_ttl_secs(),
1957            compact_interval_secs: default_compact_interval_secs(),
1958            batching: hyprstream_rpc::streaming::BatchingConfig::default(),
1959            quic_port: None,
1960            broadcast_announce_timeout_secs: default_broadcast_announce_timeout_secs(),
1961            group_idle_timeout_secs: default_group_idle_timeout_secs(),
1962            frame_read_timeout_secs: default_frame_read_timeout_secs(),
1963        }
1964    }
1965}
1966
1967fn default_max_pending_per_topic() -> usize {
1968    1000
1969}
1970fn default_message_ttl_secs() -> u64 {
1971    30
1972}
1973fn default_compact_interval_secs() -> u64 {
1974    5
1975}
1976fn default_broadcast_announce_timeout_secs() -> u64 {
1977    hyprstream_rpc::moq_stream::BROADCAST_ANNOUNCE_TIMEOUT.as_secs()
1978}
1979fn default_group_idle_timeout_secs() -> u64 {
1980    hyprstream_rpc::moq_stream::GROUP_IDLE_TIMEOUT.as_secs()
1981}
1982fn default_frame_read_timeout_secs() -> u64 {
1983    hyprstream_rpc::moq_stream::FRAME_READ_TIMEOUT.as_secs()
1984}
1985
1986/// Storage paths and directories configuration
1987#[derive(Debug, Clone, Serialize, Deserialize)]
1988pub struct StorageConfig {
1989    /// Models directory path
1990    pub models_dir: PathBuf,
1991    /// LoRAs directory path
1992    pub loras_dir: PathBuf,
1993    /// Cache directory path
1994    pub cache_dir: PathBuf,
1995    /// Config directory path
1996    pub config_dir: PathBuf,
1997}
1998
1999impl Default for StorageConfig {
2000    fn default() -> Self {
2001        // Try to get XDG-compliant paths, fall back to current directory
2002        let (models_dir, loras_dir, cache_dir, config_dir) = match StoragePaths::new() {
2003            Ok(storage_paths) => (
2004                storage_paths
2005                    .models_dir()
2006                    .unwrap_or_else(|_| PathBuf::from("./models")),
2007                storage_paths
2008                    .loras_dir()
2009                    .unwrap_or_else(|_| PathBuf::from("./loras")),
2010                storage_paths
2011                    .cache_dir()
2012                    .unwrap_or_else(|_| PathBuf::from("./cache")),
2013                storage_paths
2014                    .config_dir()
2015                    .unwrap_or_else(|_| PathBuf::from("./config")),
2016            ),
2017            Err(e) => {
2018                tracing::warn!("XDG paths unavailable: {}, using local directories", e);
2019                (
2020                    PathBuf::from("./models"),
2021                    PathBuf::from("./loras"),
2022                    PathBuf::from("./cache"),
2023                    PathBuf::from("./config"),
2024                )
2025            }
2026        };
2027
2028        Self {
2029            models_dir,
2030            loras_dir,
2031            cache_dir,
2032            config_dir,
2033        }
2034    }
2035}
2036
2037/// Event proxy service configuration.
2038#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2039pub struct EventServiceConfig {
2040    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
2041    #[serde(default)]
2042    pub quic_port: Option<u16>,
2043}
2044
2045/// Registry service configuration.
2046#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2047pub struct RegistryServiceConfig {
2048    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
2049    #[serde(default)]
2050    pub quic_port: Option<u16>,
2051    /// In-daemon at9p service-identity renewal. The registry is the sole
2052    /// record-store writer, so its process hosts the renewal timer.
2053    #[serde(default)]
2054    pub at9p_renewal: At9pRenewalConfig,
2055}
2056
2057/// Minimum accepted service-identity lifetime: shared by the offline
2058/// provisioner's `--valid-for-seconds` clamp and the in-daemon renewal TTL.
2059pub const MIN_SERVICE_IDENTITY_TTL_SECS: i64 = 600;
2060
2061/// Maximum accepted service-identity lifetime: 90 days. The at9p chain layer
2062/// has no maximum TTL of its own — this ceiling is provisioner-side policy.
2063/// 90 days satisfies the anchor-TTL ≥ 3× worst-case-deploy-gap policy for the
2064/// 30-day delegated-signer ceremony cadence, and the in-daemon renewal loop
2065/// (`services::at9p_renewal`) renews at the half-TTL point so a live daemon
2066/// never approaches it.
2067pub const MAX_SERVICE_IDENTITY_TTL_SECS: i64 = 7_776_000;
2068
2069/// In-daemon at9p service-identity renewal (`[registry.at9p_renewal]`).
2070///
2071/// The renewal timer reuses the boot provisioner's mint core against the
2072/// daemon's LIVE store/ingest handles: same DIDs forever, `epoch+1`
2073/// successors, same on-volume key, no-op inside the half-TTL window. The
2074/// deployment credential/UCAN is checked exactly once per process start —
2075/// never per tick — so a running daemon renews for its process lifetime;
2076/// restarts still gate on the deployment credential (unchanged).
2077#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2078pub struct At9pRenewalConfig {
2079    /// Check interval in seconds (default 6 h, the JWT key-rotation check
2080    /// cadence). Every tick renews due identities AND re-exports the roster
2081    /// projection, so `roster_stale` in host-side monitoring means the loop
2082    /// died, not merely that nothing was due.
2083    #[serde(default)]
2084    pub check_interval_secs: Option<u64>,
2085    /// TTL stamped onto minted successors, seconds. Defaults to 24 h —
2086    /// defensively inside the 86,400-second roster-lifetime bound that
2087    /// host-side native-config/monitor tooling still enforces, so an
2088    /// unset key can never mint a successor the deployed guard classifies
2089    /// as `invalid_roster`. A longer TTL (up to
2090    /// [`MAX_SERVICE_IDENTITY_TTL_SECS`], validated against the same range
2091    /// as the CLI clamp) is an explicit opt-in that must be paired with the
2092    /// host-side guard widening in the same rollout.
2093    ///
2094    /// Deployments provisioning identities with a longer boot-time
2095    /// `--valid-for-seconds` MUST set this key to match: the timer mints
2096    /// successors with the CONFIG TTL, so an unset key against 90-day
2097    /// boot-minted identities would contract the next renewal window to
2098    /// 24 h (still renewed, never expired — but the long margin is lost).
2099    #[serde(default)]
2100    pub valid_for_secs: Option<i64>,
2101    /// Roster.json re-export path. `None` derives
2102    /// `<data_dir>/config/native-network/roster.json` — the projection the
2103    /// host-side renewal monitor reads. The boot-time
2104    /// `--roster-export roster.candidate.json` flow is unaffected: this path
2105    /// is the promoted projection, refreshed every tick.
2106    #[serde(default)]
2107    pub roster_export: Option<std::path::PathBuf>,
2108}
2109
2110impl At9pRenewalConfig {
2111    /// Resolved check interval (default 6 h), floor-clamped to 60 s so a
2112    /// misconfigured near-zero interval cannot spin the loop.
2113    pub fn check_interval(&self) -> std::time::Duration {
2114        std::time::Duration::from_secs(self.check_interval_secs.unwrap_or(6 * 3600).max(60))
2115    }
2116
2117    /// Resolved renewal TTL, validated against the provisioner's clamp range.
2118    /// Defaults to 24 h (see the field docs for the defensive rationale).
2119    pub fn valid_for_seconds(&self) -> anyhow::Result<i64> {
2120        const DEFAULT_RENEWAL_TTL_SECS: i64 = 86_400;
2121        let ttl = self.valid_for_secs.unwrap_or(DEFAULT_RENEWAL_TTL_SECS);
2122        anyhow::ensure!(
2123            (MIN_SERVICE_IDENTITY_TTL_SECS..=MAX_SERVICE_IDENTITY_TTL_SECS).contains(&ttl),
2124            "[registry.at9p_renewal] valid_for_secs must be {}..{} seconds",
2125            MIN_SERVICE_IDENTITY_TTL_SECS,
2126            MAX_SERVICE_IDENTITY_TTL_SECS
2127        );
2128        Ok(ttl)
2129    }
2130
2131    /// Cross-validated (check interval, renewal TTL) pair: the check interval
2132    /// must stay strictly below half the TTL AND below the host-side roster
2133    /// freshness window (24 h). Liveness argument: an identity minted at T
2134    /// with TTL V becomes due at T + V/2; ticks fire every i, so the first
2135    /// due tick lands by T + V/2 + i with remaining life V/2 - i — positive
2136    /// only while i < V/2. At i ≥ V/2 a schedule exists where the head
2137    /// expires before any due tick, and an expired accepted head can never be
2138    /// renewed (admission requires a fresh predecessor). The roster freshness
2139    /// bound: the projection's `generated_at` refreshes only on a tick, and
2140    /// host-side monitoring flags `roster_stale` once it ages past 24 h, so
2141    /// an interval of a day or more would report a healthy loop as stale —
2142    /// breaking the documented "stale roster means the timer died" signal.
2143    /// Refuses at registry startup rather than renewing too slowly to matter.
2144    pub fn validated(&self) -> anyhow::Result<(std::time::Duration, i64)> {
2145        const ROSTER_FRESHNESS_WINDOW_SECS: u64 = 86_400;
2146        let ttl = self.valid_for_seconds()?;
2147        let interval = self.check_interval();
2148        let half_ttl = u64::try_from(ttl / 2).unwrap_or(0);
2149        anyhow::ensure!(
2150            interval.as_secs() < half_ttl,
2151            "[registry.at9p_renewal] check_interval_secs ({}) must be < half of \
2152             valid_for_secs ({}/2 = {}): a slower tick lets an identity pass its \
2153             half-TTL window and expire before renewal, and an expired head has \
2154             no authorized successor path",
2155            interval.as_secs(),
2156            ttl,
2157            half_ttl
2158        );
2159        anyhow::ensure!(
2160            interval.as_secs() < ROSTER_FRESHNESS_WINDOW_SECS,
2161            "[registry.at9p_renewal] check_interval_secs ({}) must be < {}: the roster \
2162             projection's generated_at refreshes only on a tick and host-side \
2163             monitoring flags roster_stale past 24 h, so a day-or-slower tick \
2164             would report a healthy timer as stale",
2165            interval.as_secs(),
2166            ROSTER_FRESHNESS_WINDOW_SECS
2167        );
2168        Ok((interval, ttl))
2169    }
2170}
2171
2172/// Policy service configuration.
2173#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2174pub struct PolicyServiceConfig {
2175    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
2176    #[serde(default)]
2177    pub quic_port: Option<u16>,
2178    /// Optional signed MAC boot artifacts. Supported for OS-owned deployments
2179    /// with a chain-enrolled Policy authority; invalid artifacts abort startup.
2180    #[serde(default)]
2181    pub boot_policy: Option<MacBootPolicyConfig>,
2182}
2183
2184/// Both independently provisioned artifacts and their expected policy pin are
2185/// mandatory when configured. Keep this generation/hash pin in the
2186/// OS-owned deployment configuration, outside the replaceable artifact
2187/// directory. Deploy a new pin and matching artifacts as one release; a
2188/// mismatch fails startup closed. Recovery restores the matching backed-up
2189/// config and artifacts. Lowering the pin is an explicit rollback decision.
2190/// Trust keys are never supplied by these files or this configuration.
2191#[derive(Debug, Clone, Serialize, Deserialize)]
2192#[serde(deny_unknown_fields)]
2193pub struct MacBootPolicyConfig {
2194    pub policy_path: PathBuf,
2195    pub approval_path: PathBuf,
2196    pub expected_generation: u64,
2197    /// Hex-encoded 32-byte compiled policy hash, independently pinned by the
2198    /// OS-owned deployment configuration.
2199    pub expected_policy_hash: String,
2200}
2201
2202/// Discovery service configuration.
2203#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2204pub struct DiscoveryServiceConfig {
2205    /// QUIC/WebTransport port. None = no QUIC, Some(0) = ephemeral, Some(N) = explicit.
2206    #[serde(default)]
2207    pub quic_port: Option<u16>,
2208    /// Volatile Discovery state. Memory is the single-process/WASM default;
2209    /// active-active deployments must select Valkey or tiered memory+Valkey.
2210    #[serde(default)]
2211    pub state: hyprstream_discovery::DiscoveryStateConfig,
2212}
2213
2214/// TUI display server configuration.
2215#[derive(Debug, Clone, Serialize, Deserialize)]
2216pub struct TuiServiceConfig {
2217    /// QUIC/WebTransport port for TUI viewers. None = no QUIC.
2218    #[serde(default)]
2219    pub quic_port: Option<u16>,
2220    /// Maximum concurrent sessions.
2221    #[serde(default = "default_tui_max_sessions")]
2222    pub max_sessions: u32,
2223    /// Scrollback lines per pane.
2224    #[serde(default = "default_tui_scrollback")]
2225    pub scrollback_lines: usize,
2226    /// WebTransport certificate validity in days (max 14).
2227    #[serde(default = "default_tui_wt_cert_days")]
2228    pub wt_cert_validity_days: u32,
2229}
2230
2231fn default_tui_max_sessions() -> u32 {
2232    16
2233}
2234fn default_tui_scrollback() -> usize {
2235    2000
2236}
2237fn default_tui_wt_cert_days() -> u32 {
2238    14
2239}
2240
2241impl Default for TuiServiceConfig {
2242    fn default() -> Self {
2243        Self {
2244            quic_port: None,
2245            max_sessions: default_tui_max_sessions(),
2246            scrollback_lines: default_tui_scrollback(),
2247            wt_cert_validity_days: default_tui_wt_cert_days(),
2248        }
2249    }
2250}
2251
2252/// Metrics service configuration (DuckDB-backed time-series ingest + DataFusion query).
2253#[derive(Debug, Clone, Serialize, Deserialize)]
2254pub struct MetricsConfig {
2255    /// DuckDB connection string. ":memory:" for in-process, or a file path.
2256    /// Use the same path as flight config to share data between services.
2257    #[serde(default = "default_metrics_db")]
2258    pub db_path: String,
2259
2260    /// Background checkpoint interval in seconds. 0 = disabled.
2261    #[serde(default = "default_checkpoint_interval_secs")]
2262    pub checkpoint_interval_secs: u64,
2263
2264    /// QUIC/WebTransport port. None = no QUIC.
2265    #[serde(default)]
2266    pub quic_port: Option<u16>,
2267}
2268
2269fn default_metrics_db() -> String {
2270    ":memory:".to_owned()
2271}
2272
2273fn default_checkpoint_interval_secs() -> u64 {
2274    300
2275}
2276
2277impl Default for MetricsConfig {
2278    fn default() -> Self {
2279        Self {
2280            db_path: default_metrics_db(),
2281            checkpoint_interval_secs: default_checkpoint_interval_secs(),
2282            quic_port: None,
2283        }
2284    }
2285}
2286
2287/// Service management configuration
2288///
2289/// Controls which services are started at startup in ipc-systemd mode.
2290#[derive(Debug, Clone, Serialize, Deserialize)]
2291pub struct ServicesConfig {
2292    /// Services to start automatically at startup (ipc-systemd mode)
2293    ///
2294    /// Default: the factories compiled into the standard service roster.
2295    #[serde(default = "default_startup_services")]
2296    pub startup: Vec<String>,
2297}
2298
2299impl Default for ServicesConfig {
2300    fn default() -> Self {
2301        Self {
2302            startup: default_startup_services(),
2303        }
2304    }
2305}
2306
2307/// Default list of services to start at startup
2308fn default_startup_services() -> Vec<String> {
2309    let mut services = vec![
2310        "event".to_owned(),    // Must start first (message bus)
2311        "registry".to_owned(), // Model registry
2312        "policy".to_owned(),   // Authorization
2313        "streams".to_owned(),  // Streaming proxy with JWT validation
2314        "worker".to_owned(),   // Container workloads
2315        "model".to_owned(),    // Model management
2316        "oauth".to_owned(),    // OAuth 2.1 authorization server
2317        "oai".to_owned(),      // OpenAI-compatible HTTP API
2318    ];
2319    #[cfg(feature = "metrics")]
2320    {
2321        services.push("flight".to_owned()); // Arrow Flight SQL server
2322    }
2323    services.extend([
2324        "discovery".to_owned(), // Endpoint discovery (RFC 9728 metadata)
2325        "mcp".to_owned(),       // Model Context Protocol service
2326        "tui".to_owned(),       // Terminal multiplexer display server
2327    ]);
2328    #[cfg(feature = "metrics")]
2329    {
2330        services.push("metrics".to_owned()); // Metrics ingest and query
2331    }
2332    services
2333}
2334
2335/// Configuration for one deployable, CPU-only inference process.
2336///
2337/// The service is opt-in: an empty `model_path` is the unconfigured default.
2338/// Metal runs two separate processes with distinct `replica` values and
2339/// resource limits, keeping libtorch and KV-cache fault domains isolated.
2340#[derive(Debug, Clone, Serialize, Deserialize)]
2341pub struct InferenceServerConfig {
2342    /// Materialized model directory loaded before the service becomes ready.
2343    #[serde(default)]
2344    pub model_path: PathBuf,
2345    /// Authority-facing model reference used for logs and deployment identity.
2346    #[serde(default)]
2347    pub model_ref: String,
2348    /// Authenticated immutable Git object ID for the materialized model.
2349    #[serde(default)]
2350    pub model_oid: String,
2351    /// Verified tenant to which this process is exclusively bound.
2352    #[serde(default)]
2353    pub tenant: String,
2354    /// Replica ordinal. Metal deploys ordinals 0 and 1.
2355    #[serde(default)]
2356    pub replica: u16,
2357    /// Inclusive transformer layer start. Partial ranges remain blocked on #314.
2358    #[serde(default)]
2359    pub stage_start: u32,
2360    /// Exclusive transformer layer end. `None` means the complete model.
2361    #[serde(default)]
2362    pub stage_end: Option<u32>,
2363    /// Browser-addressable QUIC/WebTransport port.
2364    #[serde(default)]
2365    pub quic_port: Option<u16>,
2366    /// Routable address placed in signed `StreamInfo.announcedAt`.
2367    #[serde(default)]
2368    pub advertise_addr: Option<std::net::SocketAddr>,
2369}
2370
2371impl Default for InferenceServerConfig {
2372    fn default() -> Self {
2373        Self {
2374            model_path: PathBuf::new(),
2375            model_ref: String::new(),
2376            model_oid: String::new(),
2377            tenant: String::new(),
2378            replica: 0,
2379            stage_start: 0,
2380            stage_end: None,
2381            quic_port: None,
2382            advertise_addr: None,
2383        }
2384    }
2385}
2386
2387impl InferenceServerConfig {
2388    /// Validate the deployable CPU service contract without loading weights.
2389    pub fn validate(&self) -> anyhow::Result<()> {
2390        anyhow::ensure!(
2391            !self.model_path.as_os_str().is_empty(),
2392            "inference.model_path is required"
2393        );
2394        anyhow::ensure!(
2395            self.model_path.is_absolute(),
2396            "inference.model_path must be absolute"
2397        );
2398        anyhow::ensure!(
2399            self.model_path.is_dir(),
2400            "inference.model_path is not a directory: {}",
2401            self.model_path.display()
2402        );
2403        anyhow::ensure!(
2404            !self.model_ref.trim().is_empty(),
2405            "inference.model_ref is required"
2406        );
2407        anyhow::ensure!(
2408            !self.tenant.trim().is_empty(),
2409            "inference.tenant is required"
2410        );
2411        let advertise_addr = self.advertise_addr.ok_or_else(|| {
2412            anyhow::anyhow!(
2413                "inference.advertise_addr is required for network-addressable browser MoQ"
2414            )
2415        })?;
2416        anyhow::ensure!(
2417            !advertise_addr.ip().is_unspecified()
2418                && !advertise_addr.ip().is_loopback()
2419                && advertise_addr.port() != 0,
2420            "inference.advertise_addr must be a non-loopback routable IP and non-zero port"
2421        );
2422        let quic_port = self.quic_port.ok_or_else(|| {
2423            anyhow::anyhow!(
2424                "inference.quic_port is required and must match inference.advertise_addr"
2425            )
2426        })?;
2427        anyhow::ensure!(
2428            quic_port != 0 && quic_port == advertise_addr.port(),
2429            "inference.quic_port must be non-zero and match inference.advertise_addr port"
2430        );
2431        anyhow::ensure!(
2432            matches!(self.model_oid.len(), 40 | 64)
2433                && self.model_oid.bytes().all(|b| b.is_ascii_hexdigit()),
2434            "inference.model_oid must be a 40- or 64-character hexadecimal object ID"
2435        );
2436        anyhow::ensure!(
2437            self.stage_start == 0 && self.stage_end.is_none(),
2438            "partial inference stage ranges require the #314 subset loader; configure the complete range as stage_start=0 and omit stage_end"
2439        );
2440        Ok(())
2441    }
2442
2443    /// Verify that the configured path is inside the checkout at `model_oid`.
2444    ///
2445    /// A deployment may not pair an arbitrary directory with a claimed OID:
2446    /// the immutable Git identity is checked before any weights are loaded.
2447    pub fn verify_materialized_oid(&self) -> anyhow::Result<()> {
2448        let model_path = self.model_path.canonicalize()?;
2449        let repository = git2::Repository::discover(&model_path).map_err(|error| {
2450            anyhow::anyhow!("inference.model_path is not in a Git checkout: {error}")
2451        })?;
2452        let checkout = repository
2453            .workdir()
2454            .ok_or_else(|| anyhow::anyhow!("inference model repository is bare"))?
2455            .canonicalize()?;
2456        anyhow::ensure!(
2457            model_path.starts_with(&checkout),
2458            "inference.model_path escapes its discovered checkout"
2459        );
2460        let actual = repository
2461            .head()?
2462            .target()
2463            .ok_or_else(|| anyhow::anyhow!("inference model checkout has no direct HEAD OID"))?
2464            .to_string();
2465        anyhow::ensure!(
2466            actual.eq_ignore_ascii_case(&self.model_oid),
2467            "inference model OID mismatch: configured {}, materialized {}",
2468            self.model_oid,
2469            actual
2470        );
2471
2472        let model_relative = model_path
2473            .strip_prefix(&checkout)
2474            .map_err(|_| anyhow::anyhow!("inference model path is outside its checkout"))?;
2475        let mut options = git2::StatusOptions::new();
2476        options
2477            .include_untracked(true)
2478            .recurse_untracked_dirs(true)
2479            // Ignored bytes under the model subtree are still mutable model
2480            // inputs and must not inherit the checkout's authenticated OID.
2481            .include_ignored(true)
2482            .include_unmodified(false);
2483        for entry in repository.statuses(Some(&mut options))?.iter() {
2484            let Some(path) = entry.path() else {
2485                anyhow::bail!("inference model checkout contains a non-UTF-8 changed path");
2486            };
2487            if std::path::Path::new(path).starts_with(model_relative) {
2488                anyhow::bail!(
2489                    "inference model checkout is not immutable at {}: {path} has status {:?}",
2490                    self.model_oid,
2491                    entry.status()
2492                );
2493            }
2494        }
2495        Ok(())
2496    }
2497
2498    /// Stable deployment identity for logs and capacity reporting.
2499    pub fn instance_name(&self) -> String {
2500        format!("inference-cpu-{}", self.replica)
2501    }
2502}
2503
2504/// Application-level LoRA settings (TOML config: enabled, max_adapters, etc.)
2505///
2506/// This is distinct from `TenantDeltaConfig` which configures LoRA weight parameters.
2507#[derive(Debug, Clone, Serialize, Deserialize)]
2508pub struct LoraAppConfig {
2509    /// Enable LoRA adapters
2510    pub enabled: bool,
2511    /// Maximum number of active adapters
2512    pub max_adapters: usize,
2513    /// LoRA scaling factor (alpha)
2514    pub alpha: f32,
2515    /// Target sparsity ratio (0.0-1.0)
2516    pub sparsity: f32,
2517}
2518
2519impl Default for LoraAppConfig {
2520    fn default() -> Self {
2521        Self {
2522            enabled: true,
2523            max_adapters: 4,
2524            alpha: 32.0,
2525            sparsity: 0.99,
2526        }
2527    }
2528}
2529
2530/// Builder for Hyprstream configuration
2531pub struct HyprConfigBuilder {
2532    server_builder: ServerConfigBuilder,
2533    model: ModelConfig,
2534    inference: InferenceServerConfig,
2535    runtime: RuntimeConfig,
2536    generation: GenerationConfig,
2537    lora: LoraAppConfig,
2538    storage: StorageConfig,
2539    git2db: git2db::config::Git2DBConfig,
2540    worker: Option<hyprstream_workers::config::WorkerConfig>,
2541    services: ServicesConfig,
2542    token: TokenConfig,
2543    oai: OAIConfig,
2544    flight: FlightConfig,
2545    mcp: MCPConfig,
2546    oauth: OAuthConfig,
2547    streaming: StreamingConfig,
2548    tls: TlsConfig,
2549    quic: QuicConfig,
2550    event: EventServiceConfig,
2551    registry: RegistryServiceConfig,
2552    policy: PolicyServiceConfig,
2553    discovery: DiscoveryServiceConfig,
2554    tui: TuiServiceConfig,
2555    metrics: MetricsConfig,
2556    cluster_at9p_did: Option<String>,
2557    cluster_did_web: Option<String>,
2558    cluster_anchor_root_cert: Option<PathBuf>,
2559    cluster_remote_node: bool,
2560    account: crate::account::AccountZoneConfig,
2561}
2562
2563impl HyprConfigBuilder {
2564    /// Create a new builder with default values
2565    pub fn new() -> Self {
2566        Self {
2567            server_builder: ServerConfigBuilder::new(),
2568            model: ModelConfig::default(),
2569            inference: InferenceServerConfig::default(),
2570            runtime: RuntimeConfig::default(),
2571            generation: GenerationConfig::default(),
2572            lora: LoraAppConfig::default(),
2573            storage: StorageConfig::default(),
2574            git2db: git2db::config::Git2DBConfig::default(),
2575            worker: None,
2576            services: ServicesConfig::default(),
2577            token: TokenConfig::default(),
2578            oai: OAIConfig::default(),
2579            flight: FlightConfig::default(),
2580            mcp: MCPConfig::default(),
2581            oauth: OAuthConfig::default(),
2582            streaming: StreamingConfig::default(),
2583            tls: TlsConfig::default(),
2584            quic: QuicConfig::default(),
2585            event: EventServiceConfig::default(),
2586            registry: RegistryServiceConfig::default(),
2587            policy: PolicyServiceConfig::default(),
2588            discovery: DiscoveryServiceConfig::default(),
2589            tui: TuiServiceConfig::default(),
2590            metrics: MetricsConfig::default(),
2591            cluster_at9p_did: None,
2592            cluster_did_web: None,
2593            cluster_anchor_root_cert: None,
2594            cluster_remote_node: false,
2595            account: Default::default(),
2596        }
2597    }
2598
2599    /// Start from an existing config
2600    pub fn from_config(config: HyprConfig) -> Self {
2601        Self {
2602            server_builder: config.server.to_builder(),
2603            model: config.model,
2604            inference: config.inference,
2605            runtime: config.runtime,
2606            generation: config.generation,
2607            lora: config.lora,
2608            storage: config.storage,
2609            git2db: config.git2db,
2610            worker: config.worker,
2611            services: config.services,
2612            token: config.token,
2613            oai: config.oai,
2614            flight: config.flight,
2615            mcp: config.mcp,
2616            oauth: config.oauth,
2617            streaming: config.streaming,
2618            tls: config.tls,
2619            quic: config.quic,
2620            event: config.event,
2621            registry: config.registry,
2622            policy: config.policy,
2623            discovery: config.discovery,
2624            tui: config.tui,
2625            metrics: config.metrics,
2626            cluster_at9p_did: config.cluster_at9p_did,
2627            cluster_did_web: config.cluster_did_web,
2628            cluster_anchor_root_cert: config.cluster_anchor_root_cert,
2629            cluster_remote_node: config.cluster_remote_node,
2630            account: config.account,
2631        }
2632    }
2633
2634    /// Access server builder for chaining
2635    pub fn server(mut self, f: impl FnOnce(ServerConfigBuilder) -> ServerConfigBuilder) -> Self {
2636        self.server_builder = f(self.server_builder);
2637        self
2638    }
2639
2640    /// Load all configurations from environment variables
2641    pub fn from_env(mut self) -> Self {
2642        self.server_builder = self.server_builder.from_env();
2643        self
2644    }
2645
2646    /// Build the final configuration
2647    pub fn build(self) -> HyprConfig {
2648        HyprConfig {
2649            server: self.server_builder.build(),
2650            model: self.model,
2651            inference: self.inference,
2652            runtime: self.runtime,
2653            generation: self.generation,
2654            lora: self.lora,
2655            storage: self.storage,
2656            git2db: self.git2db,
2657            worker: self.worker,
2658            services: self.services,
2659            token: self.token,
2660            oai: self.oai,
2661            xet: Default::default(),
2662            flight: self.flight,
2663            mcp: self.mcp,
2664            oauth: self.oauth,
2665            credentials: Default::default(),
2666            streaming: self.streaming,
2667            rpc: Default::default(),
2668            tls: self.tls,
2669            quic: self.quic,
2670            event: self.event,
2671            registry: self.registry,
2672            policy: self.policy,
2673            discovery: self.discovery,
2674            tui: self.tui,
2675            metrics: self.metrics,
2676            signing_key: None,
2677            secrets: Default::default(),
2678            cluster_at9p_did: self.cluster_at9p_did,
2679            cluster_did_web: self.cluster_did_web,
2680            cluster_anchor_root_cert: self.cluster_anchor_root_cert,
2681            cluster_remote_node: self.cluster_remote_node,
2682            account: self.account,
2683            #[cfg(feature = "ledger")]
2684            ledger: Default::default(),
2685            rds: Default::default(),
2686            #[cfg(feature = "postgres-ledger")]
2687            ledger_postgres_url: None,
2688            #[cfg(feature = "postgres-ledger")]
2689            ledger_postgres_pool_size: None,
2690        }
2691    }
2692
2693    /// Set the worker service configuration
2694    pub fn worker(mut self, config: hyprstream_workers::config::WorkerConfig) -> Self {
2695        self.worker = Some(config);
2696        self
2697    }
2698}
2699
2700impl Default for HyprConfigBuilder {
2701    fn default() -> Self {
2702        Self::new()
2703    }
2704}
2705
2706impl HyprConfig {
2707    /// Create a builder for the application configuration
2708    pub fn builder() -> HyprConfigBuilder {
2709        HyprConfigBuilder::new()
2710    }
2711
2712    // Keep list parsing restricted to fields that are actually lists. In particular,
2713    // issuer URLs and other scalar strings must retain their existing parsing.
2714    fn environment_source() -> Environment {
2715        Environment::with_prefix("HYPRSTREAM")
2716            .separator("__")
2717            .try_parsing(true)
2718            .list_separator(",")
2719            .with_list_parse_key("oauth.cors.allowed_origins")
2720    }
2721
2722    /// Load configuration using the config crate with XDG directories and environment variables
2723    ///
2724    /// When binary startup pinned a validated snapshot ([`install_pinned_config`]),
2725    /// that snapshot IS the process configuration: the XDG/env re-derivation is
2726    /// skipped so factory and service-module reloads can never diverge from the
2727    /// `--config` file main already loaded and validated.
2728    pub fn load() -> Result<Self, ConfigError> {
2729        if let Some(pinned) = PINNED_CONFIG.get() {
2730            return Ok(pinned.clone());
2731        }
2732        let storage = StoragePaths::new().map_err(|e| {
2733            ConfigError::Message(format!("Failed to initialize storage paths: {e}"))
2734        })?;
2735
2736        let config_dir = storage
2737            .config_dir()
2738            .map_err(|e| ConfigError::Message(format!("Failed to get config directory: {e}")))?;
2739
2740        let settings = Config::builder()
2741            // Load from default configuration structure
2742            .add_source(Config::try_from(&HyprConfig::default())?)
2743            // Load from config file if it exists
2744            .add_source(File::from(config_dir.join("config")).required(false))
2745            .add_source(File::from(config_dir.join("config.toml")).required(false))
2746            .add_source(File::from(config_dir.join("config.json")).required(false))
2747            .add_source(File::from(config_dir.join("config.yaml")).required(false))
2748            // Load from environment variables with HYPRSTREAM__ prefix (double underscore for nesting)
2749            .add_source(Self::environment_source());
2750
2751        // Build and deserialize configuration
2752        let mut hypr_config: HyprConfig = settings.build()?.try_deserialize()?;
2753
2754        // Load git2db config from environment/file (it has its own env handling)
2755        // This ensures GIT2DB__* environment variables are properly loaded
2756        match git2db::config::Git2DBConfig::load() {
2757            Ok(git2db_config) => {
2758                tracing::info!(
2759                    "Loaded git2db config, token present: {}",
2760                    git2db_config.network.access_token.is_some()
2761                );
2762                hypr_config.git2db = git2db_config;
2763            }
2764            Err(e) => {
2765                tracing::warn!("Failed to load git2db config: {}, using default", e);
2766                hypr_config.git2db = git2db::config::Git2DBConfig::default();
2767            }
2768        }
2769
2770        Ok(hypr_config)
2771    }
2772
2773    /// Load configuration from file
2774    pub fn from_file(path: &Path) -> anyhow::Result<Self> {
2775        let contents = std::fs::read_to_string(path)?;
2776        let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("toml");
2777
2778        let config = match extension {
2779            "json" => serde_json::from_str(&contents)?,
2780            "yaml" | "yml" => serde_yaml::from_str(&contents)?,
2781            _ => toml::from_str(&contents)?,
2782        };
2783
2784        Ok(config)
2785    }
2786
2787    /// Save configuration to file
2788    pub fn to_file(&self, path: &Path) -> anyhow::Result<()> {
2789        let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("toml");
2790
2791        let contents = match extension {
2792            "json" => serde_json::to_string_pretty(self)?,
2793            "yaml" | "yml" => serde_yaml::to_string(self)?,
2794            _ => toml::to_string_pretty(self)?,
2795        };
2796
2797        std::fs::write(path, contents)?;
2798        Ok(())
2799    }
2800
2801    /// Validate the entire configuration
2802    pub fn validate(&self) -> anyhow::Result<()> {
2803        // #1652: name-keyed native admission policy must reference real
2804        // factory services. Checked before anything else so a stale
2805        // DID-valued event publisher list fails at startup, not as silent
2806        // read-only ingress.
2807        self.quic.validate_admission_policy()?;
2808
2809        // Ledger production mode (PAY-01): turns the deliberately-inert
2810        // development defaults into startup failures, so a production node
2811        // cannot come up with credit enforcement silently disabled or with a
2812        // volatile accounting backend.
2813        //
2814        // Both the ledger config and its DSN are feature-gated, and they are
2815        // gated independently: a build with `ledger` but not `postgres-ledger`
2816        // has nowhere to configure a durable backend, so it reports no DSN and
2817        // production validation fails — which is the correct answer, since such
2818        // a build cannot serve a durable ledger at all.
2819        #[cfg(feature = "ledger")]
2820        {
2821            #[cfg(feature = "postgres-ledger")]
2822            let postgres_url = self.ledger_postgres_url.as_deref();
2823            #[cfg(not(feature = "postgres-ledger"))]
2824            let postgres_url: Option<&str> = None;
2825            self.ledger.validate_for_production(postgres_url)?;
2826        }
2827
2828        // Validate model config
2829        if !self.model.path.as_os_str().is_empty() && !self.model.path.exists() {
2830            anyhow::bail!(
2831                "Configured model path does not exist: {}",
2832                self.model.path.display()
2833            );
2834        }
2835
2836        let mut disabled_did_web_providers: Vec<&str> = self
2837            .oauth
2838            .oidc_providers
2839            .iter()
2840            .filter_map(|(name, provider)| {
2841                matches!(&provider.user_mapping, UserMappingStrategy::DidWeb)
2842                    .then_some(name.as_str())
2843            })
2844            .collect();
2845        disabled_did_web_providers.sort_unstable();
2846        if !disabled_did_web_providers.is_empty() {
2847            anyhow::bail!(
2848                "OIDC provider(s) {} configure disabled user_mapping = \"didweb\"; path-form did:web account minting is forbidden (#1159)",
2849                disabled_did_web_providers.join(", ")
2850            );
2851        }
2852
2853        let mut federate_owner_dids = std::collections::HashSet::new();
2854        let mut federate_owner_usernames = std::collections::HashSet::new();
2855        for (name, provider) in &self.oauth.oidc_providers {
2856            if provider.issuer_url.as_deref() == Some("https://login.federate.to") {
2857                anyhow::ensure!(
2858                    provider.federate_atproto_owner.is_some(),
2859                    "OIDC provider {name:?} uses the Federate issuer without Federate owner enrollment"
2860                );
2861            }
2862            let Some(enrollment) = &provider.federate_atproto_owner else {
2863                continue;
2864            };
2865            anyhow::ensure!(
2866                matches!(&provider.kind, ProviderKind::Oidc),
2867                "OIDC provider {name:?} configures Federate owner enrollment but is not kind = \"oidc\""
2868            );
2869            anyhow::ensure!(
2870                provider.issuer_url.as_deref() == Some("https://login.federate.to"),
2871                "OIDC provider {name:?} Federate owner enrollment requires the pinned issuer https://login.federate.to"
2872            );
2873            anyhow::ensure!(
2874                matches!(&provider.provisioning, ProvisioningMode::Deny),
2875                "OIDC provider {name:?} Federate owner enrollment requires provisioning = \"deny\""
2876            );
2877            anyhow::ensure!(
2878                !provider.allow_http,
2879                "OIDC provider {name:?} Federate owner enrollment does not allow HTTP discovery"
2880            );
2881            anyhow::ensure!(
2882                provider
2883                    .effective_scopes()
2884                    .iter()
2885                    .any(|scope| scope == "federated:id"),
2886                "OIDC provider {name:?} Federate owner enrollment requires the federated:id scope"
2887            );
2888            anyhow::ensure!(
2889                federate_owner_dids.insert(enrollment.owner_did.as_str()),
2890                "Federate owner DID is configured for more than one OIDC provider"
2891            );
2892            if let Some(username) = enrollment.username.as_deref() {
2893                anyhow::ensure!(
2894                    !username.is_empty(),
2895                    "OIDC provider {name:?} Federate owner enrollment username must not be empty"
2896                );
2897                anyhow::ensure!(
2898                    federate_owner_usernames.insert(username),
2899                    "hosted username is configured for more than one Federate owner provider"
2900                );
2901            }
2902            let authority =
2903                hyprstream_pds::repo_authority::accept_repo_authority(&enrollment.owner_did)?;
2904            anyhow::ensure!(
2905                matches!(authority, hyprstream_pds::repo_authority::RepoAuthority::Web | hyprstream_pds::repo_authority::RepoAuthority::Plc),
2906                "OIDC provider {name:?} Federate owner enrollment supports only did:web and did:plc owner DIDs"
2907            );
2908        }
2909
2910        // #1136 DID-anchored trust: the two anchors are a PAIR, not two
2911        // independent settings. #905 §2/§6 is bidirectional-or-not-believed —
2912        // a did:web claim is credited only when the at9p side names it back —
2913        // so a one-sided anchor configuration can never establish trust. It
2914        // must be rejected here rather than loading cleanly and failing later
2915        // in `install_process_production_resolver()`: a config that parses and
2916        // then dies at resolver install is an outage discovered at startup
2917        // instead of at validation.
2918        match (&self.cluster_at9p_did, &self.cluster_did_web) {
2919            (Some(_), None) => anyhow::bail!(
2920                "cluster_at9p_did is set without cluster_did_web; the DID-anchored trust \
2921                 source requires BOTH anchors (#1136, #905 §2/§6 mutual aliasing)"
2922            ),
2923            (None, Some(_)) => anyhow::bail!(
2924                "cluster_did_web is set without cluster_at9p_did; the DID-anchored trust \
2925                 source requires BOTH anchors (#1136, #905 §2/§6 mutual aliasing)"
2926            ),
2927            // Both absent = anchors not configured, the OS-owned path applies.
2928            // Both present = the pairing the resolver expects.
2929            (None, None) | (Some(_), Some(_)) => {}
2930        }
2931
2932        Ok(())
2933    }
2934
2935    /// Get the models directory path
2936    pub fn models_dir(&self) -> &PathBuf {
2937        &self.storage.models_dir
2938    }
2939
2940    /// Get the LoRAs directory path
2941    pub fn loras_dir(&self) -> &PathBuf {
2942        &self.storage.loras_dir
2943    }
2944
2945    /// Get the cache directory path
2946    pub fn cache_dir(&self) -> &PathBuf {
2947        &self.storage.cache_dir
2948    }
2949
2950    /// Get the config directory path
2951    pub fn config_dir(&self) -> &PathBuf {
2952        &self.storage.config_dir
2953    }
2954
2955    /// Ensure all configured directories exist
2956    pub fn ensure_directories(&self) -> Result<(), std::io::Error> {
2957        std::fs::create_dir_all(&self.storage.models_dir)?;
2958        std::fs::create_dir_all(&self.storage.loras_dir)?;
2959        std::fs::create_dir_all(&self.storage.cache_dir)?;
2960        std::fs::create_dir_all(&self.storage.config_dir)?;
2961        Ok(())
2962    }
2963
2964    /// Update model configuration after downloading
2965    pub fn set_model(&mut self, model_path: PathBuf, model_name: String, architecture: String) {
2966        self.model.path = model_path;
2967        self.model.name = model_name;
2968        self.model.architecture = architecture;
2969    }
2970
2971    /// Create generation request from config + prompt
2972    /// Save configuration to default location
2973    pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
2974        let storage = StoragePaths::new()?;
2975        let config_dir = storage.config_dir()?;
2976        let config_path = config_dir.join("config.toml");
2977
2978        let contents = toml::to_string_pretty(self)?;
2979        std::fs::write(&config_path, contents)?;
2980
2981        tracing::info!("✅ Configuration saved to: {}", config_path.display());
2982        Ok(())
2983    }
2984
2985    // ── Secrets / key bypass helpers ────────────────────────────────────────
2986
2987    /// Resolve the secrets directory using the unified secret-material resolver.
2988    ///
2989    /// Precedence is:
2990    /// 1. `HYPRSTREAM__SECRETS__PATH`
2991    /// 2. explicit config, when provided via `resolve_secrets_dir_for`
2992    /// 3. loaded config file / env-derived config
2993    /// 4. XDG default (`<config_dir>/credentials`)
2994    ///
2995    /// Resolution is fail-closed: no `/etc` or `/tmp` fallback is chosen
2996    /// silently when XDG resolution fails.
2997    pub fn resolve_secrets_dir() -> anyhow::Result<PathBuf> {
2998        Self::resolve_secrets_dir_for(None)
2999    }
3000
3001    /// Resolve the secrets directory, optionally from an already-loaded config.
3002    ///
3003    /// The optional config handle lets CLI paths that already honored
3004    /// `--config <path>` stay on the same resolver family as daemon/service
3005    /// code instead of reloading default config locations.
3006    pub fn resolve_secrets_dir_for(config: Option<&HyprConfig>) -> anyhow::Result<PathBuf> {
3007        if let Ok(path) = std::env::var("HYPRSTREAM__SECRETS__PATH") {
3008            return Ok(PathBuf::from(path));
3009        }
3010        if let Some(config) = config {
3011            return Ok(config.secrets.resolve_dir(config.config_dir()));
3012        }
3013        if let Ok(config) = Self::load() {
3014            return Ok(config.secrets.resolve_dir(config.config_dir()));
3015        }
3016        SecretsConfig::default_dir()
3017    }
3018
3019    /// Check for the `HYPRSTREAM__SIGNING_KEY` test bypass.
3020    ///
3021    /// Returns `Ok(Some(key))` when the bypass is set and valid,
3022    /// `Ok(None)` when not configured, `Err` when malformed.
3023    pub fn node_signing_key_bypass() -> anyhow::Result<Option<ed25519_dalek::SigningKey>> {
3024        if let Ok(cfg) = Self::load() {
3025            if let Some(ref hex_key) = cfg.signing_key {
3026                let mut bytes = hex::decode(hex_key)
3027                    .map_err(|e| anyhow::anyhow!("HYPRSTREAM__SIGNING_KEY: invalid hex: {e}"))?;
3028                let mut arr: [u8; 32] = bytes
3029                    .as_slice()
3030                    .try_into()
3031                    .map_err(|_| anyhow::anyhow!("HYPRSTREAM__SIGNING_KEY: expected 32 bytes"))?;
3032                let sk = ed25519_dalek::SigningKey::from_bytes(&arr);
3033                bytes.zeroize();
3034                arr.zeroize();
3035                tracing::info!("Using node signing key from config (test bypass)");
3036                return Ok(Some(sk));
3037            }
3038        }
3039        Ok(None)
3040    }
3041
3042    /// Check for the `HYPRSTREAM__OAUTH__USER_SIGNING_KEY` test bypass.
3043    ///
3044    /// Returns `Ok(Some((sk, vk)))` when the bypass is set and valid,
3045    /// `Ok(None)` when not configured, `Err` when malformed.
3046    pub fn user_signing_key_bypass(
3047    ) -> anyhow::Result<Option<(ed25519_dalek::SigningKey, ed25519_dalek::VerifyingKey)>> {
3048        if let Ok(cfg) = Self::load() {
3049            if let Some(ref hex_key) = cfg.oauth.user_signing_key {
3050                let mut bytes = hex::decode(hex_key).map_err(|e| {
3051                    anyhow::anyhow!("HYPRSTREAM__OAUTH__USER_SIGNING_KEY: invalid hex: {e}")
3052                })?;
3053                let mut arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
3054                    anyhow::anyhow!("HYPRSTREAM__OAUTH__USER_SIGNING_KEY: expected 32 bytes")
3055                })?;
3056                let sk = ed25519_dalek::SigningKey::from_bytes(&arr);
3057                bytes.zeroize();
3058                arr.zeroize();
3059                let vk = sk.verifying_key();
3060                tracing::info!("Using user signing key from config (test bypass)");
3061                return Ok(Some((sk, vk)));
3062            }
3063        }
3064        Ok(None)
3065    }
3066
3067    /// Create a default configuration for a specific model path
3068    pub fn default_for_model(model_path: &Path) -> anyhow::Result<Self> {
3069        let storage_paths = StoragePaths::new()?;
3070        let mut config = Self::default();
3071
3072        config.model.path = model_path.to_path_buf();
3073        config.model.name = model_path
3074            .file_stem()
3075            .and_then(|s| s.to_str())
3076            .unwrap_or("unknown")
3077            .to_owned();
3078        config.model.architecture = "auto".to_owned(); // Auto-detect from model
3079
3080        // Update storage paths to use XDG directories
3081        config.storage = StorageConfig {
3082            models_dir: storage_paths.models_dir()?,
3083            loras_dir: storage_paths.loras_dir()?,
3084            cache_dir: storage_paths.cache_dir()?,
3085            config_dir: storage_paths.config_dir()?,
3086        };
3087
3088        Ok(config)
3089    }
3090}
3091
3092/// A prompt string that has been processed through the chat template engine.
3093/// This newtype prevents accidentally passing untemplated strings to generation.
3094#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
3095#[serde(transparent)]
3096pub struct TemplatedPrompt(String);
3097
3098impl TemplatedPrompt {
3099    /// Create from a templated string. Only call after template application.
3100    pub fn new(s: String) -> Self {
3101        Self(s)
3102    }
3103
3104    /// Get the prompt as a string slice.
3105    pub fn as_str(&self) -> &str {
3106        &self.0
3107    }
3108
3109    /// Consume and return the inner string.
3110    pub fn into_inner(self) -> String {
3111        self.0
3112    }
3113
3114    /// Get the length of the prompt in bytes.
3115    pub fn len(&self) -> usize {
3116        self.0.len()
3117    }
3118
3119    /// Check if the prompt is empty.
3120    pub fn is_empty(&self) -> bool {
3121        self.0.is_empty()
3122    }
3123}
3124
3125impl std::fmt::Display for TemplatedPrompt {
3126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3127        write!(f, "{}", self.0)
3128    }
3129}
3130
3131/// Unified sampling parameters with Option fields for clean precedence merging.
3132///
3133/// All fields are Option<T> to represent "not specified", enabling clear
3134/// precedence: Server defaults → Model defaults → User overrides
3135#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3136pub struct SamplingParams {
3137    pub max_tokens: Option<usize>,
3138    pub temperature: Option<f32>,
3139    pub top_p: Option<f32>,
3140    pub top_k: Option<usize>,
3141    pub repeat_penalty: Option<f32>,
3142    pub repeat_last_n: Option<usize>,
3143    pub stop_tokens: Option<Vec<String>>,
3144    pub seed: Option<u64>,
3145
3146    // Advanced parameters (HuggingFace transformers compatibility)
3147    #[serde(default)]
3148    pub length_penalty: Option<f32>,
3149    #[serde(default)]
3150    pub typical_p: Option<f32>,
3151    #[serde(default)]
3152    pub epsilon_cutoff: Option<f32>,
3153    #[serde(default)]
3154    pub eta_cutoff: Option<f32>,
3155    #[serde(default)]
3156    pub do_sample: Option<bool>,
3157
3158    // NEW: Async parameters
3159    #[serde(default)]
3160    pub timeout_ms: Option<u64>,
3161}
3162
3163impl SamplingParams {
3164    /// Load model-specific config from a model directory
3165    pub async fn from_model_path(
3166        model_path: &std::path::Path,
3167    ) -> Result<Self, Box<dyn std::error::Error>> {
3168        let gen_config_path = model_path.join("generation_config.json");
3169        if gen_config_path.exists() {
3170            let content = tokio::fs::read_to_string(&gen_config_path).await?;
3171            let config: serde_json::Value = serde_json::from_str(&content)?;
3172            return Ok(Self::from_generation_config(&config));
3173        }
3174
3175        let config_path = model_path.join("config.json");
3176        if config_path.exists() {
3177            let content = tokio::fs::read_to_string(&config_path).await?;
3178            let config: serde_json::Value = serde_json::from_str(&content)?;
3179            if let Some(gen_config) = config.get("generation_config") {
3180                return Ok(Self::from_generation_config(gen_config));
3181            }
3182        }
3183
3184        Ok(Self::default())
3185    }
3186
3187    /// Parse HuggingFace generation_config.json format
3188    fn from_generation_config(config: &serde_json::Value) -> Self {
3189        Self {
3190            temperature: config
3191                .get("temperature")
3192                .and_then(serde_json::Value::as_f64)
3193                .map(|v| v as f32),
3194            top_k: config
3195                .get("top_k")
3196                .and_then(serde_json::Value::as_u64)
3197                .map(|v| v as usize),
3198            top_p: config
3199                .get("top_p")
3200                .and_then(serde_json::Value::as_f64)
3201                .map(|v| v as f32),
3202            repeat_penalty: config
3203                .get("repetition_penalty")
3204                .and_then(serde_json::Value::as_f64)
3205                .map(|v| v as f32),
3206            max_tokens: config
3207                .get("max_new_tokens")
3208                .and_then(serde_json::Value::as_u64)
3209                .map(|v| v as usize)
3210                .or_else(|| {
3211                    config
3212                        .get("max_length")
3213                        .and_then(serde_json::Value::as_u64)
3214                        .map(|v| v as usize)
3215                }),
3216            length_penalty: config
3217                .get("length_penalty")
3218                .and_then(serde_json::Value::as_f64)
3219                .map(|v| v as f32),
3220            typical_p: config
3221                .get("typical_p")
3222                .and_then(serde_json::Value::as_f64)
3223                .map(|v| v as f32),
3224            epsilon_cutoff: config
3225                .get("epsilon_cutoff")
3226                .and_then(serde_json::Value::as_f64)
3227                .map(|v| v as f32),
3228            eta_cutoff: config
3229                .get("eta_cutoff")
3230                .and_then(serde_json::Value::as_f64)
3231                .map(|v| v as f32),
3232            do_sample: config.get("do_sample").and_then(serde_json::Value::as_bool),
3233            stop_tokens: config.get("eos_token_id").and_then(|v| {
3234                if let Some(arr) = v.as_array() {
3235                    let tokens: Vec<String> = arr
3236                        .iter()
3237                        .filter_map(|v| v.as_str().map(String::from))
3238                        .collect();
3239                    if tokens.is_empty() {
3240                        None
3241                    } else {
3242                        Some(tokens)
3243                    }
3244                } else {
3245                    None
3246                }
3247            }),
3248            seed: config.get("seed").and_then(serde_json::Value::as_u64),
3249            repeat_last_n: None,
3250            timeout_ms: None,
3251        }
3252    }
3253
3254    /// Merge with another config. The other config takes precedence for any Some values.
3255    /// This enables clear precedence: `base.merge(override)` where override wins.
3256    pub fn merge(self, other: Self) -> Self {
3257        Self {
3258            max_tokens: other.max_tokens.or(self.max_tokens),
3259            temperature: other.temperature.or(self.temperature),
3260            top_p: other.top_p.or(self.top_p),
3261            top_k: other.top_k.or(self.top_k),
3262            repeat_penalty: other.repeat_penalty.or(self.repeat_penalty),
3263            repeat_last_n: other.repeat_last_n.or(self.repeat_last_n),
3264            stop_tokens: other.stop_tokens.or(self.stop_tokens),
3265            seed: other.seed.or(self.seed),
3266            length_penalty: other.length_penalty.or(self.length_penalty),
3267            typical_p: other.typical_p.or(self.typical_p),
3268            epsilon_cutoff: other.epsilon_cutoff.or(self.epsilon_cutoff),
3269            eta_cutoff: other.eta_cutoff.or(self.eta_cutoff),
3270            do_sample: other.do_sample.or(self.do_sample),
3271            timeout_ms: other.timeout_ms.or(self.timeout_ms),
3272        }
3273    }
3274
3275    /// Build a `GenerationRequest` from these sampling params and a prompt.
3276    ///
3277    /// Applies `SamplingParams` fields as `Option<T>` — `None` means "not specified",
3278    /// letting the engine use its defaults.
3279    pub fn into_generation_request(
3280        self,
3281        prompt: String,
3282    ) -> hyprstream_rpc_std::inference_client::GenerationRequest {
3283        hyprstream_rpc_std::inference_client::GenerationRequest {
3284            prompt,
3285            max_tokens: self.max_tokens.map(|v| v as u32),
3286            temperature: self.temperature,
3287            top_p: self.top_p,
3288            top_k: self.top_k.map(|v| v as u32),
3289            repeat_penalty: self.repeat_penalty,
3290            repeat_last_n: self.repeat_last_n.map(|v| v as u32),
3291            stop_tokens: self.stop_tokens,
3292            seed: self.seed.map(|v| v as u32),
3293            timeout_ms: self.timeout_ms,
3294            ..Default::default()
3295        }
3296    }
3297
3298    /// Resolve to concrete values with defaults
3299    pub fn resolve(self) -> ResolvedSamplingParams {
3300        ResolvedSamplingParams {
3301            max_tokens: self.max_tokens.unwrap_or(2048),
3302            temperature: self.temperature.unwrap_or(0.7),
3303            top_p: self.top_p.unwrap_or(0.95),
3304            top_k: self.top_k,
3305            repeat_penalty: self.repeat_penalty.unwrap_or(1.0),
3306            repeat_last_n: self.repeat_last_n.unwrap_or(64),
3307            stop_tokens: self.stop_tokens.unwrap_or_default(),
3308            seed: self.seed,
3309            length_penalty: self.length_penalty.unwrap_or(1.0),
3310            typical_p: self.typical_p,
3311            epsilon_cutoff: self.epsilon_cutoff,
3312            eta_cutoff: self.eta_cutoff,
3313            do_sample: self.do_sample.unwrap_or(true),
3314            timeout_ms: self.timeout_ms.unwrap_or(120000), // Use RuntimeConfig default (2 minutes)
3315        }
3316    }
3317}
3318
3319/// Resolved sampling parameters with concrete values (no Options for required fields)
3320#[derive(Debug, Clone)]
3321pub struct ResolvedSamplingParams {
3322    pub max_tokens: usize,
3323    pub temperature: f32,
3324    pub top_p: f32,
3325    pub top_k: Option<usize>,
3326    pub repeat_penalty: f32,
3327    pub repeat_last_n: usize,
3328    pub stop_tokens: Vec<String>,
3329    pub seed: Option<u64>,
3330    pub length_penalty: f32,
3331    pub typical_p: Option<f32>,
3332    pub epsilon_cutoff: Option<f32>,
3333    pub eta_cutoff: Option<f32>,
3334    pub do_sample: bool,
3335    // NEW: Async parameters
3336    pub timeout_ms: u64,
3337}
3338
3339impl From<&crate::config::server::SamplingParamDefaults> for SamplingParams {
3340    fn from(defaults: &crate::config::server::SamplingParamDefaults) -> Self {
3341        Self {
3342            max_tokens: Some(defaults.max_tokens),
3343            temperature: Some(defaults.temperature),
3344            top_p: Some(defaults.top_p),
3345            repeat_penalty: Some(defaults.repeat_penalty),
3346            top_k: None,
3347            repeat_last_n: None,
3348            stop_tokens: None,
3349            seed: None,
3350            length_penalty: None,
3351            typical_p: None,
3352            epsilon_cutoff: None,
3353            eta_cutoff: None,
3354            do_sample: None,
3355            timeout_ms: None, // Don't set timeout here - let engine handle it
3356        }
3357    }
3358}
3359
3360#[cfg(test)]
3361mod tests {
3362    use super::*;
3363
3364    #[test]
3365    fn at9p_renewal_interval_must_outrun_half_ttl() {
3366        // Defaults: 6 h check vs 24 h TTL — inside every bound, and the
3367        // default TTL stays within the 86,400 s roster-lifetime bound that
3368        // deployed host-side guards still enforce (an unset key must never
3369        // mint a successor the guard classifies invalid_roster).
3370        let defaults = At9pRenewalConfig::default();
3371        let (interval, ttl) = match defaults.validated() {
3372            Ok(pair) => pair,
3373            Err(error) => panic!("defaults validate: {error}"),
3374        };
3375        assert_eq!(interval.as_secs(), 6 * 3600);
3376        assert_eq!(ttl, 86_400);
3377        // Minimum supported TTL (600 s → half = 300 s) with the default 6 h
3378        // interval lets an identity expire between due ticks: refuse.
3379        let slow = At9pRenewalConfig {
3380            valid_for_secs: Some(MIN_SERVICE_IDENTITY_TTL_SECS),
3381            ..Default::default()
3382        };
3383        let error = match slow.validated() {
3384            Ok(_) => panic!("6h check vs 10m TTL must be refused"),
3385            Err(error) => error,
3386        };
3387        assert!(
3388            error.to_string().contains("half of valid_for_secs"),
3389            "{error}"
3390        );
3391        // Interval at exactly half the TTL still leaves a schedule where the
3392        // head expires on the tick boundary: refuse strictly below only.
3393        let boundary = At9pRenewalConfig {
3394            valid_for_secs: Some(600),
3395            check_interval_secs: Some(300),
3396            ..Default::default()
3397        };
3398        assert!(boundary.validated().is_err());
3399        // One second inside the window renews with positive remaining life.
3400        let inside = At9pRenewalConfig {
3401            valid_for_secs: Some(600),
3402            check_interval_secs: Some(299),
3403            ..Default::default()
3404        };
3405        let (inside_interval, _) = match inside.validated() {
3406            Ok(pair) => pair,
3407            Err(error) => panic!("inside window: {error}"),
3408        };
3409        assert_eq!(inside_interval.as_secs(), 299);
3410        // A two-day interval satisfies the half-TTL bound against an
3411        // explicit 90 d TTL but starves the roster freshness signal: the
3412        // projection's generated_at refreshes only on a tick, and
3413        // host-side monitoring flags roster_stale past 24 h — refuse at or
3414        // above a day.
3415        let slow_but_renewable = At9pRenewalConfig {
3416            valid_for_secs: Some(MAX_SERVICE_IDENTITY_TTL_SECS),
3417            check_interval_secs: Some(2 * 86_400),
3418            ..Default::default()
3419        };
3420        let error = match slow_but_renewable.validated() {
3421            Ok(_) => panic!("two-day interval must be refused"),
3422            Err(error) => error,
3423        };
3424        assert!(error.to_string().contains("roster_stale"), "{error}");
3425        let day_boundary = At9pRenewalConfig {
3426            valid_for_secs: Some(MAX_SERVICE_IDENTITY_TTL_SECS),
3427            check_interval_secs: Some(86_400),
3428            ..Default::default()
3429        };
3430        assert!(day_boundary.validated().is_err());
3431        let just_under_a_day = At9pRenewalConfig {
3432            valid_for_secs: Some(MAX_SERVICE_IDENTITY_TTL_SECS),
3433            check_interval_secs: Some(86_399),
3434            ..Default::default()
3435        };
3436        assert!(just_under_a_day.validated().is_ok());
3437        // Out-of-range TTL is still refused by the clamp validation.
3438        let bad_ttl = At9pRenewalConfig {
3439            valid_for_secs: Some(MAX_SERVICE_IDENTITY_TTL_SECS + 1),
3440            ..Default::default()
3441        };
3442        assert!(bad_ttl.validated().is_err());
3443    }
3444
3445    #[test]
3446    fn default_startup_services_are_available_in_this_build() {
3447        let startup = super::default_startup_services();
3448        assert!(
3449            !startup.iter().any(|name| name == "notification"),
3450            "the removed notification service must not remain in the default roster"
3451        );
3452        for name in &startup {
3453            assert!(
3454                hyprstream_service::get_factory(name).is_some(),
3455                "default service {name} must have a factory in this build"
3456            );
3457        }
3458
3459        #[cfg(feature = "metrics")]
3460        {
3461            assert!(startup.iter().any(|name| name == "flight"));
3462            assert!(startup.iter().any(|name| name == "metrics"));
3463        }
3464        #[cfg(not(feature = "metrics"))]
3465        {
3466            assert!(!startup.iter().any(|name| name == "flight"));
3467            assert!(!startup.iter().any(|name| name == "metrics"));
3468        }
3469    }
3470
3471    #[tokio::test]
3472    async fn oauth_cors_origin_list_from_environment_preserves_scalars() -> anyhow::Result<()> {
3473        use axum::{
3474            body::Body,
3475            http::{header, Request},
3476            routing::get,
3477            Router,
3478        };
3479        use tower::ServiceExt;
3480
3481        for origins in [
3482            "https://staging-amp.hyprstream.com",
3483            "https://staging-amp.hyprstream.com,https://second.example",
3484            " https://staging-amp.hyprstream.com , https://second.example\t",
3485        ] {
3486            // Use a private source map, never mutate the test process environment.
3487            let source = [
3488                ("HYPRSTREAM__OAUTH__CORS__ALLOWED_ORIGINS", origins),
3489                ("HYPRSTREAM__OAUTH__CORS__ENABLED", "true"),
3490                ("HYPRSTREAM__OAUTH__CORS__ALLOW_CREDENTIALS", "true"),
3491                ("HYPRSTREAM__OAUTH__CORS__PERMISSIVE_HEADERS", "false"),
3492                (
3493                    "HYPRSTREAM__OAUTH__EXTERNAL_URL",
3494                    "https://discovery.staging.lab.hyprstream.com",
3495                ),
3496                ("HYPRSTREAM__OAUTH__JWT_KEY_ACTIVE_SECS", "30"),
3497            ]
3498            .into_iter()
3499            .map(|(key, value)| (key.to_owned(), value.to_owned()))
3500            .collect();
3501            let cfg: HyprConfig = config::Config::builder()
3502                .add_source(config::Config::try_from(&HyprConfig::default())?)
3503                .add_source(HyprConfig::environment_source().source(Some(source)))
3504                .build()?
3505                .try_deserialize()?;
3506            assert_eq!(
3507                cfg.oauth.cors.allowed_origins,
3508                origins.split(',').map(str::trim).collect::<Vec<_>>()
3509            );
3510            assert!(cfg.oauth.cors.enabled);
3511            assert!(cfg.oauth.cors.allow_credentials);
3512            assert!(!cfg.oauth.cors.permissive_headers);
3513            assert_eq!(
3514                cfg.oauth.external_url.as_deref(),
3515                Some("https://discovery.staging.lab.hyprstream.com")
3516            );
3517            assert_eq!(cfg.oauth.jwt_key_active_secs, Some(30));
3518
3519            let app = Router::new()
3520                .route("/probe", get(|| async { "ok" }))
3521                .layer(crate::server::middleware::cors_layer(&cfg.oauth.cors));
3522            for origin in cfg
3523                .oauth
3524                .cors
3525                .allowed_origins
3526                .iter()
3527                .map(String::as_str)
3528                .chain(["https://not-allowed.example"])
3529            {
3530                let response = app
3531                    .clone()
3532                    .oneshot(
3533                        Request::builder()
3534                            .uri("/probe")
3535                            .header(header::ORIGIN, origin)
3536                            .body(Body::empty())?,
3537                    )
3538                    .await?;
3539                let allowed = cfg
3540                    .oauth
3541                    .cors
3542                    .allowed_origins
3543                    .iter()
3544                    .any(|value| value == origin);
3545                assert_eq!(
3546                    response
3547                        .headers()
3548                        .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
3549                        .and_then(|value| value.to_str().ok()),
3550                    allowed.then_some(origin)
3551                );
3552                if allowed {
3553                    assert_eq!(
3554                        response
3555                            .headers()
3556                            .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
3557                            .and_then(|value| value.to_str().ok()),
3558                        Some("true")
3559                    );
3560                }
3561            }
3562        }
3563        Ok(())
3564    }
3565
3566    /// Build a `HyprConfig` from a private env-source map with the OAuth CORS
3567    /// list at `origins`, never mutating the test process environment.
3568    fn cors_cfg_from_env(origins: &str) -> anyhow::Result<HyprConfig> {
3569        let source = [
3570            ("HYPRSTREAM__OAUTH__CORS__ALLOWED_ORIGINS", origins),
3571            ("HYPRSTREAM__OAUTH__CORS__ENABLED", "true"),
3572            ("HYPRSTREAM__OAUTH__CORS__ALLOW_CREDENTIALS", "true"),
3573            ("HYPRSTREAM__OAUTH__CORS__PERMISSIVE_HEADERS", "false"),
3574            (
3575                "HYPRSTREAM__OAUTH__EXTERNAL_URL",
3576                "https://discovery.staging.lab.hyprstream.com",
3577            ),
3578            ("HYPRSTREAM__OAUTH__JWT_KEY_ACTIVE_SECS", "30"),
3579        ]
3580        .into_iter()
3581        .map(|(key, value)| (key.to_owned(), value.to_owned()))
3582        .collect();
3583        Ok(config::Config::builder()
3584            .add_source(config::Config::try_from(&HyprConfig::default())?)
3585            .add_source(HyprConfig::environment_source().source(Some(source)))
3586            .build()?
3587            .try_deserialize()?)
3588    }
3589
3590    /// Drive the real `cors_layer` middleware with an `Origin` request and
3591    /// return the `(access-control-allow-origin, access-control-allow-credentials)`
3592    /// header values it emits.
3593    async fn cors_probe(
3594        cfg: &HyprConfig,
3595        origin: &str,
3596    ) -> anyhow::Result<(Option<String>, Option<String>)> {
3597        use axum::{
3598            body::Body,
3599            http::{header, Request},
3600            routing::get,
3601            Router,
3602        };
3603        use tower::ServiceExt;
3604        let app = Router::new()
3605            .route("/probe", get(|| async { "ok" }))
3606            .layer(crate::server::middleware::cors_layer(&cfg.oauth.cors));
3607        let response = app
3608            .oneshot(
3609                Request::builder()
3610                    .uri("/probe")
3611                    .header(header::ORIGIN, origin)
3612                    .body(Body::empty())?,
3613            )
3614            .await?;
3615        let header_str = |name: header::HeaderName| {
3616            response
3617                .headers()
3618                .get(name)
3619                .and_then(|value| value.to_str().ok())
3620                .map(str::to_owned)
3621        };
3622        Ok((
3623            header_str(header::ACCESS_CONTROL_ALLOW_ORIGIN),
3624            header_str(header::ACCESS_CONTROL_ALLOW_CREDENTIALS),
3625        ))
3626    }
3627
3628    #[tokio::test]
3629    async fn oauth_cors_env_empty_whitespace_or_separator_only_falls_back_to_localhost(
3630    ) -> anyhow::Result<()> {
3631        // An empty, whitespace-only, or separators-only value must trim+filter
3632        // to an empty vector so the middleware's localhost fallback applies —
3633        // the same posture as the legacy `HYPRSTREAM_CORS_ORIGINS` parser.
3634        for origins in ["", "   ", ",", " ,\t, "] {
3635            let cfg = cors_cfg_from_env(origins)?;
3636            assert!(cfg.oauth.cors.allowed_origins.is_empty(), "{origins:?}");
3637            assert!(cfg.oauth.cors.enabled);
3638            assert!(cfg.oauth.cors.allow_credentials);
3639            assert_eq!(
3640                cfg.oauth.external_url.as_deref(),
3641                Some("https://discovery.staging.lab.hyprstream.com")
3642            );
3643            assert_eq!(cfg.oauth.jwt_key_active_secs, Some(30));
3644
3645            // The exact four-origin localhost fallback set is allowed and echoes
3646            // credentials; a nearby unlisted port bounds the membership.
3647            for origin in [
3648                "http://localhost:3000",
3649                "http://localhost:3001",
3650                "http://127.0.0.1:3000",
3651                "http://127.0.0.1:3001",
3652            ] {
3653                let (acao, credentials) = cors_probe(&cfg, origin).await?;
3654                assert_eq!(acao, Some(origin.to_owned()), "{origins:?}");
3655                assert_eq!(credentials, Some("true".to_owned()), "{origins:?}");
3656            }
3657            for denied in ["http://localhost:3002", "https://not-allowed.example"] {
3658                // Denial is the absent ACAO; tower-http extends the configured
3659                // credentials header independently of the origin match.
3660                let (acao, _credentials) = cors_probe(&cfg, denied).await?;
3661                assert_eq!(acao, None, "{origins:?} {denied}");
3662            }
3663        }
3664        Ok(())
3665    }
3666
3667    #[tokio::test]
3668    async fn oauth_cors_env_mixed_valid_and_empty_entries_drops_empties() -> anyhow::Result<()> {
3669        // Empty entries interleaved with real origins are dropped after trimming;
3670        // the surviving exact list both serves itself and disables the fallback.
3671        let cfg = cors_cfg_from_env(
3672            " , https://staging-amp.hyprstream.com ,, https://second.example\t,",
3673        )?;
3674        assert_eq!(
3675            cfg.oauth.cors.allowed_origins,
3676            vec![
3677                "https://staging-amp.hyprstream.com".to_owned(),
3678                "https://second.example".to_owned()
3679            ]
3680        );
3681        assert!(cfg.oauth.cors.allow_credentials);
3682        for origin in [
3683            "https://staging-amp.hyprstream.com",
3684            "https://second.example",
3685        ] {
3686            let (acao, credentials) = cors_probe(&cfg, origin).await?;
3687            assert_eq!(acao, Some(origin.to_owned()));
3688            assert_eq!(credentials, Some("true".to_owned()));
3689        }
3690        // Dropped empties match nothing, the nonempty exact list suppresses the
3691        // localhost fallback, and unrelated origins stay denied. Denial is the
3692        // absent ACAO; the configured credentials header may still be emitted.
3693        for origin in ["", "http://localhost:3000", "https://not-allowed.example"] {
3694            let (acao, _credentials) = cors_probe(&cfg, origin).await?;
3695            assert_eq!(acao, None, "{origin:?}");
3696        }
3697        Ok(())
3698    }
3699
3700    #[tokio::test]
3701    async fn oauth_cors_env_padded_wildcard_selects_wildcard_with_credentials_off(
3702    ) -> anyhow::Result<()> {
3703        // Trimming a whitespace-padded star intentionally selects the explicit
3704        // wildcard operator, which always disables ambient credentials.
3705        let cfg = cors_cfg_from_env(" * ")?;
3706        assert_eq!(cfg.oauth.cors.allowed_origins, vec!["*".to_owned()]);
3707        assert!(cfg.oauth.cors.allow_credentials);
3708        for origin in ["https://anything.example", "http://localhost:3000"] {
3709            let (acao, credentials) = cors_probe(&cfg, origin).await?;
3710            assert_eq!(acao, Some("*".to_owned()), "{origin}");
3711            assert_eq!(credentials, None, "{origin}");
3712        }
3713        Ok(())
3714    }
3715
3716    #[test]
3717    fn network_iroh_required_is_serialized_and_rejects_iroh_disabled() -> anyhow::Result<()> {
3718        let mut config = QuicConfig::default();
3719        config.native_network_profile = NativeNetworkProfile::NetworkIrohRequired;
3720        config.iroh = false;
3721        assert!(config.validate_native_network_profile().is_err());
3722
3723        config.iroh = true;
3724        config.validate_native_network_profile()?;
3725        let serialized = toml::to_string(&config)?;
3726        assert!(serialized.contains("native_network_profile = \"network-iroh-required\""));
3727        let decoded: QuicConfig = toml::from_str(&serialized)?;
3728        assert!(decoded.iroh_required());
3729        Ok(())
3730    }
3731
3732    /// #1652: the Event ingress grant is name-keyed. Names outside the factory
3733    /// roster are rejected at validation — this is the loud startup failure a
3734    /// stale pre-#1652 config (DID-valued list, or a typo'd name) must hit.
3735    #[test]
3736    fn event_publishers_must_be_factory_service_names() -> anyhow::Result<()> {
3737        let mut config = QuicConfig::default();
3738        config.validate_admission_policy()?;
3739
3740        for name in ["event", "streams", "model", "oauth"] {
3741            config.event_publishers.insert(name.to_owned());
3742        }
3743        config.validate_admission_policy()?;
3744
3745        config.event_publishers.insert("not-a-service".to_owned());
3746        let error = match config.validate_admission_policy() {
3747            Ok(()) => panic!("unknown service name must fail validation"),
3748            Err(error) => error,
3749        };
3750        assert!(
3751            error.to_string().contains("not a registered service name"),
3752            "unexpected error: {error}"
3753        );
3754
3755        // A pre-#1652 DID-valued list is exactly this failure: DIDs are not
3756        // factory service names.
3757        config.event_publishers.clear();
3758        config.event_publishers.insert("did:at9p:9f7abc".to_owned());
3759        assert!(
3760            config.validate_admission_policy().is_err(),
3761            "DID-valued event_publishers must fail loudly, not become silent read-only"
3762        );
3763        Ok(())
3764    }
3765
3766    /// #1652 deploy story: a config file from before the derivation still
3767    /// carrying a `[quic.moql_subject_tenants]` table loads (the key is gone
3768    /// and ignored — tenants are store-derived now), while its DID-valued
3769    /// `event_publishers` is rejected by validation.
3770    #[test]
3771    fn legacy_did_valued_admission_config_fails_loudly_on_publishers_only() -> anyhow::Result<()> {
3772        let legacy = r#"
3773            [quic]
3774            event_publishers = ["did:at9p:legacy-service-did"]
3775
3776            [quic.moql_subject_tenants]
3777            "did:at9p:legacy-service-did" = "local"
3778        "#;
3779        let config: HyprConfig = toml::from_str(legacy)?;
3780        let error = match config.validate() {
3781            Ok(()) => panic!("DID-valued event_publishers must fail validation"),
3782            Err(error) => error,
3783        };
3784        assert!(
3785            error.to_string().contains("did:at9p:legacy-service-did"),
3786            "validation must name the offending entry: {error}"
3787        );
3788        Ok(())
3789    }
3790
3791    #[test]
3792    fn discovery_state_documentation_configures_root_backend() {
3793        let doc = include_str!("../../../../docs/discovery-state.md");
3794        let example = doc
3795            .split_once("```toml\n")
3796            .unwrap_or_else(|| panic!("TOML example"))
3797            .1
3798            .split_once("```")
3799            .unwrap_or_else(|| panic!("closed TOML example"))
3800            .0;
3801        let config: HyprConfig = toml::from_str(example).unwrap_or_else(|e| panic!("{e}"));
3802        let state = config.discovery.state;
3803        assert_eq!(
3804            state.backend,
3805            hyprstream_discovery::DiscoveryStateBackend::Tiered
3806        );
3807        assert!(state.active_active);
3808        assert_eq!(state.memory.announcement_capacity, 16_384);
3809        assert_eq!(state.valkey.announcement_capacity, 65_536);
3810        assert_eq!(state.valkey.key_prefix, "production");
3811        assert_eq!(state.valkey.url, "rediss://discovery-state.example:6379");
3812        assert_eq!(state.tiered.l1_max_ttl_ms, 1_000);
3813    }
3814
3815    #[test]
3816    fn credentials_backend_default_matches_build_profile() {
3817        let config: CredentialsConfig =
3818            toml::from_str("").unwrap_or_else(|error| panic!("{error}"));
3819        assert_eq!(config.backend, CredentialsBackend::Pglite);
3820    }
3821
3822    #[test]
3823    fn credential_pds_rejects_plaintext_capable_backends() {
3824        assert!(CredentialsBackend::Pglite
3825            .ensure_allowed_for_build()
3826            .is_ok());
3827        assert!(CredentialsBackend::Postgres
3828            .ensure_allowed_for_build()
3829            .is_ok());
3830        assert!(CredentialsBackend::Rocksdb
3831            .ensure_allowed_for_build()
3832            .is_err());
3833        assert!(CredentialsBackend::Valkey
3834            .ensure_allowed_for_build()
3835            .is_err());
3836    }
3837
3838    #[test]
3839    fn credentials_backend_deserializes_postgres() {
3840        let config: CredentialsConfig =
3841            toml::from_str("backend = \"postgres\"").unwrap_or_else(|error| panic!("{error}"));
3842        assert_eq!(config.backend, CredentialsBackend::Postgres);
3843    }
3844
3845    #[test]
3846    fn nested_environment_selects_postgres_accounts_and_rds_cell() -> anyhow::Result<()> {
3847        let source = [
3848            ("HYPRSTREAM__CREDENTIALS__BACKEND", "postgres"),
3849            ("HYPRSTREAM__RDS__CELL_ID", "staging-us-east-1"),
3850        ]
3851        .into_iter()
3852        .map(|(key, value)| (key.to_owned(), value.to_owned()))
3853        .collect();
3854        let config: HyprConfig = Config::builder()
3855            .add_source(Config::try_from(&HyprConfig::default())?)
3856            .add_source(HyprConfig::environment_source().source(Some(source)))
3857            .build()?
3858            .try_deserialize()?;
3859
3860        assert_eq!(config.credentials.backend, CredentialsBackend::Postgres);
3861        assert_eq!(config.rds.cell_id, "staging-us-east-1");
3862        let resolved_rds = config.rds.resolve_with(|_| None)?;
3863        assert_eq!(resolved_rds.cell_id, "staging-us-east-1");
3864        Ok(())
3865    }
3866
3867    #[test]
3868    fn standalone_inference_config_rejects_partial_stage_without_subset_loader() {
3869        let model = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
3870        let config = InferenceServerConfig {
3871            model_path: model.path().to_path_buf(),
3872            model_ref: "demo:main".to_owned(),
3873            model_oid: "1".repeat(40),
3874            tenant: "demo.example".to_owned(),
3875            quic_port: Some(7440),
3876            advertise_addr: Some("192.0.2.10:7440".parse().unwrap_or_else(|e| panic!("{e}"))),
3877            stage_start: 8,
3878            stage_end: Some(16),
3879            ..InferenceServerConfig::default()
3880        };
3881        let error = match config.validate() {
3882            Ok(()) => panic!("partial ranges must fail closed until #314"),
3883            Err(error) => error,
3884        };
3885        assert!(error.to_string().contains("#314"));
3886    }
3887
3888    #[test]
3889    fn standalone_inference_replicas_have_distinct_runtime_names() {
3890        let first = InferenceServerConfig {
3891            replica: 0,
3892            ..InferenceServerConfig::default()
3893        };
3894        let second = InferenceServerConfig {
3895            replica: 1,
3896            ..InferenceServerConfig::default()
3897        };
3898        assert_eq!(first.instance_name(), "inference-cpu-0");
3899        assert_eq!(second.instance_name(), "inference-cpu-1");
3900        assert_ne!(first.instance_name(), second.instance_name());
3901    }
3902
3903    #[test]
3904    fn standalone_inference_rejects_mismatched_advertised_port() {
3905        let model = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
3906        let config = InferenceServerConfig {
3907            model_path: model.path().to_path_buf(),
3908            model_ref: "demo:main".to_owned(),
3909            model_oid: "1".repeat(40),
3910            tenant: "demo.example".to_owned(),
3911            quic_port: Some(7441),
3912            advertise_addr: Some("192.0.2.10:7440".parse().unwrap_or_else(|e| panic!("{e}"))),
3913            ..InferenceServerConfig::default()
3914        };
3915
3916        let error = match config.validate() {
3917            Ok(()) => panic!("bound and advertised QUIC ports must agree"),
3918            Err(error) => error,
3919        };
3920        assert!(error.to_string().contains("must be non-zero and match"));
3921    }
3922
3923    #[test]
3924    fn standalone_inference_verifies_materialized_git_oid() {
3925        let model = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
3926        let repository = git2::Repository::init(model.path()).unwrap_or_else(|e| panic!("{e}"));
3927        std::fs::write(model.path().join("config.json"), b"{}").unwrap_or_else(|e| panic!("{e}"));
3928        std::fs::write(model.path().join(".gitignore"), b"ignored.bin\n")
3929            .unwrap_or_else(|e| panic!("{e}"));
3930        let mut index = repository.index().unwrap_or_else(|e| panic!("{e}"));
3931        index
3932            .add_path(std::path::Path::new("config.json"))
3933            .unwrap_or_else(|e| panic!("{e}"));
3934        index
3935            .add_path(std::path::Path::new(".gitignore"))
3936            .unwrap_or_else(|e| panic!("{e}"));
3937        index.write().unwrap_or_else(|e| panic!("{e}"));
3938        let tree_oid = index.write_tree().unwrap_or_else(|e| panic!("{e}"));
3939        let tree = repository
3940            .find_tree(tree_oid)
3941            .unwrap_or_else(|e| panic!("{e}"));
3942        let signature = git2::Signature::now("hyprstream-test", "test@hyprstream.local")
3943            .unwrap_or_else(|e| panic!("{e}"));
3944        let oid = repository
3945            .commit(Some("HEAD"), &signature, &signature, "fixture", &tree, &[])
3946            .unwrap_or_else(|e| panic!("{e}"));
3947
3948        let mut config = InferenceServerConfig {
3949            model_path: model.path().to_path_buf(),
3950            model_ref: "demo:main".to_owned(),
3951            model_oid: oid.to_string(),
3952            tenant: "demo.example".to_owned(),
3953            quic_port: Some(7440),
3954            advertise_addr: Some("192.0.2.10:7440".parse().unwrap_or_else(|e| panic!("{e}"))),
3955            ..InferenceServerConfig::default()
3956        };
3957        config
3958            .validate()
3959            .unwrap_or_else(|e| panic!("valid fixture rejected: {e}"));
3960        config
3961            .verify_materialized_oid()
3962            .unwrap_or_else(|e| panic!("matching OID rejected: {e}"));
3963
3964        std::fs::write(model.path().join("config.json"), b"{\"tampered\":true}")
3965            .unwrap_or_else(|e| panic!("{e}"));
3966        assert!(
3967            config.verify_materialized_oid().is_err(),
3968            "dirty tracked model bytes must not inherit the HEAD identity"
3969        );
3970        std::fs::write(model.path().join("config.json"), b"{}").unwrap_or_else(|e| panic!("{e}"));
3971
3972        std::fs::write(model.path().join("ignored.bin"), b"mutable weights")
3973            .unwrap_or_else(|e| panic!("{e}"));
3974        assert!(
3975            config.verify_materialized_oid().is_err(),
3976            "ignored model bytes must not inherit the HEAD identity"
3977        );
3978        std::fs::remove_file(model.path().join("ignored.bin")).unwrap_or_else(|e| panic!("{e}"));
3979
3980        config.model_oid = "f".repeat(40);
3981        assert!(config.verify_materialized_oid().is_err());
3982    }
3983
3984    /// #1136 anchors are a PAIR. #905 §2/§6 is bidirectional-or-not-believed, so a
3985    /// one-sided anchor config can never establish trust and must fail at validation
3986    /// rather than at `install_process_production_resolver()`.
3987    #[test]
3988    fn validate_rejects_one_sided_did_anchor_config() {
3989        let mut c = HyprConfig::default();
3990        c.model.path = std::path::PathBuf::new();
3991
3992        c.cluster_at9p_did = Some("did:at9p:example".to_owned());
3993        c.cluster_did_web = None;
3994        assert!(
3995            c.validate().is_err(),
3996            "at9p without did:web must be rejected"
3997        );
3998
3999        c.cluster_at9p_did = None;
4000        c.cluster_did_web = Some("did:web:example.com".to_owned());
4001        assert!(
4002            c.validate().is_err(),
4003            "did:web without at9p must be rejected"
4004        );
4005
4006        // Both absent: anchors simply not configured — the OS-owned path applies.
4007        c.cluster_did_web = None;
4008        assert!(
4009            c.validate().is_ok(),
4010            "no anchors configured must remain valid"
4011        );
4012
4013        // Both present: the pairing the resolver expects.
4014        c.cluster_at9p_did = Some("did:at9p:example".to_owned());
4015        c.cluster_did_web = Some("did:web:example.com".to_owned());
4016        assert!(c.validate().is_ok(), "paired anchors must be accepted");
4017    }
4018
4019    /// Serialize process-env mutations for secrets-dir resolver tests.
4020    static SECRETS_DIR_ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
4021
4022    #[test]
4023    #[allow(clippy::unwrap_used)]
4024    fn public_cluster_did_anchors_deserialize_from_root_config() {
4025        let config: HyprConfig = toml::from_str(
4026            r#"
4027cluster_at9p_did = "did:at9p:bafyclusterpin"
4028cluster_did_web = "did:web:discovery.hyprstream.com"
4029"#,
4030        )
4031        .unwrap();
4032        assert_eq!(
4033            config.cluster_at9p_did.as_deref(),
4034            Some("did:at9p:bafyclusterpin")
4035        );
4036        assert_eq!(
4037            config.cluster_did_web.as_deref(),
4038            Some("did:web:discovery.hyprstream.com")
4039        );
4040    }
4041
4042    #[test]
4043    #[allow(clippy::unwrap_used)]
4044    fn resolve_secrets_dir_env_overrides_config() {
4045        let _serial = SECRETS_DIR_ENV_LOCK.lock();
4046        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", "/tmp/hyprstream-test-config");
4047        let _instance = EnvVarGuard::unset("HYPRSTREAM_INSTANCE");
4048        let _env = EnvVarGuard::set("HYPRSTREAM__SECRETS__PATH", "/run/hyprstream/secrets");
4049
4050        let mut cfg = HyprConfig::default();
4051        cfg.secrets.path = Some(PathBuf::from("/config/secrets"));
4052
4053        let dir = HyprConfig::resolve_secrets_dir_for(Some(&cfg)).unwrap();
4054        assert_eq!(dir, PathBuf::from("/run/hyprstream/secrets"));
4055    }
4056
4057    #[test]
4058    #[allow(clippy::unwrap_used)]
4059    fn resolve_secrets_dir_config_overrides_xdg_default() {
4060        let _serial = SECRETS_DIR_ENV_LOCK.lock();
4061        let xdg = tempfile::TempDir::new().unwrap();
4062        let config_secret = xdg.path().join("from-config");
4063        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", xdg.path().to_str().unwrap());
4064        let _instance = EnvVarGuard::unset("HYPRSTREAM_INSTANCE");
4065        let _env = EnvVarGuard::unset("HYPRSTREAM__SECRETS__PATH");
4066
4067        let mut cfg = HyprConfig::default();
4068        cfg.secrets.path = Some(config_secret.clone());
4069
4070        let dir = HyprConfig::resolve_secrets_dir_for(Some(&cfg)).unwrap();
4071        assert_eq!(dir, config_secret);
4072    }
4073
4074    #[test]
4075    #[allow(clippy::unwrap_used)]
4076    fn resolve_secrets_dir_uses_xdg_default_without_env_or_config_path() {
4077        let _serial = SECRETS_DIR_ENV_LOCK.lock();
4078        let xdg = tempfile::TempDir::new().unwrap();
4079        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", xdg.path().to_str().unwrap());
4080        let _instance = EnvVarGuard::unset("HYPRSTREAM_INSTANCE");
4081        let _env = EnvVarGuard::unset("HYPRSTREAM__SECRETS__PATH");
4082
4083        let dir = HyprConfig::resolve_secrets_dir().unwrap();
4084        assert_eq!(dir, xdg.path().join("hyprstream").join("credentials"));
4085    }
4086
4087    #[test]
4088    fn resolve_secrets_dir_errors_when_xdg_unresolvable() {
4089        let _serial = SECRETS_DIR_ENV_LOCK.lock();
4090        let _instance = EnvVarGuard::set("HYPRSTREAM_INSTANCE", "../bad");
4091        let _env = EnvVarGuard::unset("HYPRSTREAM__SECRETS__PATH");
4092
4093        assert!(HyprConfig::resolve_secrets_dir().is_err());
4094    }
4095
4096    #[test]
4097    #[allow(clippy::expect_used)]
4098    fn test_config_with_worker_section_at_defaults_serializes_to_toml() {
4099        // F3 (#761) regression: `AdmissionConfig`'s default per-Subject/per-group
4100        // quotas used to be `usize::MAX`, which is not a valid TOML i64, so
4101        // `Config::save()` (which does `toml::to_string_pretty(self)`) failed
4102        // for any config carrying a `[worker]` section. This reproduces that
4103        // exact save path and round-trips it.
4104        let mut config = HyprConfig::default();
4105        config.worker = Some(hyprstream_workers::config::WorkerConfig::default());
4106
4107        let toml_str = toml::to_string_pretty(&config)
4108            .expect("a default worker section must serialize to TOML (F3)");
4109        let parsed: HyprConfig = toml::from_str(&toml_str).expect("round-trip parse must succeed");
4110        let admission = parsed
4111            .worker
4112            .expect("worker section round-trips")
4113            .pool
4114            .admission;
4115        assert_eq!(admission.max_per_subject, None);
4116        assert_eq!(admission.max_per_group, None);
4117    }
4118
4119    #[test]
4120    fn test_generation_config_defaults() {
4121        let config = GenerationConfig::default();
4122
4123        // Verify max_tokens is set to 2048 (not 100)
4124        assert_eq!(
4125            config.max_tokens, 2048,
4126            "Default max_tokens should be 2048 for thinking mode support"
4127        );
4128
4129        // Verify other reasonable defaults
4130        assert!(config.temperature > 0.0, "Temperature should be non-zero");
4131        assert!(
4132            config.top_p > 0.0 && config.top_p <= 1.0,
4133            "top_p should be in valid range"
4134        );
4135    }
4136
4137    #[test]
4138    fn test_sampling_params_into_generation_request() {
4139        let params = SamplingParams {
4140            temperature: Some(0.8),
4141            top_k: Some(30),
4142            max_tokens: Some(1000),
4143            ..Default::default()
4144        };
4145
4146        let request = params.into_generation_request("test prompt".to_owned());
4147
4148        assert_eq!(request.prompt, "test prompt");
4149        assert_eq!(request.temperature, Some(0.8));
4150        assert_eq!(request.top_k, Some(30));
4151        assert_eq!(request.max_tokens, Some(1000));
4152    }
4153
4154    #[test]
4155    fn test_clean_config_precedence() {
4156        let server_defaults = SamplingParams {
4157            max_tokens: Some(1024),
4158            temperature: Some(0.5),
4159            top_p: Some(0.9),
4160            top_k: Some(50),
4161            repeat_penalty: Some(1.1),
4162            ..Default::default()
4163        };
4164
4165        let model_defaults = SamplingParams {
4166            temperature: Some(0.7),
4167            top_k: Some(40),
4168            typical_p: Some(0.95),
4169            ..Default::default()
4170        };
4171
4172        let user_overrides = SamplingParams {
4173            temperature: Some(0.9),
4174            max_tokens: Some(512),
4175            ..Default::default()
4176        };
4177
4178        let final_config = server_defaults.merge(model_defaults).merge(user_overrides);
4179
4180        assert_eq!(final_config.temperature, Some(0.9));
4181        assert_eq!(final_config.max_tokens, Some(512));
4182        assert_eq!(final_config.top_k, Some(40));
4183        assert_eq!(final_config.top_p, Some(0.9));
4184        assert_eq!(final_config.repeat_penalty, Some(1.1));
4185        assert_eq!(final_config.typical_p, Some(0.95));
4186    }
4187
4188    #[test]
4189    fn test_builder_flow() {
4190        let server_params = SamplingParams {
4191            max_tokens: Some(2048),
4192            temperature: Some(0.7),
4193            top_p: Some(0.95),
4194            ..Default::default()
4195        };
4196
4197        let model_params = SamplingParams {
4198            temperature: Some(0.6),
4199            repeat_penalty: Some(1.2),
4200            ..Default::default()
4201        };
4202
4203        let user_overrides = SamplingParams {
4204            temperature: Some(0.8),
4205            max_tokens: Some(512),
4206            ..Default::default()
4207        };
4208
4209        let params = server_params.merge(model_params).merge(user_overrides);
4210        let request = params.into_generation_request("test prompt".to_owned());
4211
4212        assert_eq!(request.prompt, "test prompt");
4213        assert_eq!(request.temperature, Some(0.8));
4214        assert_eq!(request.max_tokens, Some(512));
4215        assert_eq!(request.top_p, Some(0.95));
4216        assert_eq!(request.repeat_penalty, Some(1.2));
4217    }
4218
4219    #[test]
4220    fn test_resolved_params() {
4221        let params = SamplingParams {
4222            temperature: Some(0.5),
4223            max_tokens: None,
4224            ..Default::default()
4225        };
4226
4227        let resolved = params.resolve();
4228
4229        assert_eq!(resolved.temperature, 0.5);
4230        assert_eq!(resolved.max_tokens, 2048);
4231        assert_eq!(resolved.top_p, 0.95);
4232        assert_eq!(resolved.repeat_penalty, 1.0);
4233        assert!(resolved.do_sample);
4234    }
4235
4236    #[test]
4237    fn test_oauth_secs_overrides() {
4238        let mut config = OAuthConfig::default();
4239        assert_eq!(
4240            config.active_secs(),
4241            i64::from(config.jwt_key_active_days) * 86400
4242        );
4243        config.jwt_key_active_secs = Some(30);
4244        config.jwt_key_lead_secs = Some(25);
4245        config.jwt_key_drain_secs = Some(20);
4246        config.jwt_key_rotation_check_secs = Some(3);
4247        assert_eq!(config.active_secs(), 30);
4248        assert_eq!(config.lead_secs(), 25);
4249        assert_eq!(config.drain_secs(), 20);
4250        assert_eq!(
4251            config.rotation_check_interval(),
4252            std::time::Duration::from_secs(3)
4253        );
4254    }
4255
4256    #[test]
4257    #[allow(clippy::unwrap_used)]
4258    fn validation_rejects_didweb_user_mapping() {
4259        let provider: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4260            "client_id": "legacy-client",
4261            "user_mapping": "didweb"
4262        }))
4263        .unwrap();
4264        let mut config = HyprConfig::default();
4265        config
4266            .oauth
4267            .oidc_providers
4268            .insert("legacy".to_owned(), provider);
4269
4270        let err = config.validate().unwrap_err();
4271        assert!(err
4272            .to_string()
4273            .contains("disabled user_mapping = \"didweb\""));
4274    }
4275
4276    #[test]
4277    #[allow(clippy::unwrap_used)]
4278    fn federate_owner_enrollment_requires_pinned_oidc_and_deny_provisioning() {
4279        let provider: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4280            "kind": "oidc",
4281            "issuer_url": "https://login.federate.to",
4282            "client_id": "pilot-client",
4283            "scopes": ["openid", "profile", "federated:id"],
4284            "federate_atproto_owner": {
4285                "owner_did": "did:plc:abcdefghijklmnopqrstuvwx",
4286                "username": "pilot-owner"
4287            }
4288        }))
4289        .unwrap();
4290        let mut config = HyprConfig::default();
4291        config
4292            .oauth
4293            .oidc_providers
4294            .insert("federate".to_owned(), provider);
4295        assert!(config.validate().is_ok());
4296
4297        let fresh_owner: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4298            "kind": "oidc",
4299            "issuer_url": "https://login.federate.to",
4300            "client_id": "pilot-client",
4301            "scopes": ["openid", "profile", "federated:id"],
4302            "federate_atproto_owner": {
4303                "owner_did": "did:plc:bcdefghijklmnopqrstuvwxy"
4304            }
4305        }))
4306        .unwrap();
4307        let mut fresh_config = HyprConfig::default();
4308        fresh_config
4309            .oauth
4310            .oidc_providers
4311            .insert("federate".to_owned(), fresh_owner);
4312        assert!(fresh_config.validate().is_ok());
4313
4314        let missing_scope: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4315            "kind": "oidc",
4316            "issuer_url": "https://login.federate.to",
4317            "client_id": "pilot-client",
4318            "federate_atproto_owner": {
4319                "owner_did": "did:plc:bcdefghijklmnopqrstuvwxy"
4320            }
4321        }))
4322        .unwrap();
4323        let mut missing_scope_config = HyprConfig::default();
4324        missing_scope_config
4325            .oauth
4326            .oidc_providers
4327            .insert("federate".to_owned(), missing_scope);
4328        assert!(missing_scope_config
4329            .validate()
4330            .unwrap_err()
4331            .to_string()
4332            .contains("requires the federated:id scope"));
4333
4334        let alternate: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4335            "kind": "oauth2",
4336            "issuer_url": "https://login.federate.to",
4337            "client_id": "alternate-client",
4338            "userinfo_endpoint": "https://userinfo.example"
4339        }))
4340        .unwrap();
4341        config
4342            .oauth
4343            .oidc_providers
4344            .insert("federate-userinfo".to_owned(), alternate);
4345        assert!(config
4346            .validate()
4347            .unwrap_err()
4348            .to_string()
4349            .contains("without Federate owner enrollment"));
4350
4351        let insecure_provider: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4352            "kind": "oidc",
4353            "issuer_url": "https://login.federate.to",
4354            "client_id": "pilot-client",
4355            "allow_http": true,
4356            "scopes": ["openid", "profile", "federated:id"],
4357            "federate_atproto_owner": {
4358                "owner_did": "did:plc:abcdefghijklmnopqrstuvwx",
4359                "username": "pilot-owner"
4360            }
4361        }))
4362        .unwrap();
4363        let mut insecure_config = HyprConfig::default();
4364        insecure_config
4365            .oauth
4366            .oidc_providers
4367            .insert("federate".to_owned(), insecure_provider.clone());
4368        assert!(insecure_config
4369            .validate()
4370            .unwrap_err()
4371            .to_string()
4372            .contains("does not allow HTTP"));
4373
4374        let mut wrong_issuer: OidcProviderConfig = serde_json::from_value(serde_json::json!({
4375            "kind": "oidc",
4376            "issuer_url": "https://attacker.example",
4377            "client_id": "pilot-client",
4378            "scopes": ["openid", "profile", "federated:id"],
4379            "federate_atproto_owner": {
4380                "owner_did": "did:plc:abcdefghijklmnopqrstuvwx",
4381                "username": "pilot-owner"
4382            }
4383        }))
4384        .unwrap();
4385        let mut config = HyprConfig::default();
4386        config
4387            .oauth
4388            .oidc_providers
4389            .insert("federate".to_owned(), wrong_issuer.clone());
4390        assert!(config
4391            .validate()
4392            .unwrap_err()
4393            .to_string()
4394            .contains("pinned issuer"));
4395
4396        wrong_issuer.issuer_url = Some("https://login.federate.to".to_owned());
4397        wrong_issuer.provisioning = ProvisioningMode::Auto;
4398        let mut config = HyprConfig::default();
4399        config
4400            .oauth
4401            .oidc_providers
4402            .insert("federate".to_owned(), wrong_issuer);
4403        assert!(config
4404            .validate()
4405            .unwrap_err()
4406            .to_string()
4407            .contains("provisioning = \"deny\""));
4408    }
4409
4410    #[test]
4411    #[allow(clippy::unwrap_used, clippy::expect_used)]
4412    fn test_oauth_secs_from_env() {
4413        // Simulate env vars the same way HyprConfig::load() does
4414        std::env::set_var("HYPRSTREAM__OAUTH__JWT_KEY_ACTIVE_SECS", "30");
4415        let result = config::Config::builder()
4416            .add_source(config::Config::try_from(&HyprConfig::default()).unwrap())
4417            .add_source(
4418                config::Environment::with_prefix("HYPRSTREAM")
4419                    .separator("__")
4420                    .try_parsing(true),
4421            )
4422            .build()
4423            .and_then(config::Config::try_deserialize::<HyprConfig>);
4424        std::env::remove_var("HYPRSTREAM__OAUTH__JWT_KEY_ACTIVE_SECS");
4425        let cfg = result.expect("config should parse with env var");
4426        assert_eq!(
4427            cfg.oauth.jwt_key_active_secs,
4428            Some(30),
4429            "jwt_key_active_secs should be 30 from env"
4430        );
4431        assert_eq!(cfg.oauth.active_secs(), 30);
4432    }
4433
4434    /// RAII guard to set/unset a process env var for the duration of a test and
4435    /// restore the previous value, keeping env-mutating tests from leaking state.
4436    struct EnvVarGuard {
4437        key: String,
4438        prev: Option<String>,
4439    }
4440    impl EnvVarGuard {
4441        fn set(key: &str, val: &str) -> Self {
4442            let prev = std::env::var(key).ok();
4443            std::env::set_var(key, val);
4444            Self {
4445                key: key.to_owned(),
4446                prev,
4447            }
4448        }
4449        fn unset(key: &str) -> Self {
4450            let prev = std::env::var(key).ok();
4451            std::env::remove_var(key);
4452            Self {
4453                key: key.to_owned(),
4454                prev,
4455            }
4456        }
4457    }
4458    impl Drop for EnvVarGuard {
4459        fn drop(&mut self) {
4460            match &self.prev {
4461                Some(v) => std::env::set_var(&self.key, v),
4462                None => std::env::remove_var(&self.key),
4463            }
4464        }
4465    }
4466}
4467
4468#[cfg(test)]
4469mod pinned_config_tests {
4470    #![allow(clippy::expect_used, clippy::unwrap_used)]
4471
4472    use super::*;
4473
4474    const PINNED_CHILD: &str = "HYPRSTREAM_PINNED_CONFIG_CHILD";
4475
4476    /// The write-once snapshot must be the ONE process configuration: after
4477    /// startup pins the validated explicit file, factory-style
4478    /// `HyprConfig::load()` calls observe the snapshot even when the XDG
4479    /// default changes underneath, and never follow source-file rereads.
4480    /// Runs in an isolated child because the slot is process-global.
4481    #[test]
4482    fn pinned_config_snapshot_observed_by_load() -> anyhow::Result<()> {
4483        if std::env::var_os(PINNED_CHILD).is_none() {
4484            let status = std::process::Command::new(std::env::current_exe()?)
4485                .args([
4486                    "--exact",
4487                    "config::pinned_config_tests::pinned_config_snapshot_observed_by_load",
4488                    "--nocapture",
4489                ])
4490                .env(PINNED_CHILD, "1")
4491                .status()?;
4492            anyhow::ensure!(status.success(), "pinned-config regression failed");
4493            return Ok(());
4494        }
4495
4496        let root = tempfile::tempdir()?;
4497        let xdg = root.path().join("xdg-config");
4498        std::env::set_var("XDG_CONFIG_HOME", &xdg);
4499        let default_config = xdg.join("hyprstream").join("config.toml");
4500        std::fs::create_dir_all(default_config.parent().expect("parent"))?;
4501
4502        let write_config = |path: &Path, secrets: &Path| -> anyhow::Result<()> {
4503            if let Some(parent) = path.parent() {
4504                std::fs::create_dir_all(parent)?;
4505            }
4506            let mut configured = HyprConfig::default();
4507            configured.secrets.path = Some(secrets.to_path_buf());
4508            configured.to_file(path)
4509        };
4510
4511        // XDG default initially points at B; the operator's explicit file at A.
4512        let secrets_b = root.path().join("secrets-B");
4513        write_config(&default_config, &secrets_b)?;
4514        let explicit = root.path().join("custom dir/custom.toml");
4515        let secrets_a = root.path().join("secrets-A");
4516        write_config(&explicit, &secrets_a)?;
4517
4518        // Main's path: load the explicit file, validate, pin.
4519        let loaded = HyprConfig::from_file(&explicit)?;
4520        loaded.validate()?;
4521        let _ = install_pinned_config(loaded);
4522
4523        // Post-pin drift: the XDG default changes to C and the explicit source
4524        // file changes to D. Factory-style reloads must stay on the snapshot.
4525        let secrets_c = root.path().join("secrets-C");
4526        write_config(&default_config, &secrets_c)?;
4527        let reloaded = HyprConfig::load().expect("pinned reload");
4528        assert_eq!(
4529            reloaded.secrets.path,
4530            Some(secrets_a.clone()),
4531            "factory-style HyprConfig::load() must observe the pinned snapshot, not XDG defaults"
4532        );
4533        let secrets_d = root.path().join("secrets-D");
4534        write_config(&explicit, &secrets_d)?;
4535        let again = HyprConfig::load().expect("second pinned reload");
4536        assert_eq!(
4537            again.secrets.path,
4538            Some(secrets_a),
4539            "load() must not follow source-file rereads after the pin"
4540        );
4541        std::env::remove_var("XDG_CONFIG_HOME");
4542        Ok(())
4543    }
4544}