1pub mod server;
9
10pub use server::{
12 CorsConfig, NinepCanonicalReadConfig, SamplingParamDefaults, ServerConfig, ServerConfigBuilder,
13};
14
15pub use hyprstream_pds::rds::RdsConfig;
20
21pub use hyprstream_inference::config::{
24 default_lora_rank, default_target_modules, FinishReason, GenerationConfig, GenerationResult,
25 HyprstreamTrainingConfig, ModelConfig, RuntimeConfig, TTTMetrics, TTTTrainingConfig,
26 TrainingMode,
27};
28
29use 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
39static PINNED_CONFIG: OnceLock<HyprConfig> = OnceLock::new();
55
56pub fn install_pinned_config(config: HyprConfig) -> bool {
63 PINNED_CONFIG.set(config).is_ok()
64}
65
66pub fn pinned_config() -> Option<&'static HyprConfig> {
68 PINNED_CONFIG.get()
69}
70
71static EXPLICIT_CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();
78
79pub fn install_explicit_config_path(path: PathBuf) -> bool {
81 EXPLICIT_CONFIG_PATH.set(path).is_ok()
82}
83
84pub fn explicit_config_path() -> Option<&'static PathBuf> {
86 EXPLICIT_CONFIG_PATH.get()
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize, Default)]
91pub struct HyprConfig {
92 #[serde(default)]
94 pub server: ServerConfig,
95
96 #[serde(default)]
98 pub model: ModelConfig,
99
100 #[serde(default)]
102 pub inference: InferenceServerConfig,
103
104 #[serde(default)]
106 pub runtime: RuntimeConfig,
107
108 #[serde(default)]
110 pub generation: GenerationConfig,
111
112 #[serde(default)]
114 pub lora: LoraAppConfig,
115
116 #[serde(default)]
118 pub storage: StorageConfig,
119
120 #[serde(default)]
122 pub git2db: git2db::config::Git2DBConfig,
123
124 #[serde(default)]
129 pub worker: Option<hyprstream_workers::config::WorkerConfig>,
130
131 #[serde(default)]
135 pub services: ServicesConfig,
136
137 #[serde(default)]
139 pub token: TokenConfig,
140
141 #[serde(default)]
143 pub oai: OAIConfig,
144
145 #[serde(default)]
147 pub xet: XetConfig,
148
149 #[serde(default)]
151 pub flight: FlightConfig,
152
153 #[serde(default)]
155 pub mcp: MCPConfig,
156
157 #[serde(default)]
159 pub oauth: OAuthConfig,
160
161 #[serde(default)]
163 pub credentials: CredentialsConfig,
164
165 #[serde(default)]
167 pub streaming: StreamingConfig,
168
169 #[serde(default)]
175 pub rpc: RpcServerConfig,
176
177 #[serde(default)]
182 pub tls: TlsConfig,
183
184 #[serde(default)]
192 pub account: crate::account::AccountZoneConfig,
193
194 #[serde(default)]
200 pub quic: QuicConfig,
201
202 #[serde(default)]
204 pub event: EventServiceConfig,
205
206 #[serde(default)]
208 pub registry: RegistryServiceConfig,
209
210 #[serde(default)]
212 pub policy: PolicyServiceConfig,
213
214 #[serde(default)]
216 pub discovery: DiscoveryServiceConfig,
217
218 #[serde(default)]
220 pub tui: TuiServiceConfig,
221
222 #[serde(default)]
224 pub metrics: MetricsConfig,
225
226 #[serde(default, skip_serializing)]
232 pub signing_key: Option<String>,
233
234 #[serde(default)]
241 pub secrets: SecretsConfig,
242
243 #[serde(default)]
247 pub cluster_at9p_did: Option<String>,
248
249 #[serde(default)]
251 pub cluster_did_web: Option<String>,
252
253 #[serde(default)]
258 pub cluster_anchor_root_cert: Option<PathBuf>,
259
260 #[serde(default)]
267 pub cluster_remote_node: bool,
268
269 #[cfg(feature = "ledger")]
275 #[serde(default)]
276 pub ledger: crate::services::ledger::LedgerConfig,
277
278 #[serde(default)]
291 pub rds: RdsConfig,
292
293 #[cfg(feature = "postgres-ledger")]
297 #[serde(default)]
298 pub ledger_postgres_url: Option<String>,
299
300 #[cfg(feature = "postgres-ledger")]
302 #[serde(default)]
303 pub ledger_postgres_pool_size: Option<usize>,
304}
305
306#[derive(Debug, Clone, Serialize, Deserialize, Default)]
317pub struct SecretsConfig {
318 #[serde(default)]
321 pub path: Option<PathBuf>,
322}
323
324impl SecretsConfig {
325 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 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#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
374#[serde(rename_all = "kebab-case")]
375pub enum TlsMode {
376 #[default]
378 SelfSigned,
379 Acme,
383 AcmeDns01,
392 Files,
394}
395
396#[derive(Debug, Clone, Serialize, Deserialize)]
397pub struct TlsConfig {
398 #[serde(default = "default_tls_enabled")]
400 pub enabled: bool,
401
402 #[serde(default)]
404 pub mode: TlsMode,
405
406 #[serde(default)]
408 pub cert_path: Option<PathBuf>,
409
410 #[serde(default)]
412 pub key_path: Option<PathBuf>,
413
414 #[serde(default = "default_tls_server_name")]
416 pub server_name: String,
417
418 #[serde(default)]
420 pub acme_domain: Option<String>,
421
422 #[serde(default)]
424 pub acme_contact: Option<String>,
425
426 #[serde(default)]
429 pub acme_directory: Option<String>,
430
431 #[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 pub fn effective_mode(&self) -> TlsMode {
455 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 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#[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 #[serde(default = "default_quic_enabled")]
505 pub enabled: bool,
506
507 #[serde(default = "default_quic_bind_addr")]
509 pub bind_addr: String,
510
511 #[serde(default = "default_quic_server_name")]
513 pub server_name: String,
514
515 #[serde(default)]
517 pub cert_path: String,
518
519 #[serde(default)]
521 pub key_path: String,
522
523 #[serde(default = "default_iroh_enabled")]
530 pub iroh: bool,
531
532 #[serde(default)]
535 pub native_network_profile: NativeNetworkProfile,
536
537 #[serde(default)]
554 pub event_publishers: std::collections::BTreeSet<String>,
555
556 #[serde(default)]
563 pub stream_publishers: std::collections::BTreeSet<String>,
564
565 #[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 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 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 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 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 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 Ok((vec![materials.cert_der], materials.key_der))
687 } else {
688 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 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 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 iroh_enabled: self.iroh,
752 iroh_required: self.iroh_required(),
753 on_iroh_bound: None,
754 moq_relay: None,
757 moq_relay_server_identity: None,
758 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}
770fn 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#[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, max_ttl_seconds: 172_800, }
798 }
799}
800
801fn default_token_ttl() -> u32 {
802 172_800
803} fn default_max_token_ttl() -> u32 {
805 172_800
806} #[derive(Debug, Clone, Serialize, Deserialize)]
810pub struct OAIConfig {
811 #[serde(default = "default_oai_host")]
813 pub host: String,
814
815 #[serde(default = "default_oai_port")]
817 pub port: u16,
818
819 #[serde(default)]
822 pub external_url: Option<String>,
823
824 #[serde(default)]
826 pub tls_cert: Option<PathBuf>,
827
828 #[serde(default)]
830 pub tls_key: Option<PathBuf>,
831
832 #[serde(default = "default_oai_timeout")]
834 pub request_timeout_secs: u64,
835
836 #[serde(default)]
838 pub cors: server::CorsConfig,
839
840 #[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 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#[derive(Debug, Clone, Serialize, Deserialize)]
903pub struct XetConfig {
904 #[serde(default = "default_xet_host")]
906 pub host: String,
907
908 #[serde(default = "default_xet_port")]
910 pub port: u16,
911
912 #[serde(default)]
915 pub external_url: Option<String>,
916
917 #[serde(default)]
919 pub tls_cert: Option<PathBuf>,
920
921 #[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 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#[derive(Debug, Clone, Serialize, Deserialize)]
970pub struct FlightConfig {
971 #[serde(default = "default_flight_host")]
973 pub host: String,
974
975 #[serde(default = "default_flight_port")]
977 pub port: u16,
978
979 #[serde(default)]
981 pub external_url: Option<String>,
982
983 #[serde(default)]
985 pub default_dataset: Option<String>,
986
987 #[serde(default)]
989 pub tls_cert: Option<PathBuf>,
990
991 #[serde(default)]
993 pub tls_key: Option<PathBuf>,
994
995 #[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 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#[derive(Debug, Clone, Serialize, Deserialize)]
1042pub struct MCPConfig {
1043 #[serde(default = "default_mcp_host")]
1045 pub host: String,
1046
1047 #[serde(default = "default_mcp_port")]
1049 pub http_port: u16,
1050
1051 #[serde(default)]
1054 pub external_url: Option<String>,
1055
1056 #[serde(default)]
1058 pub tls_cert: Option<PathBuf>,
1059
1060 #[serde(default)]
1062 pub tls_key: Option<PathBuf>,
1063
1064 #[serde(default)]
1066 pub quic_port: Option<u16>,
1067
1068 #[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 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#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1118pub struct TrustedIssuerConfig {
1119 #[serde(default)]
1122 pub jwks_uri: Option<String>,
1123 #[serde(default = "default_jwks_cache_ttl")]
1125 pub jwks_cache_ttl_secs: u64,
1126 #[serde(default)]
1131 pub allow_http: bool,
1132 #[serde(default, skip_serializing_if = "Option::is_none")]
1138 pub federate_tui_client: Option<FederateClientClassConfig>,
1139}
1140
1141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1151pub struct FederateClientClassConfig {
1152 pub client_id: String,
1154 pub aud: String,
1158 #[serde(default)]
1160 pub connector_id: Option<String>,
1161}
1162
1163fn default_jwks_cache_ttl() -> u64 {
1164 300
1165}
1166
1167#[derive(Debug, Clone, Serialize, Deserialize)]
1185pub struct MeshPeerConfig {
1186 pub ed25519_multibase: String,
1190 pub mldsa65_multibase: String,
1194}
1195
1196#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1198#[serde(rename_all = "lowercase")]
1199pub enum ProviderKind {
1200 #[default]
1202 Oidc,
1203 OAuth2,
1206}
1207
1208#[derive(Debug, Clone, Serialize, Deserialize)]
1210pub struct ClaimMapping {
1211 #[serde(default = "default_claim_sub")]
1215 pub sub: String,
1216 #[serde(default = "default_claim_name")]
1218 pub name: Option<String>,
1219 #[serde(default = "default_claim_email")]
1221 pub email: Option<String>,
1222 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
1258pub struct OidcProviderConfig {
1259 #[serde(default)]
1261 pub kind: ProviderKind,
1262 #[serde(default)]
1265 pub issuer_url: Option<String>,
1266 #[serde(default)]
1268 pub authorization_endpoint: Option<String>,
1269 #[serde(default)]
1272 pub token_endpoint_url: Option<String>,
1273 #[serde(default)]
1275 pub userinfo_endpoint: Option<String>,
1276 #[serde(default = "default_pkce_supported")]
1279 pub pkce_supported: bool,
1280 #[serde(default)]
1282 pub claim_mapping: ClaimMapping,
1283 pub client_id: String,
1285 #[serde(default)]
1287 pub client_secret: Option<String>,
1288 #[serde(default)]
1290 pub scopes: Vec<String>,
1291 #[serde(default)]
1293 pub display_name: Option<String>,
1294 #[serde(default)]
1296 pub allow_http: bool,
1297 #[serde(default)]
1299 pub user_mapping: UserMappingStrategy,
1300 #[serde(default, skip_serializing_if = "Option::is_none")]
1308 pub federate_atproto_owner: Option<FederateAtprotoOwnerEnrollment>,
1309 #[serde(default)]
1311 pub provisioning: ProvisioningMode,
1312 #[serde(default)]
1314 pub allowed_domains: Vec<String>,
1315 #[serde(default)]
1317 pub default_scopes: Vec<String>,
1318 #[serde(default = "default_clock_skew")]
1320 pub clock_skew_seconds: u64,
1321}
1322
1323#[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#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1378#[serde(rename_all = "lowercase")]
1379pub enum UserMappingStrategy {
1380 #[default]
1382 Namespaced,
1383 Email,
1385 Claim {
1387 name: String,
1389 },
1390 DidWeb,
1394}
1395
1396#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1398#[serde(rename_all = "lowercase")]
1399pub enum ProvisioningMode {
1400 #[default]
1402 Deny,
1403 Auto,
1405 Allowlist,
1407}
1408
1409#[derive(Debug, Clone, Serialize, Deserialize)]
1415pub struct OAuthConfig {
1416 #[serde(default = "default_oauth_host")]
1418 pub host: String,
1419
1420 #[serde(default = "default_oauth_port")]
1422 pub port: u16,
1423
1424 #[serde(default)]
1427 pub external_url: Option<String>,
1428
1429 #[serde(default = "default_oauth_scopes")]
1431 pub default_scopes: Vec<String>,
1432
1433 #[serde(default = "default_oauth_token_ttl")]
1435 pub token_ttl_seconds: u32,
1436
1437 #[serde(default = "default_refresh_token_ttl")]
1439 pub refresh_token_ttl_seconds: u32,
1440
1441 #[serde(default)]
1443 pub tls_cert: Option<PathBuf>,
1444
1445 #[serde(default)]
1447 pub tls_key: Option<PathBuf>,
1448
1449 #[serde(default)]
1451 pub quic_port: Option<u16>,
1452
1453 #[serde(default)]
1464 pub deployment_well_known_dir: Option<PathBuf>,
1465
1466 #[serde(default = "default_oauth_cors")]
1468 pub cors: server::CorsConfig,
1469
1470 #[serde(default)]
1474 pub trusted_issuers: std::collections::HashMap<String, TrustedIssuerConfig>,
1475
1476 #[serde(default)]
1484 pub identity_registration_did_web_origins: Vec<String>,
1485
1486 #[serde(default)]
1494 pub mesh_peers: std::collections::HashMap<String, MeshPeerConfig>,
1495
1496 #[serde(default)]
1501 pub authority_hints: Vec<String>,
1502
1503 #[serde(default)]
1510 pub oidc_providers: std::collections::HashMap<String, OidcProviderConfig>,
1511
1512 #[serde(default, skip_serializing)]
1519 pub user_signing_key: Option<String>,
1520
1521 #[serde(default = "default_client_jwks_uri_cache_ttl")]
1533 pub client_jwks_uri_cache_ttl_secs: u64,
1534
1535 #[serde(default = "default_jwt_key_active_days")]
1537 pub jwt_key_active_days: u32,
1538
1539 #[serde(default = "default_jwt_key_lead_days")]
1541 pub jwt_key_lead_days: u32,
1542
1543 #[serde(default = "default_jwt_key_drain_days")]
1545 pub jwt_key_drain_days: u32,
1546
1547 #[serde(default)]
1550 pub jwt_key_active_secs: Option<u32>,
1551
1552 #[serde(default)]
1554 pub jwt_key_lead_secs: Option<u32>,
1555
1556 #[serde(default)]
1558 pub jwt_key_drain_secs: Option<u32>,
1559
1560 #[serde(default)]
1562 pub jwt_key_rotation_check_secs: Option<u64>,
1563
1564 #[serde(default)]
1571 pub require_pushed_authorization_requests: bool,
1572
1573 #[serde(default)]
1579 pub xrpc_read_slice: bool,
1580
1581 #[serde(default)]
1587 pub public_git_canary_backend_port: Option<u16>,
1588
1589 #[serde(default)]
1593 pub public_git_canary_registry_repo_id: Option<String>,
1594
1595 #[serde(default)]
1600 pub public_git_canary_publisher_did: Option<String>,
1601
1602 #[serde(default = "default_atproto_plc_directory_url")]
1604 pub atproto_plc_directory_url: String,
1605
1606 #[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 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 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 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 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 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 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#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1725#[serde(rename_all = "lowercase")]
1726pub enum CredentialsBackend {
1727 Rocksdb,
1728 Valkey,
1729 Pglite,
1731 Postgres,
1733}
1734
1735fn default_credentials_backend() -> CredentialsBackend {
1736 CredentialsBackend::Pglite
1737}
1738
1739impl CredentialsBackend {
1740 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#[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#[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 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} fn default_client_jwks_uri_cache_ttl() -> u64 {
1818 3600
1819} fn 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#[derive(Debug, Clone, Serialize, Deserialize)]
1835pub struct RpcServerConfig {
1836 #[serde(default = "default_rpc_stream_limit")]
1838 pub stream_limit: usize,
1839 #[serde(default = "default_rpc_connection_limit")]
1841 pub connection_limit: usize,
1842 #[serde(default = "default_rpc_request_read_timeout_secs")]
1844 pub request_read_timeout_secs: u64,
1845 #[serde(default = "default_rpc_handshake_timeout_secs")]
1847 pub handshake_timeout_secs: u64,
1848 #[serde(default = "default_rpc_stopped_grace_secs")]
1850 pub stopped_grace_secs: u64,
1851 #[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 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#[derive(Debug, Clone, Serialize, Deserialize)]
1907pub struct StreamingConfig {
1908 #[serde(default = "default_max_pending_per_topic", skip_serializing)]
1910 pub max_pending_per_topic: usize,
1911
1912 #[serde(default = "default_message_ttl_secs", skip_serializing)]
1914 pub message_ttl_secs: u64,
1915
1916 #[serde(default = "default_compact_interval_secs", skip_serializing)]
1918 pub compact_interval_secs: u64,
1919
1920 #[serde(flatten, default)]
1926 pub batching: hyprstream_rpc::streaming::BatchingConfig,
1927
1928 #[serde(default)]
1930 pub quic_port: Option<u16>,
1931
1932 #[serde(default = "default_broadcast_announce_timeout_secs")]
1936 pub broadcast_announce_timeout_secs: u64,
1937
1938 #[serde(default = "default_group_idle_timeout_secs")]
1943 pub group_idle_timeout_secs: u64,
1944
1945 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
1988pub struct StorageConfig {
1989 pub models_dir: PathBuf,
1991 pub loras_dir: PathBuf,
1993 pub cache_dir: PathBuf,
1995 pub config_dir: PathBuf,
1997}
1998
1999impl Default for StorageConfig {
2000 fn default() -> Self {
2001 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#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2039pub struct EventServiceConfig {
2040 #[serde(default)]
2042 pub quic_port: Option<u16>,
2043}
2044
2045#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2047pub struct RegistryServiceConfig {
2048 #[serde(default)]
2050 pub quic_port: Option<u16>,
2051 #[serde(default)]
2054 pub at9p_renewal: At9pRenewalConfig,
2055}
2056
2057pub const MIN_SERVICE_IDENTITY_TTL_SECS: i64 = 600;
2060
2061pub const MAX_SERVICE_IDENTITY_TTL_SECS: i64 = 7_776_000;
2068
2069#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2078pub struct At9pRenewalConfig {
2079 #[serde(default)]
2084 pub check_interval_secs: Option<u64>,
2085 #[serde(default)]
2100 pub valid_for_secs: Option<i64>,
2101 #[serde(default)]
2107 pub roster_export: Option<std::path::PathBuf>,
2108}
2109
2110impl At9pRenewalConfig {
2111 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 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 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#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2174pub struct PolicyServiceConfig {
2175 #[serde(default)]
2177 pub quic_port: Option<u16>,
2178 #[serde(default)]
2181 pub boot_policy: Option<MacBootPolicyConfig>,
2182}
2183
2184#[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 pub expected_policy_hash: String,
2200}
2201
2202#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2204pub struct DiscoveryServiceConfig {
2205 #[serde(default)]
2207 pub quic_port: Option<u16>,
2208 #[serde(default)]
2211 pub state: hyprstream_discovery::DiscoveryStateConfig,
2212}
2213
2214#[derive(Debug, Clone, Serialize, Deserialize)]
2216pub struct TuiServiceConfig {
2217 #[serde(default)]
2219 pub quic_port: Option<u16>,
2220 #[serde(default = "default_tui_max_sessions")]
2222 pub max_sessions: u32,
2223 #[serde(default = "default_tui_scrollback")]
2225 pub scrollback_lines: usize,
2226 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
2254pub struct MetricsConfig {
2255 #[serde(default = "default_metrics_db")]
2258 pub db_path: String,
2259
2260 #[serde(default = "default_checkpoint_interval_secs")]
2262 pub checkpoint_interval_secs: u64,
2263
2264 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
2291pub struct ServicesConfig {
2292 #[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
2307fn default_startup_services() -> Vec<String> {
2309 let mut services = vec![
2310 "event".to_owned(), "registry".to_owned(), "policy".to_owned(), "streams".to_owned(), "worker".to_owned(), "model".to_owned(), "oauth".to_owned(), "oai".to_owned(), ];
2319 #[cfg(feature = "metrics")]
2320 {
2321 services.push("flight".to_owned()); }
2323 services.extend([
2324 "discovery".to_owned(), "mcp".to_owned(), "tui".to_owned(), ]);
2328 #[cfg(feature = "metrics")]
2329 {
2330 services.push("metrics".to_owned()); }
2332 services
2333}
2334
2335#[derive(Debug, Clone, Serialize, Deserialize)]
2341pub struct InferenceServerConfig {
2342 #[serde(default)]
2344 pub model_path: PathBuf,
2345 #[serde(default)]
2347 pub model_ref: String,
2348 #[serde(default)]
2350 pub model_oid: String,
2351 #[serde(default)]
2353 pub tenant: String,
2354 #[serde(default)]
2356 pub replica: u16,
2357 #[serde(default)]
2359 pub stage_start: u32,
2360 #[serde(default)]
2362 pub stage_end: Option<u32>,
2363 #[serde(default)]
2365 pub quic_port: Option<u16>,
2366 #[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 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 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 .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 pub fn instance_name(&self) -> String {
2500 format!("inference-cpu-{}", self.replica)
2501 }
2502}
2503
2504#[derive(Debug, Clone, Serialize, Deserialize)]
2508pub struct LoraAppConfig {
2509 pub enabled: bool,
2511 pub max_adapters: usize,
2513 pub alpha: f32,
2515 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
2530pub 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 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 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 pub fn server(mut self, f: impl FnOnce(ServerConfigBuilder) -> ServerConfigBuilder) -> Self {
2636 self.server_builder = f(self.server_builder);
2637 self
2638 }
2639
2640 pub fn from_env(mut self) -> Self {
2642 self.server_builder = self.server_builder.from_env();
2643 self
2644 }
2645
2646 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 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 pub fn builder() -> HyprConfigBuilder {
2709 HyprConfigBuilder::new()
2710 }
2711
2712 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 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 .add_source(Config::try_from(&HyprConfig::default())?)
2743 .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 .add_source(Self::environment_source());
2750
2751 let mut hypr_config: HyprConfig = settings.build()?.try_deserialize()?;
2753
2754 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 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 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 pub fn validate(&self) -> anyhow::Result<()> {
2803 self.quic.validate_admission_policy()?;
2808
2809 #[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 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 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 (None, None) | (Some(_), Some(_)) => {}
2930 }
2931
2932 Ok(())
2933 }
2934
2935 pub fn models_dir(&self) -> &PathBuf {
2937 &self.storage.models_dir
2938 }
2939
2940 pub fn loras_dir(&self) -> &PathBuf {
2942 &self.storage.loras_dir
2943 }
2944
2945 pub fn cache_dir(&self) -> &PathBuf {
2947 &self.storage.cache_dir
2948 }
2949
2950 pub fn config_dir(&self) -> &PathBuf {
2952 &self.storage.config_dir
2953 }
2954
2955 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 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 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 pub fn resolve_secrets_dir() -> anyhow::Result<PathBuf> {
2998 Self::resolve_secrets_dir_for(None)
2999 }
3000
3001 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 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 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 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(); 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#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
3095#[serde(transparent)]
3096pub struct TemplatedPrompt(String);
3097
3098impl TemplatedPrompt {
3099 pub fn new(s: String) -> Self {
3101 Self(s)
3102 }
3103
3104 pub fn as_str(&self) -> &str {
3106 &self.0
3107 }
3108
3109 pub fn into_inner(self) -> String {
3111 self.0
3112 }
3113
3114 pub fn len(&self) -> usize {
3116 self.0.len()
3117 }
3118
3119 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#[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 #[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 #[serde(default)]
3160 pub timeout_ms: Option<u64>,
3161}
3162
3163impl SamplingParams {
3164 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 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 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 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 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), }
3316 }
3317}
3318
3319#[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 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, }
3357 }
3358}
3359
3360#[cfg(test)]
3361mod tests {
3362 use super::*;
3363
3364 #[test]
3365 fn at9p_renewal_interval_must_outrun_half_ttl() {
3366 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 #[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 #[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 c.cluster_did_web = None;
4008 assert!(
4009 c.validate().is_ok(),
4010 "no anchors configured must remain valid"
4011 );
4012
4013 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 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 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 assert_eq!(
4125 config.max_tokens, 2048,
4126 "Default max_tokens should be 2048 for thinking mode support"
4127 );
4128
4129 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 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 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 #[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 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 let loaded = HyprConfig::from_file(&explicit)?;
4520 loaded.validate()?;
4521 let _ = install_pinned_config(loaded);
4522
4523 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}