Skip to main content

hyprstream_service/service/
factory.rs

1//! Service factory infrastructure for inventory-based service registration.
2//!
3//! This module provides the `ServiceFactory` type and `ServiceContext` for
4//! implementing the same inventory pattern used for `ScopeDefinition` and
5//! `DriverFactory`.
6//!
7//! # Example
8//!
9//! ```ignore
10//! use hyprstream_service::service::factory::{ServiceContext, ServiceFactory};
11//! use hyprstream_rpc_derive::service_factory;
12//!
13//! #[service_factory("policy")]
14//! fn create_policy_service(ctx: &ServiceContext) -> anyhow::Result<Box<dyn Spawnable>> {
15//!     // Services include infrastructure and are directly Spawnable
16//!     let policy = PolicyService::new(
17//!         ...,
18//!         ctx.transport("policy", SocketKind::Rep),
19//!         ctx.verifying_key(),
20//!     );
21//!     Ok(Box::new(policy))
22//! }
23//! ```
24
25use std::collections::HashMap;
26use std::net::SocketAddr;
27use std::sync::Arc;
28
29use ed25519_dalek::{SigningKey, VerifyingKey};
30use zeroize::Zeroizing;
31
32use crate::service::metadata::SchemaMetadataFn;
33use crate::service::spawner::Spawnable;
34use hyprstream_rpc::registry::{global as global_registry, SocketKind};
35use hyprstream_rpc::transport::TransportConfig;
36
37/// Dynamic carrier reach for an otherwise authority-bound announcement.
38///
39/// This deliberately contains only transport evidence.  The surrounding
40/// [`NativeAnnouncementRequest`] carries the independently accepted service
41/// identity, capability, response-key, and KEM material.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub enum NativeAnnouncementReach {
44    Quic {
45        address: SocketAddr,
46        server_name: String,
47        certificate_hashes: Vec<[u8; 32]>,
48    },
49    Iroh {
50        node_id: [u8; 32],
51    },
52}
53
54impl NativeAnnouncementReach {
55    pub fn socket_kind(&self) -> &'static str {
56        match self {
57            Self::Quic { .. } => "quic",
58            Self::Iroh { .. } => "iroh",
59        }
60    }
61
62    pub fn endpoint(&self) -> String {
63        match self {
64            Self::Quic {
65                address,
66                server_name,
67                certificate_hashes,
68            } => {
69                if certificate_hashes.is_empty() {
70                    format!("quic://{server_name}:{address}")
71                } else {
72                    use base64::Engine as _;
73                    let hashes = certificate_hashes
74                        .iter()
75                        .map(|hash| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash))
76                        .collect::<Vec<_>>()
77                        .join(",");
78                    format!("quic://{server_name}:{address}#{hashes}")
79                }
80            }
81            Self::Iroh { node_id } => format!("iroh://{}", lowercase_hex(node_id)),
82        }
83    }
84}
85
86fn lowercase_hex(bytes: &[u8]) -> String {
87    const HEX: &[u8; 16] = b"0123456789abcdef";
88    let mut encoded = String::with_capacity(bytes.len() * 2);
89    for byte in bytes {
90        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
91        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
92    }
93    encoded
94}
95
96/// Complete, already-validated native announcement ready for publication.
97pub struct NativeAnnouncementRequest {
98    pub cancellation: tokio_util::sync::CancellationToken,
99    pub service_name: String,
100    pub reach: NativeAnnouncementReach,
101    pub signing_key: SigningKey,
102    pub service_jwt: Option<String>,
103    pub discovery_verifying_key: VerifyingKey,
104    pub service_did: hyprstream_rpc::identity::Did,
105    pub capabilities: Vec<String>,
106    pub accepted_state_digest: Vec<u8>,
107    pub accepted_state_epoch: u64,
108    pub response_key_id: String,
109    pub request_kem_key_id: String,
110    pub request_kem_recipient: Vec<u8>,
111    pub expires_at_unix_ms: i64,
112}
113
114impl NativeAnnouncementRequest {
115    /// Re-project the complete authority bundle, retaining this bound service's
116    /// identity, signer and reach. A successor may renew authority but cannot
117    /// silently switch the running service to a different identity.
118    pub fn refresh_from_accepted_state(
119        &mut self,
120        state: &hyprstream_pds::at9p_duplicity::AcceptedAt9pState,
121    ) -> anyhow::Result<()> {
122        anyhow::ensure!(
123            state.did == self.service_did.to_string(),
124            "announcement identity changed"
125        );
126        let accepted = NativeServiceAnnouncement::from_accepted_state(
127            &self.service_name,
128            &self.signing_key,
129            state,
130        )?;
131        self.capabilities = accepted.capabilities;
132        self.accepted_state_digest = accepted.accepted_state_digest.to_vec();
133        self.accepted_state_epoch = accepted.accepted_state_epoch;
134        self.response_key_id = accepted.response_key_id;
135        self.request_kem_key_id = accepted.request_kem_key_id;
136        self.request_kem_recipient = accepted.request_kem_recipient.encode();
137        self.expires_at_unix_ms = accepted.accepted_state_expires_at_unix_ms;
138        Ok(())
139    }
140}
141
142pub type NativeAnnouncementPublisher =
143    Arc<dyn Fn(NativeAnnouncementRequest) -> anyhow::Result<()> + Send + Sync + 'static>;
144
145#[allow(clippy::too_many_arguments)]
146fn publish_native_announcement(
147    publisher: Option<NativeAnnouncementPublisher>,
148    cancellation: tokio_util::sync::CancellationToken,
149    service_name: String,
150    reach: NativeAnnouncementReach,
151    signing_key: SigningKey,
152    service_jwt: Option<String>,
153    policy_verifying_key: VerifyingKey,
154    discovery_verifying_key: VerifyingKey,
155    accepted: Option<NativeServiceAnnouncement>,
156) -> anyhow::Result<()> {
157    // Check if JWT needs renewal (within 2 days of expiry, or missing).
158    let needs_renewal = service_jwt.as_ref().is_none_or(|jwt| {
159        let parts: Vec<&str> = jwt.split('.').collect();
160        if parts.len() != 3 {
161            return true;
162        }
163        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
164        if let Ok(payload) = URL_SAFE_NO_PAD.decode(parts[1]) {
165            if let Ok(claims) = serde_json::from_slice::<serde_json::Value>(&payload) {
166                if let Some(exp) = claims["exp"].as_i64() {
167                    return chrono::Utc::now().timestamp() > exp - 2 * 86_400;
168                }
169            }
170        }
171        true
172    });
173
174    let Some(accepted) = accepted else {
175        anyhow::bail!(
176            "refusing production network announcement for '{service_name}': \
177             accepted native identity/KEM bundle is unavailable"
178        );
179    };
180    accepted.validate(&service_name, &signing_key.verifying_key())?;
181    if needs_renewal {
182        tracing::warn!(
183            "Service JWT for '{service_name}' expired or near-expiry. \
184             Renewal RPC pending capnp schema update. Re-run wizard to refresh JWTs."
185        );
186        let _ = policy_verifying_key;
187    }
188    let Some(publish) = publisher else {
189        anyhow::bail!(
190            "refusing production network announcement for '{service_name}': publisher is unavailable"
191        );
192    };
193    publish(NativeAnnouncementRequest {
194        cancellation,
195        service_name,
196        reach,
197        signing_key,
198        service_jwt,
199        discovery_verifying_key,
200        service_did: accepted.service_did,
201        capabilities: accepted.capabilities,
202        accepted_state_digest: accepted.accepted_state_digest.to_vec(),
203        accepted_state_epoch: accepted.accepted_state_epoch,
204        response_key_id: accepted.response_key_id,
205        request_kem_key_id: accepted.request_kem_key_id,
206        request_kem_recipient: accepted.request_kem_recipient.encode(),
207        expires_at_unix_ms: accepted.accepted_state_expires_at_unix_ms,
208    })
209}
210
211/// Complete native announcement material verified against one accepted state.
212#[derive(Clone)]
213pub struct NativeServiceAnnouncement {
214    service_did: hyprstream_rpc::identity::Did,
215    capabilities: Vec<String>,
216    accepted_state_digest: [u8; 64],
217    accepted_state_epoch: u64,
218    accepted_state_expires_at_unix_ms: i64,
219    response_key_id: String,
220    response_verifying_key: [u8; 32],
221    request_kem_key_id: String,
222    request_kem_recipient: hyprstream_rpc::crypto::hybrid_kem::RecipientPublic,
223}
224
225impl NativeServiceAnnouncement {
226    /// Build the native Iroh `moql` admission proof from this exact
227    /// checkpoint-verified accepted-state projection. The caller's signer must
228    /// still be the accepted response key; no credential is synthesized.
229    pub fn moql_admission_proof(
230        &self,
231        signer: &SigningKey,
232    ) -> anyhow::Result<hyprstream_rpc::transport::moql_admission::MoqlAdmissionProof> {
233        anyhow::ensure!(
234            self.response_verifying_key == signer.verifying_key().to_bytes(),
235            "admission signer is not the accepted current response key"
236        );
237        let ml_dsa_65 = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(signer);
238        let ml_dsa65 = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&ml_dsa_65);
239        Ok(
240            hyprstream_rpc::transport::moql_admission::MoqlAdmissionProof {
241                did: self.service_did.to_string(),
242                ed25519: signer.clone(),
243                ml_dsa_65,
244                expected_server: hyprstream_rpc::stream_info::MoqlServerIdentity {
245                    did: self.service_did.to_string(),
246                    epoch: self.accepted_state_epoch,
247                    head_digest: self.accepted_state_digest.to_vec(),
248                    expires_at_unix_ms: self.accepted_state_expires_at_unix_ms,
249                    ed25519: self.response_verifying_key,
250                    ml_dsa65,
251                },
252            },
253        )
254    }
255    /// Project a complete native announcement from the opaque #1004 accepted
256    /// state. The local service key must be the accepted current key and the
257    /// named service must be present in that exact state.
258    pub fn from_accepted_state(
259        service_name: &str,
260        signer: &SigningKey,
261        state: &hyprstream_pds::at9p_duplicity::AcceptedAt9pState,
262    ) -> anyhow::Result<Self> {
263        anyhow::ensure!(
264            state
265                .current
266                .services
267                .iter()
268                .any(|entry| entry.id == format!("#{service_name}")),
269            "accepted state does not authorize service {service_name}"
270        );
271        // `subjectKeys` is a published set (#1188 / #1183): the local service
272        // signer must be *one of* the accepted current response keys, not
273        // positionally `first()`. An overlap-rotating identity publishes several
274        // usable keys at once; a service holding any of them is authorized.
275        let derived_ml_dsa65 = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(
276            &hyprstream_rpc::node_identity::derive_mesh_mldsa_key(signer),
277        );
278        anyhow::ensure!(
279            state.current.subject_keys.iter().any(|key| {
280                key.ed25519_pub.as_slice() == signer.verifying_key().as_bytes()
281                    && key.mldsa65_pub == derived_ml_dsa65
282            }),
283            "service signer is not an accepted current hybrid response key"
284        );
285        let expires_at = state.expires_at.as_deref().ok_or_else(|| {
286            anyhow::anyhow!("genesis-only accepted state has no bounded production expiry")
287        })?;
288        let expires_at = chrono::DateTime::parse_from_rfc3339(expires_at)?.timestamp_millis();
289        let did = hyprstream_rpc::identity::Did::from(state.did.clone());
290        let recipient = hyprstream_rpc::node_identity::derive_mesh_kem_recipient(signer)?.public();
291        let announcement = Self {
292            service_did: did.clone(),
293            capabilities: if matches!(service_name, "event" | "streams") {
294                vec!["hyprstream-moq/1".to_owned()]
295            } else {
296                vec!["hyprstream-rpc/1".to_owned(), "hyprstream-moq/1".to_owned()]
297            },
298            accepted_state_digest: state.head_digest,
299            accepted_state_epoch: state.epoch,
300            accepted_state_expires_at_unix_ms: expires_at,
301            response_key_id: format!("{did}#response"),
302            response_verifying_key: signer.verifying_key().to_bytes(),
303            request_kem_key_id: format!("{did}#mesh-kem"),
304            request_kem_recipient: recipient,
305        };
306        announcement.validate(service_name, &signer.verifying_key())?;
307        Ok(announcement)
308    }
309
310    fn validate(&self, service_name: &str, signer: &VerifyingKey) -> anyhow::Result<()> {
311        anyhow::ensure!(
312            self.service_did.is_did_at9p(),
313            "native announcement requires did:at9p identity"
314        );
315        anyhow::ensure!(
316            !service_name.is_empty()
317                && self.capabilities.iter().any(|c| c
318                    == if matches!(service_name, "event" | "streams") {
319                        "hyprstream-moq/1"
320                    } else {
321                        "hyprstream-rpc/1"
322                    }),
323            "native announcement lacks canonical service capability"
324        );
325        anyhow::ensure!(
326            self.response_verifying_key == signer.to_bytes(),
327            "accepted response key does not match service signer"
328        );
329        anyhow::ensure!(
330            self.response_key_id
331                .starts_with(&format!("{}#", self.service_did)),
332            "response key id crosses service authority"
333        );
334        anyhow::ensure!(
335            self.request_kem_key_id
336                .starts_with(&format!("{}#", self.service_did)),
337            "KEM key id crosses service authority"
338        );
339        anyhow::ensure!(
340            self.request_kem_recipient.suite_id
341                == hyprstream_rpc::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
342            "native announcement requires hybrid KEM suite"
343        );
344        self.request_kem_recipient.validate()?;
345        anyhow::ensure!(
346            self.accepted_state_epoch > 0
347                && self.accepted_state_expires_at_unix_ms > chrono::Utc::now().timestamp_millis(),
348            "accepted state is unbounded or expired"
349        );
350        Ok(())
351    }
352}
353
354/// Shared QUIC/WebTransport configuration for all services.
355///
356/// Contains TLS materials and base settings shared across services.
357/// Each service gets its own port via `for_service()`.
358#[derive(Clone)]
359pub struct QuicSharedConfig {
360    /// DER-encoded TLS certificate chain (leaf first, then intermediates/CA)
361    pub cert_chain: Vec<Vec<u8>>,
362    /// SHA-256 leaf pins for short-lived self-signed WebTransport certificates.
363    /// Empty for WebPKI certificates, which authenticate through the CA chain.
364    pub certificate_hashes: Vec<[u8; 32]>,
365    /// DER-encoded TLS private key — zeroed on drop.
366    pub key_der: Zeroizing<Vec<u8>>,
367    /// Base IP address for binding (e.g., 0.0.0.0)
368    pub base_ip: std::net::IpAddr,
369    /// TLS server name (for certificate validation and discovery)
370    pub server_name: String,
371    /// OAuth issuer URL for RFC 9728 protected resource metadata
372    pub oauth_issuer_url: Option<String>,
373    /// JWT verifying key (derived from root via HKDF "hyprstream-jwt-v1").
374    /// Published as `x_root_pubkey` in RFC 9728 metadata for client-side trust pinning.
375    pub jwt_verifying_key: Option<ed25519_dalek::VerifyingKey>,
376    /// #410/#282: bind an iroh substrate (ALPNs `hyprstream-rpc/1` + `moql`)
377    /// as the PRIMARY production transport, in parallel to the quinn endpoint
378    /// (kept for back-compat), for every QUIC-enabled service. On by default;
379    /// an operator opts out via `[quic] iroh = false` to run quinn-only (legacy).
380    pub iroh_enabled: bool,
381    pub iroh_required: bool,
382    /// #358: the producer-chosen moq RELAY every QUIC-enabled service on this node
383    /// rendezvouses through, in wire-reach form. `None` = direct-only. Sourced
384    /// from the relay DID transport entry (default: the PDS / federation anchor)
385    /// decoded by [`hyprstream_rpc::service_entry`]; see
386    /// [`hyprstream_rpc::moq_stream::relay_reach_from_decoded`]. Threaded into each
387    /// service's [`QuicLoopConfig`] so the spawner advertises a `Role::Relay` reach
388    /// and links the origin UP to the relay.
389    pub moq_relay: Option<hyprstream_rpc::stream_info::TransportConfig>,
390    /// Resolver-verified identity of the independently operated relay. It is
391    /// intentionally not inferred from the producing service's proof.
392    pub moq_relay_server_identity: Option<hyprstream_rpc::stream_info::MoqlServerIdentity>,
393    /// Application-owned publisher. Keeping this callback here avoids making
394    /// orchestration depend on the Discovery implementation crate.
395    pub native_announcement_publisher: Option<NativeAnnouncementPublisher>,
396    /// #1027: optional inside-carrier `moql` admission authenticator holding
397    /// the daemon-owned accepted-state/currentness authority and the
398    /// operator-controlled subject→tenant resolver. Threaded unchanged into
399    /// every service's `QuicLoopConfig`; the spawner installs it on the iroh
400    /// `moql` handler. `None` keeps the fail-closed anonymous posture.
401    pub moq_admission:
402        Option<Arc<hyprstream_rpc::transport::moql_admission::MoqlAdmissionAuthenticator>>,
403    /// Optional service-owned decision for remote MoQL ingress. Admission and
404    /// tenant resolution never imply this producer/relay role; `None` leaves
405    /// every admitted peer read-only.
406    pub moq_ingress_authorizer:
407        Option<hyprstream_rpc::transport::iroh_moq::SharedIngressAuthorizer>,
408    /// Native client's accepted-state-bound proof for authenticated Iroh `moql`
409    /// dials. Quinn/WebTransport uses its distinct CONNECT authentication path.
410    pub moq_admission_proof: Option<hyprstream_rpc::transport::moql_admission::MoqlAdmissionProof>,
411}
412
413impl QuicSharedConfig {
414    /// Build a per-service `QuicLoopConfig` with the given port.
415    ///
416    /// Port 0 = ephemeral (OS-assigned).
417    pub fn for_service(
418        &self,
419        service_name: &str,
420        port: u16,
421    ) -> hyprstream_rpc::service::QuicLoopConfig {
422        let bind_addr = std::net::SocketAddr::new(self.base_ip, port);
423        let metadata = self.oauth_issuer_url.as_ref().map(|issuer| {
424            let mut meta = serde_json::json!({
425                "resource": format!("https://{}/{}", self.server_name, service_name),
426                "authorization_servers": [issuer],
427                "bearer_methods_supported": ["header"],
428            });
429            // Publish root pubkey for client-side trust pinning (TOFU)
430            if let Some(ref vk) = self.jwt_verifying_key {
431                use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
432                #[allow(clippy::unwrap_used)] // meta is always a JSON object
433                meta.as_object_mut().unwrap().insert(
434                    "x_root_pubkey".to_owned(),
435                    serde_json::Value::String(URL_SAFE_NO_PAD.encode(vk.to_bytes())),
436                );
437            }
438            meta.to_string().into_bytes()
439        });
440        hyprstream_rpc::service::QuicLoopConfig {
441            announcement_cancellation: tokio_util::sync::CancellationToken::new(),
442            cert_chain: self.cert_chain.clone(),
443            key_der: Zeroizing::new((*self.key_der).clone()),
444            bind_addr,
445            server_name: self.server_name.clone(),
446            protected_resource_json: metadata,
447            on_quic_bound: None,
448            // #282: bind iroh in parallel when the deployment opted in.
449            iroh_enabled: self.iroh_enabled,
450            iroh_required: self.iroh_required,
451            on_iroh_bound: None,
452            // #358: thread the producer-chosen relay through so the spawner
453            // advertises a Role::Relay reach + links the origin up to the relay.
454            moq_relay: self.moq_relay.clone(),
455            moq_relay_server_identity: self.moq_relay_server_identity.clone(),
456            // #1027: thread the daemon-owned moql admission authenticator
457            // through so the spawner installs it on the iroh `moql` handler.
458            moq_admission: self
459                .moq_admission
460                .as_ref()
461                .map(|admission| Arc::new(admission.for_server())),
462            moq_ingress_authorizer: self.moq_ingress_authorizer.clone(),
463            moq_admission_proof: self.moq_admission_proof.clone(),
464        }
465    }
466
467    /// Build a per-service `QuicLoopConfig` with an announce callback.
468    ///
469    /// After binding, callbacks announce each bound native carrier to Discovery.
470    ///
471    /// If the service JWT is close to expiry, the callback requests a renewed JWT
472    /// from PolicyService via the `issueToken` RPC (no local CA key needed).
473    pub fn for_service_with_announce(
474        &self,
475        service_name: &str,
476        port: u16,
477        signing_key: hyprstream_rpc::prelude::SigningKey,
478        service_jwt: Option<String>,
479        policy_verifying_key: VerifyingKey,
480        discovery_verifying_key: VerifyingKey,
481        accepted: Option<NativeServiceAnnouncement>,
482    ) -> hyprstream_rpc::service::QuicLoopConfig {
483        let mut config = self.for_service(service_name, port);
484        let publisher = self.native_announcement_publisher.clone();
485        let quic_signing_key = signing_key.clone();
486        let quic_jwt = service_jwt.clone();
487        let quic_accepted = accepted.clone();
488        let quic_certificate_hashes = self.certificate_hashes.clone();
489        let quic_cancellation = config.announcement_cancellation.clone();
490        config.on_quic_bound = Some(Box::new(move |svc_name, addr, sn| {
491            if let Err(error) = publish_native_announcement(
492                publisher.clone(),
493                quic_cancellation,
494                svc_name,
495                NativeAnnouncementReach::Quic {
496                    address: addr,
497                    server_name: sn,
498                    certificate_hashes: quic_certificate_hashes.clone(),
499                },
500                quic_signing_key.clone(),
501                quic_jwt.clone(),
502                policy_verifying_key,
503                discovery_verifying_key,
504                quic_accepted.clone(),
505            ) {
506                tracing::warn!("QUIC native announcement was not published: {error}");
507            }
508        }));
509        let iroh_publisher = self.native_announcement_publisher.clone();
510        let iroh_cancellation = config.announcement_cancellation.clone();
511        config.on_iroh_bound = Some(Box::new(move |svc_name, node_id| {
512            publish_native_announcement(
513                iroh_publisher.clone(),
514                iroh_cancellation,
515                svc_name,
516                NativeAnnouncementReach::Iroh { node_id },
517                signing_key.clone(),
518                service_jwt.clone(),
519                policy_verifying_key,
520                discovery_verifying_key,
521                accepted.clone(),
522            )
523        }));
524        config
525    }
526}
527
528/// Context for service creation.
529///
530/// Contains all shared resources needed by services during initialization.
531/// Passed to factory functions registered via `#[service_factory]`.
532pub struct ServiceContext {
533    /// Server's signing key (for JWT generation)
534    signing_key: SigningKey,
535
536    /// Server's verifying key (for envelope/JWT verification)
537    verifying_key: VerifyingKey,
538
539    /// Identity provider for purpose-keyed signing
540    identity_provider: Arc<hyprstream_rpc::node_identity::NodeIdentityProvider>,
541
542    /// Launcher-proven single service hosted by this process; never derived from transport.
543    dedicated_process_service: Option<String>,
544
545    /// Whether running in IPC mode (vs inproc)
546    ipc: bool,
547
548    /// Models directory path
549    models_dir: std::path::PathBuf,
550
551    /// Shared QUIC/WebTransport config (TLS materials + base settings).
552    /// Per-service ports are resolved via `into_spawnable_quic()`.
553    quic_shared: Option<QuicSharedConfig>,
554
555    /// OAuth issuer URL for protected resource metadata (RFC 9728).
556    /// When set, QUIC services serve `.well-known/oauth-protected-resource`.
557    oauth_issuer_url: Option<String>,
558
559    /// Shared federation key resolver (None when no trusted_issuers are configured).
560    federation_key_source: Option<Arc<dyn hyprstream_rpc::auth::FederationKeySource>>,
561
562    /// Per-service signing keys (independent Ed25519 keypairs).
563    ///
564    /// Populated from:
565    /// - Single-process: generated in memory at startup
566    /// - Multi-process: loaded from per-service credential files
567    service_keys: HashMap<String, SigningKey>,
568
569    native_announcements: HashMap<String, NativeServiceAnnouncement>,
570
571    /// CA verifying key (trust anchor for verifying service JWTs).
572    ///
573    /// In single-process mode, this is derived from the root key.
574    /// In multi-process mode, this is loaded from the ca-pubkey credential.
575    ca_verifying_key: Option<VerifyingKey>,
576
577    /// Optional JWKS fetcher for JWKS-backed key resolution.
578    /// When set, `cluster_key_source()` returns `JwksKeySource(Mode::Isolated)`
579    /// instead of `ClusterKeySource`.
580    jwks_fetcher: Option<hyprstream_rpc::auth::JwksFetcher>,
581
582    /// Shared ML-DSA-65 verifying keys for PQ-hybrid JWT verification.
583    /// Updated by the rotation task; shared across all key sources.
584    ///
585    /// Uses `std::sync::RwLock` to match the cross-crate `Arc<RwLock<..>>`
586    /// contract with `hyprstream::auth::key_rotation` and `JwtKeySource`.
587    #[allow(clippy::disallowed_types)]
588    ml_dsa_verifying_keys:
589        std::sync::Arc<std::sync::RwLock<Vec<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey>>>,
590
591    /// The CA's derived ML-DSA-65 verifying key — the post-quantum half of the
592    /// CA JWT composite pair. Paired with `ca_verifying_key` it lets the key
593    /// sources resolve the composite kid of hybrid service JWTs.
594    ///
595    /// In multi-process mode, loaded from the `ca-mldsa-pubkey` credential.
596    ca_ml_dsa_verifying_key: Option<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey>,
597
598    /// Explicitly resolved credentials/secrets directory — the location the
599    /// loading process actually selected (honoring `--config [secrets].path`
600    /// and the `HYPRSTREAM__SECRETS__PATH` override). `None` lets factory
601    /// code fall back to the config-free resolver, preserving compatibility
602    /// for constructors that never carried a config handle.
603    secrets_dir: Option<std::path::PathBuf>,
604}
605
606/// Owned callback joining carrier binding to the signed announcement lifecycle.
607pub type NativeIrohAnnouncementCallback =
608    Arc<dyn Fn(tokio_util::sync::CancellationToken, [u8; 32]) -> anyhow::Result<()> + Send + Sync>;
609
610impl ServiceContext {
611    /// Return an accepted-state-bound admission proof for a service that was
612    /// checkpoint-authorized for native network startup.
613    pub fn moql_admission_proof(
614        &self,
615        service_name: &str,
616    ) -> anyhow::Result<Option<hyprstream_rpc::transport::moql_admission::MoqlAdmissionProof>> {
617        self.native_announcements
618            .get(service_name)
619            .map(|announcement| {
620                announcement.moql_admission_proof(&self.service_signing_key(service_name))
621            })
622            .transpose()
623    }
624    /// Publication callback for a MoQ-only service which has no RPC loop.
625    pub fn native_iroh_announcement_callback(
626        &self,
627        service_name: &str,
628    ) -> anyhow::Result<NativeIrohAnnouncementCallback> {
629        let shared = self
630            .quic_shared
631            .as_ref()
632            .ok_or_else(|| anyhow::anyhow!("native Event configuration missing"))?;
633        let publisher = shared.native_announcement_publisher.clone();
634        anyhow::ensure!(publisher.is_some(), "native announcement publisher missing");
635        let accepted = self.native_announcements.get(service_name).cloned();
636        anyhow::ensure!(
637            accepted.is_some(),
638            "native accepted announcement missing for {service_name}"
639        );
640        let signing_key = self.service_signing_key(service_name);
641        let trust = crate::service::trust_store::global_trust_store();
642        let jwt = trust
643            .get(&signing_key.verifying_key())
644            .and_then(|att| att.jwt);
645        let policy = trust
646            .resolve_one("policy")
647            .ok_or_else(|| anyhow::anyhow!("policy key missing"))?;
648        let discovery = trust
649            .resolve_one("discovery")
650            .ok_or_else(|| anyhow::anyhow!("discovery key missing"))?;
651        let service_name = service_name.to_owned();
652        Ok(Arc::new(move |cancellation, node_id| {
653            publish_native_announcement(
654                publisher.clone(),
655                cancellation,
656                service_name.clone(),
657                NativeAnnouncementReach::Iroh { node_id },
658                signing_key.clone(),
659                jwt.clone(),
660                policy,
661                discovery,
662                accepted.clone(),
663            )
664        }))
665    }
666
667    /// Create a new service context.
668    pub fn new(
669        signing_key: SigningKey,
670        verifying_key: VerifyingKey,
671        ipc: bool,
672        models_dir: std::path::PathBuf,
673    ) -> Self {
674        let identity_provider = Arc::new(hyprstream_rpc::node_identity::NodeIdentityProvider::new(
675            &signing_key,
676        ));
677        Self {
678            signing_key,
679            verifying_key,
680            identity_provider,
681            dedicated_process_service: None,
682            ipc,
683            models_dir,
684            quic_shared: None,
685            oauth_issuer_url: None,
686            federation_key_source: None,
687            service_keys: HashMap::new(),
688            native_announcements: HashMap::new(),
689            ca_verifying_key: None,
690            jwks_fetcher: None,
691            ml_dsa_verifying_keys: {
692                #[allow(clippy::disallowed_types)]
693                std::sync::Arc::new(std::sync::RwLock::new(Vec::new()))
694            },
695            ca_ml_dsa_verifying_key: None,
696            secrets_dir: None,
697        }
698    }
699
700    /// The launcher may set this only after enforcing one service per process.
701    /// It authorizes that service to terminate the process on an unjoinable worker.
702    pub fn with_dedicated_process_service(mut self, service: String) -> Self {
703        self.dedicated_process_service = Some(service);
704        self
705    }
706
707    pub fn is_dedicated_process_for(&self, service: &str) -> bool {
708        self.dedicated_process_service.as_deref() == Some(service)
709    }
710
711    /// Carry the explicitly resolved credentials directory into factories.
712    ///
713    /// Startup resolves `[secrets].path` from the loaded config and reads the
714    /// retained signing key and service JWT from that directory; factory-time
715    /// helpers (key registration, JWT renewal) have no config handle of their
716    /// own and must not re-resolve from env/defaults, or a custom
717    /// `--config [secrets].path` deployment would work at startup and then
718    /// renew against the wrong directory.
719    pub fn with_secrets_dir(mut self, dir: std::path::PathBuf) -> Self {
720        self.secrets_dir = Some(dir);
721        self
722    }
723
724    /// The explicitly resolved credentials directory, when the constructing
725    /// process carried one.
726    pub fn secrets_dir(&self) -> Option<&std::path::Path> {
727        self.secrets_dir.as_deref()
728    }
729
730    /// Set the shared ML-DSA-65 verifying keys for PQ-hybrid JWT verification.
731    #[allow(clippy::disallowed_types)]
732    pub fn set_ml_dsa_verifying_keys(
733        &mut self,
734        keys: std::sync::Arc<std::sync::RwLock<Vec<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey>>>,
735    ) {
736        self.ml_dsa_verifying_keys = keys;
737    }
738
739    /// Get a clone of the shared ML-DSA verifying keys Arc.
740    #[allow(clippy::disallowed_types)]
741    pub fn ml_dsa_verifying_keys_arc(
742        &self,
743    ) -> std::sync::Arc<std::sync::RwLock<Vec<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey>>> {
744        self.ml_dsa_verifying_keys.clone()
745    }
746
747    /// Add a per-service independent signing key.
748    ///
749    /// In single-process mode, these are generated in memory at startup.
750    /// In multi-process mode, these are loaded from per-service credential files.
751    pub fn with_service_key(mut self, service_name: &str, signing_key: SigningKey) -> Self {
752        self.service_keys
753            .insert(service_name.to_owned(), signing_key);
754        self
755    }
756
757    pub fn with_native_announcement(
758        mut self,
759        service_name: impl Into<String>,
760        announcement: NativeServiceAnnouncement,
761    ) -> Self {
762        self.native_announcements
763            .insert(service_name.into(), announcement);
764        self
765    }
766
767    /// Bulk-register service keys from an iterator.
768    pub fn with_service_keys<I>(mut self, keys: I) -> Self
769    where
770        I: IntoIterator<Item = (String, SigningKey)>,
771    {
772        for (name, sk) in keys {
773            self.service_keys.insert(name, sk);
774        }
775        self
776    }
777
778    /// Set the CA verifying key (trust anchor for verifying service JWTs).
779    pub fn with_ca_verifying_key(mut self, key: VerifyingKey) -> Self {
780        self.ca_verifying_key = Some(key);
781        self
782    }
783
784    /// Set the CA's derived ML-DSA-65 verifying key (the post-quantum half of
785    /// the CA JWT composite pair used for hybrid service JWTs).
786    pub fn with_ca_ml_dsa_verifying_key(
787        mut self,
788        key: hyprstream_rpc::crypto::pq::MlDsaVerifyingKey,
789    ) -> Self {
790        self.ca_ml_dsa_verifying_key = Some(key);
791        self
792    }
793
794    /// Swap the signing key to an independent per-service key.
795    ///
796    /// Used in IPC mode for non-policy services: replaces the root/CA key
797    /// with the service's own independent Ed25519 key. The CA key is no
798    /// longer accessible via `signing_key()` after this call.
799    pub fn swap_signing_key(mut self, new_key: SigningKey) -> Self {
800        self.verifying_key = new_key.verifying_key();
801        self.identity_provider = Arc::new(
802            hyprstream_rpc::node_identity::NodeIdentityProvider::new(&new_key),
803        );
804        self.signing_key = new_key;
805        self
806    }
807
808    /// Generate independent Ed25519 keypairs for all listed services and
809    /// issue CA-signed service JWTs in memory.
810    ///
811    /// Used by single-process mode where all services run in one process.
812    /// The root signing key serves as the CA key — PolicyService will use it
813    /// directly (it IS the CA), while all other services get independent keys.
814    ///
815    /// Populates `service_keys`, `ca_verifying_key`, and the global trust store
816    /// from the generated materials.
817    pub fn generate_independent_service_keys(self, service_names: &[String]) -> Self {
818        let ca_signing_key = hyprstream_rpc::node_identity::derive_purpose_key(
819            &self.signing_key,
820            "hyprstream-jwt-v1",
821        );
822        let ca_verifying_key = ca_signing_key.verifying_key();
823        // The CA JWT composite pair: service JWTs must be hybrid because the
824        // dispatch plane enforces a Hybrid crypto policy with no bypass. The
825        // ML-DSA-65 half is derived from the CA JWT signing key so the pair
826        // stays a single Ed25519 secret.
827        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca_signing_key);
828        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
829
830        let mut ctx = self
831            .with_ca_verifying_key(ca_verifying_key)
832            .with_ca_ml_dsa_verifying_key(ca_pq_vk.clone());
833
834        let now = chrono::Utc::now().timestamp();
835        let expiry = now + 7 * 86_400; // 7 days
836
837        // Capture root signing/verifying keys before ctx is moved in the loop.
838        let root_signing_key = ctx.signing_key.clone();
839        let root_verifying_key = ctx.verifying_key();
840
841        // Populate the global trust store with all service keys.
842        // The trust store is the source of truth for key-centric identity:
843        // keys ARE identity, service names are authorization scopes.
844        let trust = crate::service::trust_store::global_trust_store();
845
846        // Remove any stale entries for services we're about to regenerate.
847        // This happens when CLI mode loaded bootstrap pubkeys from disk (no JWTs)
848        // before the service start handler generates fresh in-memory keys with JWTs.
849        for name in service_names {
850            if let Some(stale_vk) = trust.resolve_one(name) {
851                let stale = trust.get(&stale_vk);
852                if stale.as_ref().is_some_and(|a| a.jwt.is_none()) {
853                    tracing::debug!(service = name, "Removing stale trust store entry (no JWT)");
854                    trust.remove(&stale_vk);
855                }
856            }
857        }
858
859        for name in service_names {
860            if name == "policy" {
861                // PolicyService uses the root key directly (it IS the CA).
862                // Register its signing key in the registry
863                // so service_signing_key("policy") works.
864                ctx = ctx.with_service_key(name, root_signing_key.clone());
865
866                // PolicyService key never expires — it IS the trust anchor.
867                trust.insert(
868                    root_verifying_key,
869                    crate::service::trust_store::Attestation {
870                        scopes: std::iter::once("policy".to_owned()).collect(),
871                        subject: None,
872                        jwt: None,
873                        expires_at: 0,
874                        attested_by: None,
875                    },
876                );
877                continue;
878            }
879
880            // Generate independent Ed25519 keypair
881            let service_key = SigningKey::generate(&mut rand::rngs::OsRng);
882            let service_vk = service_key.verifying_key();
883
884            // Issue service JWT (CA-signed certificate binding name → pubkey).
885            // Set iss and aud to match PolicyService's local_issuer_url and
886            // default_audience so it recognizes these CA-signed tokens as local.
887            let oauth_issuer = ctx.oauth_issuer_url().map(str::to_owned);
888            let mut claims =
889                hyprstream_rpc::auth::Claims::new(format!("service:{name}"), now, expiry)
890                    .with_cnf_jwk(service_vk.as_bytes());
891            if let Some(ref iss) = oauth_issuer {
892                claims = claims
893                    .with_issuer(iss.clone())
894                    .with_audience(Some(iss.clone()));
895            }
896
897            let jwt = hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(
898                &claims,
899                &ca_signing_key,
900                &ca_pq,
901                &ca_pq_vk,
902            );
903
904            ctx = ctx.with_service_key(name, service_key);
905
906            // Register this service's key in the trust store.
907            trust.insert(
908                service_vk,
909                crate::service::trust_store::Attestation {
910                    scopes: std::iter::once(name.clone()).collect(),
911                    subject: None,
912                    jwt: Some(jwt),
913                    expires_at: expiry,
914                    attested_by: Some(root_verifying_key.to_bytes()),
915                },
916            );
917        }
918
919        ctx
920    }
921
922    /// Set the shared QUIC/WebTransport configuration.
923    ///
924    /// Per-service ports are resolved via `into_spawnable_quic()`.
925    pub fn with_quic(mut self, config: QuicSharedConfig) -> Self {
926        self.quic_shared = Some(config);
927        self
928    }
929
930    /// Get the shared QUIC config (if enabled).
931    pub fn quic_shared(&self) -> Option<&QuicSharedConfig> {
932        self.quic_shared.as_ref()
933    }
934
935    /// Check if QUIC/WebTransport is enabled.
936    pub fn has_quic(&self) -> bool {
937        self.quic_shared.is_some()
938    }
939
940    pub fn iroh_required(&self) -> bool {
941        self.quic_shared
942            .as_ref()
943            .is_some_and(|config| config.iroh_required)
944    }
945
946    /// Set the OAuth issuer URL for RFC 9728 metadata.
947    pub fn with_oauth_issuer(mut self, url: String) -> Self {
948        self.oauth_issuer_url = Some(url);
949        self
950    }
951
952    /// Get the OAuth issuer URL (if configured).
953    pub fn oauth_issuer_url(&self) -> Option<&str> {
954        self.oauth_issuer_url.as_deref()
955    }
956
957    /// Get the federation key source (if configured).
958    pub fn federation_key_source(
959        &self,
960    ) -> Option<Arc<dyn hyprstream_rpc::auth::FederationKeySource>> {
961        self.federation_key_source.clone()
962    }
963
964    /// Set the shared federation key source for multi-issuer ZMQ token acceptance.
965    pub fn with_federation_key_source(
966        mut self,
967        src: Arc<dyn hyprstream_rpc::auth::FederationKeySource>,
968    ) -> Self {
969        self.federation_key_source = Some(src);
970        self
971    }
972
973    /// Get the root signing key.
974    ///
975    /// **Only PolicyService (the CA) should call this.** All other services must
976    /// use `service_signing_key("name")` for per-service key derivation. The root
977    /// key is needed by PolicyService to issue service JWTs and by node-level
978    /// operations (main.rs) for QuicSharedConfig construction.
979    ///
980    /// If you're writing a factory function and the service name is not "policy",
981    /// use `service_signing_key(service_name)` instead.
982    #[inline]
983    pub fn signing_key(&self) -> &SigningKey {
984        &self.signing_key
985    }
986
987    /// Get the signing key for a specific service.
988    ///
989    /// Lookup order:
990    /// 1. `service_keys` registry (independent keypair per service)
991    /// 2. PolicyService special case (returns root key — it IS the CA)
992    /// 3. "multi" fallback (multi-service IPC mode shares one key for all services)
993    ///
994    /// Panics if no key is registered. Ensure `generate_independent_service_keys()`
995    /// was called (inproc) or the service's own key was loaded from credentials (IPC).
996    pub fn service_signing_key(&self, service_name: &str) -> SigningKey {
997        if let Some(sk) = self.service_keys.get(service_name) {
998            return sk.clone();
999        }
1000        if service_name == "policy" {
1001            return self.signing_key.clone();
1002        }
1003        // Multi-service IPC mode registers a single "multi" key; fall back to it.
1004        if let Some(sk) = self.service_keys.get("multi") {
1005            return sk.clone();
1006        }
1007        panic!(
1008            "service_signing_key({service_name}): no independent key registered. \
1009             Ensure generate_independent_service_keys() was called (inproc) or \
1010             the service's signing-key credential was loaded (IPC mode)."
1011        );
1012    }
1013
1014    /// Get the CA verifying key (trust anchor).
1015    pub fn ca_verifying_key(&self) -> Option<VerifyingKey> {
1016        self.ca_verifying_key
1017    }
1018
1019    /// Get the verifying key.
1020    pub fn verifying_key(&self) -> VerifyingKey {
1021        self.verifying_key
1022    }
1023
1024    /// Get the JWT verifying key (CA verifying key — trust anchor).
1025    ///
1026    /// This is the key that verifies all service JWTs. Published as `x_root_pubkey`
1027    /// in RFC 9728 metadata. Services use this to verify service JWTs from peers.
1028    pub fn jwt_verifying_key(&self) -> VerifyingKey {
1029        match self.ca_verifying_key {
1030            Some(k) => k,
1031            None => panic!(
1032                "jwt_verifying_key: ca_verifying_key not set. \
1033                 Ensure ca-pubkey credential was loaded (IPC mode) or \
1034                 generate_independent_service_keys() was called (inproc mode)."
1035            ),
1036        }
1037    }
1038
1039    /// Create a key source for regular services.
1040    ///
1041    /// When a JWKS fetcher is configured, returns `JwksKeySource(Mode::Isolated)`
1042    /// with kid-based resolution. Otherwise falls back to `ClusterKeySource`
1043    /// (single hardcoded CA key).
1044    ///
1045    /// # Panics
1046    ///
1047    /// Panics if `ca_verifying_key` is not set.
1048    pub fn cluster_key_source(&self) -> std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource> {
1049        let issuer_url = self.oauth_issuer_url().unwrap_or_default().to_owned();
1050
1051        if let Some(ref fetcher) = self.jwks_fetcher {
1052            let jwks_url = format!("{}/oauth/jwks", issuer_url.trim_end_matches('/'));
1053            let source = hyprstream_rpc::auth::JwksKeySource::new(
1054                hyprstream_rpc::auth::JwksMode::Isolated { jwks_url },
1055                issuer_url,
1056                fetcher.clone(),
1057            );
1058            let source = source.with_ml_dsa_verifying_keys(self.ml_dsa_verifying_keys.clone());
1059            // Authoritative local CA key for offline service-JWT resolution
1060            // (no dependency on the HTTP /oauth/jwks endpoint at startup).
1061            let mut source = source.with_local_ca_key(self.jwt_verifying_key());
1062            // The CA composite pair (derived ML-DSA-65 + CA Ed25519) resolves
1063            // hybrid service JWTs offline for the same startup-ordering reason.
1064            if let Some(pq_vk) = self.ca_ml_dsa_verifying_key.clone() {
1065                source = source.with_local_ca_composite(pq_vk, self.jwt_verifying_key());
1066            }
1067            std::sync::Arc::new(source)
1068        } else {
1069            let source =
1070                hyprstream_rpc::auth::ClusterKeySource::new(self.jwt_verifying_key(), issuer_url);
1071            let mut source = source.with_ml_dsa_verifying_keys(self.ml_dsa_verifying_keys.clone());
1072            if let Some(pq_vk) = self.ca_ml_dsa_verifying_key.clone() {
1073                source = source.with_ca_composite_key(pq_vk);
1074            }
1075            std::sync::Arc::new(source)
1076        }
1077    }
1078
1079    /// Set the JWKS fetcher for JWKS-backed key resolution.
1080    ///
1081    /// When set, `cluster_key_source()` returns `JwksKeySource(Mode::Isolated)`
1082    /// instead of `ClusterKeySource`, enabling kid-based key selection from
1083    /// the local `/oauth/jwks` endpoint.
1084    pub fn set_jwks_fetcher(&mut self, fetcher: hyprstream_rpc::auth::JwksFetcher) {
1085        self.jwks_fetcher = Some(fetcher);
1086    }
1087
1088    /// Get the identity provider for purpose-keyed signing.
1089    pub fn identity_provider(&self) -> &Arc<hyprstream_rpc::node_identity::NodeIdentityProvider> {
1090        &self.identity_provider
1091    }
1092
1093    /// Check if running in IPC mode.
1094    pub fn is_ipc(&self) -> bool {
1095        self.ipc
1096    }
1097
1098    /// Get models directory path.
1099    pub fn models_dir(&self) -> &std::path::Path {
1100        &self.models_dir
1101    }
1102
1103    /// Canonical service-owned deployment directory.
1104    ///
1105    /// This deliberately ignores the caller-provided `models_dir`: public
1106    /// `ServiceContext::new` creates local/factory context only and cannot
1107    /// select the production Discovery authority root.
1108    pub fn deployment_data_dir(&self) -> anyhow::Result<std::path::PathBuf> {
1109        deployment_data_dir()
1110    }
1111
1112    /// Get transport config for a service endpoint from the registry.
1113    ///
1114    /// This looks up the endpoint from the global EndpointRegistry.
1115    pub fn endpoint(&self, service: &str, kind: SocketKind) -> TransportConfig {
1116        global_registry().endpoint(service, kind)
1117    }
1118
1119    /// Get unified transport config for a service.
1120    ///
1121    /// In IPC mode, returns a Unix socket path in the runtime directory.
1122    /// In inproc mode, returns the endpoint from the global registry.
1123    ///
1124    /// This unifies the transport resolution logic that was previously
1125    /// duplicated across factory functions.
1126    pub fn transport(&self, service: &str, kind: SocketKind) -> TransportConfig {
1127        if self.ipc {
1128            let runtime_dir = hyprstream_rpc::paths::runtime_dir();
1129            TransportConfig::ipc(runtime_dir.join(format!("{service}.sock")))
1130        } else {
1131            global_registry().endpoint(service, kind)
1132        }
1133    }
1134
1135    /// Wrap a RequestService for spawning with a per-service QUIC port.
1136    ///
1137    /// - `quic_port: None` → use ephemeral port (0) when QUIC is globally enabled
1138    /// - `quic_port: Some(0)` → ephemeral (OS-assigned) port
1139    /// - `quic_port: Some(N)` → explicit port N
1140    ///
1141    /// When `[quic] enabled = true` in config, all services get QUIC on
1142    /// auto-assigned ephemeral ports by default. Set an explicit port to
1143    /// control which port a service uses.
1144    pub fn into_spawnable_quic<
1145        S: hyprstream_rpc::service::RequestService + Send + Sync + 'static,
1146    >(
1147        &self,
1148        service: S,
1149        quic_port: Option<u16>,
1150    ) -> Box<dyn Spawnable> {
1151        self.into_spawnable_quic_with_publisher(service, quic_port, None)
1152    }
1153
1154    /// Supply an owned publication path for a service that cannot RPC itself
1155    /// before readiness. Binding/cancellation still belong to the spawner.
1156    pub fn into_spawnable_quic_with_publisher<
1157        S: hyprstream_rpc::service::RequestService + Send + Sync + 'static,
1158    >(
1159        &self,
1160        service: S,
1161        quic_port: Option<u16>,
1162        publisher: Option<NativeAnnouncementPublisher>,
1163    ) -> Box<dyn Spawnable> {
1164        let quic = match &self.quic_shared {
1165            Some(shared) => {
1166                let mut shared = shared.clone();
1167                let owned = publisher.is_some();
1168                if let Some(publisher) = publisher {
1169                    shared.native_announcement_publisher = Some(publisher);
1170                }
1171                let port = quic_port.unwrap_or(0);
1172                // Use announce callback for all services except discovery itself
1173                // (discovery can't announce to itself)
1174                if service.name() == "discovery" && !owned {
1175                    Some(shared.for_service(service.name(), port))
1176                } else {
1177                    // Bind the announcement JWT to the exact signer. A
1178                    // singleton lookup can select a sibling during overlap.
1179                    let trust = crate::service::trust_store::global_trust_store();
1180                    let signing_key = self.service_signing_key(service.name());
1181                    let service_jwt = trust
1182                        .get(&signing_key.verifying_key())
1183                        .and_then(|att| att.jwt);
1184                    let policy_vk = trust
1185                        .resolve_one("policy")
1186                        .unwrap_or_else(|| panic!("trust store has no policy key"));
1187                    let discovery_vk = trust
1188                        .resolve_one("discovery")
1189                        .unwrap_or_else(|| panic!("trust store has no discovery key"));
1190                    if !trust.is_authorized(&discovery_vk, "discovery") {
1191                        panic!("trust store has no discovery key");
1192                    }
1193                    Some(shared.for_service_with_announce(
1194                        service.name(),
1195                        port,
1196                        signing_key,
1197                        service_jwt,
1198                        policy_vk,
1199                        discovery_vk,
1200                        self.native_announcements.get(service.name()).cloned(),
1201                    ))
1202                }
1203            }
1204            None => None,
1205        };
1206        if quic.is_some() {
1207            Box::new(crate::service::spawner::UnifiedServiceConfig::new(
1208                service, quic,
1209            ))
1210        } else {
1211            Box::new(service)
1212        }
1213    }
1214
1215    /// Wrap a RequestService for spawning, enabling QUIC when globally configured.
1216    ///
1217    /// Uses ephemeral port (0) for QUIC when `[quic] enabled = true`.
1218    pub fn into_spawnable<S: hyprstream_rpc::service::RequestService + Send + Sync + 'static>(
1219        &self,
1220        service: S,
1221    ) -> Box<dyn Spawnable> {
1222        self.into_spawnable_quic(service, None)
1223    }
1224}
1225
1226/// Deployment-owned registry directory shared by the checkpoint writer and
1227/// authenticated process bootstrap. No caller-provided context or path can
1228/// influence this value.
1229pub fn deployment_data_dir() -> anyhow::Result<std::path::PathBuf> {
1230    let data_dir = hyprstream_rpc::paths::try_data_dir()?
1231        .ok_or_else(|| anyhow::anyhow!("deployment data directory is unavailable"))?;
1232    anyhow::ensure!(
1233        data_dir.is_absolute(),
1234        "deployment data directory must be absolute"
1235    );
1236    Ok(data_dir.join("models/.registry"))
1237}
1238
1239// ServiceClient trait removed — generated clients use Arc<dyn RpcClient> directly.
1240
1241/// Factory function signature for creating services.
1242///
1243/// Takes a `ServiceContext` and returns a boxed `Spawnable` service.
1244pub type ServiceFactoryFn = fn(&ServiceContext) -> anyhow::Result<Box<dyn Spawnable>>;
1245
1246/// Service factory for inventory-based registration.
1247///
1248/// Services register their factory function using `#[service_factory("name")]`,
1249/// which generates an `inventory::submit!` for this type.
1250///
1251/// # Pattern
1252///
1253/// Same pattern as:
1254/// - `ScopeDefinition` with `#[register_scopes]` for authorization scopes
1255/// - `DriverFactory` in git2db for storage drivers
1256pub struct ServiceFactory {
1257    /// Service name (matches config.services.startup entries)
1258    pub name: &'static str,
1259
1260    /// Factory function that creates the service
1261    pub factory: ServiceFactoryFn,
1262
1263    /// Raw `.capnp` schema bytes (compile-time embedded via `include_bytes!`)
1264    pub schema: Option<&'static [u8]>,
1265
1266    /// Schema metadata function for compile-time scope discovery.
1267    ///
1268    /// When set, returns `(service_name, &[MethodMeta])` derived from Cap'n Proto
1269    /// schema annotations. Used by PolicyService to discover supported scopes.
1270    pub metadata: Option<SchemaMetadataFn>,
1271
1272    /// Names of services that must be started before this one.
1273    pub depends_on: &'static [&'static str],
1274}
1275
1276impl ServiceFactory {
1277    /// Create a new service factory (without schema).
1278    ///
1279    /// Called by the `#[service_factory]` macro-generated code.
1280    pub const fn new(name: &'static str, factory: ServiceFactoryFn) -> Self {
1281        Self {
1282            name,
1283            factory,
1284            schema: None,
1285            metadata: None,
1286            depends_on: &[],
1287        }
1288    }
1289
1290    /// Create a new service factory with schema bytes.
1291    ///
1292    /// Called by the `#[service_factory("name", schema = "...")]` macro-generated code.
1293    pub const fn with_schema(
1294        name: &'static str,
1295        factory: ServiceFactoryFn,
1296        schema: &'static [u8],
1297    ) -> Self {
1298        Self {
1299            name,
1300            factory,
1301            schema: Some(schema),
1302            metadata: None,
1303            depends_on: &[],
1304        }
1305    }
1306
1307    /// Create a new service factory with schema bytes and metadata.
1308    ///
1309    /// Called by the `#[service_factory("name", schema = "...", metadata = ...)]` macro-generated code.
1310    pub const fn with_metadata(
1311        name: &'static str,
1312        factory: ServiceFactoryFn,
1313        schema: &'static [u8],
1314        metadata: SchemaMetadataFn,
1315    ) -> Self {
1316        Self {
1317            name,
1318            factory,
1319            schema: Some(schema),
1320            metadata: Some(metadata),
1321            depends_on: &[],
1322        }
1323    }
1324
1325    /// Set service dependencies (chained builder).
1326    ///
1327    /// Services listed in `depends_on` must be started before this one.
1328    /// Used by the `#[service_factory("name", depends_on = ["policy"])]` macro.
1329    pub const fn with_depends_on(mut self, deps: &'static [&'static str]) -> Self {
1330        self.depends_on = deps;
1331        self
1332    }
1333}
1334
1335// Collect all registered factories
1336inventory::collect!(ServiceFactory);
1337
1338/// Get a service factory by name.
1339///
1340/// Looks up the factory from compile-time registered factories.
1341///
1342/// # Example
1343///
1344/// ```ignore
1345/// let factory = get_factory("policy").ok_or_else(|| anyhow!("Unknown service: policy"))?;
1346/// let spawnable = (factory.factory)(&ctx)?;
1347/// manager.spawn(spawnable).await?;
1348/// ```
1349pub fn get_factory(name: &str) -> Option<&'static ServiceFactory> {
1350    inventory::iter::<ServiceFactory>().find(|f| f.name == name)
1351}
1352
1353/// List all registered service factories.
1354///
1355/// Useful for introspection and help text.
1356pub fn list_factories() -> impl Iterator<Item = &'static ServiceFactory> {
1357    inventory::iter::<ServiceFactory>()
1358}
1359
1360#[cfg(test)]
1361#[allow(clippy::expect_used, clippy::unwrap_used)]
1362mod tests {
1363    use super::*;
1364    use parking_lot::Mutex;
1365
1366    fn accepted_announcement(
1367        signer: &SigningKey,
1368        expires_at_unix_ms: i64,
1369    ) -> NativeServiceAnnouncement {
1370        let recipient = hyprstream_rpc::crypto::hybrid_kem::generate_recipient(
1371            hyprstream_rpc::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
1372        )
1373        .expect("recipient")
1374        .public()
1375        .clone();
1376        NativeServiceAnnouncement {
1377            service_did: hyprstream_rpc::identity::Did::from("did:at9p:factory-test"),
1378            capabilities: vec!["hyprstream-rpc/1".to_owned(), "hyprstream-moq/1".to_owned()],
1379            accepted_state_digest: [0x52; 64],
1380            accepted_state_epoch: 7,
1381            accepted_state_expires_at_unix_ms: expires_at_unix_ms,
1382            response_key_id: "did:at9p:factory-test#response".to_owned(),
1383            response_verifying_key: signer.verifying_key().to_bytes(),
1384            request_kem_key_id: "did:at9p:factory-test#mesh-kem".to_owned(),
1385            request_kem_recipient: recipient,
1386        }
1387    }
1388
1389    fn announcement_config(
1390        publisher: Option<NativeAnnouncementPublisher>,
1391        accepted: Option<NativeServiceAnnouncement>,
1392    ) -> hyprstream_rpc::service::QuicLoopConfig {
1393        let signer = SigningKey::from_bytes(&[0x41; 32]);
1394        QuicSharedConfig {
1395            cert_chain: Vec::new(),
1396            certificate_hashes: Vec::new(),
1397            key_der: Zeroizing::new(Vec::new()),
1398            base_ip: std::net::Ipv4Addr::LOCALHOST.into(),
1399            server_name: "model.example.test".to_owned(),
1400            oauth_issuer_url: None,
1401            jwt_verifying_key: None,
1402            iroh_enabled: true,
1403            iroh_required: false,
1404            moq_relay: None,
1405            moq_relay_server_identity: None,
1406            native_announcement_publisher: publisher,
1407            moq_admission: None,
1408            moq_ingress_authorizer: None,
1409            moq_admission_proof: None,
1410        }
1411        .for_service_with_announce(
1412            "model",
1413            0,
1414            signer.clone(),
1415            Some("same-service-jwt".to_owned()),
1416            signer.verifying_key(),
1417            signer.verifying_key(),
1418            accepted,
1419        )
1420    }
1421
1422    struct SeparateService {
1423        key: SigningKey,
1424        transport: hyprstream_rpc::transport::TransportConfig,
1425    }
1426
1427    #[async_trait::async_trait(?Send)]
1428    impl hyprstream_rpc::service::RequestService for SeparateService {
1429        async fn handle_request(
1430            &self,
1431            _ctx: &hyprstream_rpc::service::EnvelopeContext,
1432            body: &hyprstream_rpc::service::DecodedRequestBody,
1433        ) -> anyhow::Result<(Vec<u8>, Option<hyprstream_rpc::service::Continuation>)> {
1434            Ok((body.bytes().to_vec(), None))
1435        }
1436        fn decode_request_body(
1437            &self,
1438            signed_body: &[u8],
1439        ) -> anyhow::Result<hyprstream_rpc::service::DecodedRequestBody> {
1440            Ok(hyprstream_rpc::service::DecodedRequestBody::opaque(
1441                signed_body.to_vec(),
1442            ))
1443        }
1444        fn name(&self) -> &str {
1445            "model"
1446        }
1447        fn transport(&self) -> &hyprstream_rpc::transport::TransportConfig {
1448            &self.transport
1449        }
1450        fn signing_key(&self) -> SigningKey {
1451            self.key.clone()
1452        }
1453    }
1454
1455    #[test]
1456    fn separate_service_announcement_needs_only_discovery_public_key() {
1457        const CHILD: &str = "HYPRSTREAM_TEST_SEPARATE_ANNOUNCEMENT_CHILD";
1458        if std::env::var_os(CHILD).is_none() {
1459            let status = std::process::Command::new(std::env::current_exe().unwrap())
1460                .arg("--exact")
1461                .arg("service::factory::tests::separate_service_announcement_needs_only_discovery_public_key")
1462                .env(CHILD, "1")
1463                .status().unwrap();
1464            assert!(status.success());
1465            return;
1466        }
1467        let own_key = SigningKey::from_bytes(&[0x75; 32]);
1468        let trust = crate::global_trust_store();
1469        for (name, seed) in [("policy", 0x76), ("discovery", 0x77)] {
1470            let public_key = SigningKey::from_bytes(&[seed; 32]).verifying_key();
1471            trust.insert(
1472                public_key,
1473                crate::Attestation {
1474                    scopes: [name.to_owned()].into_iter().collect(),
1475                    subject: None,
1476                    jwt: None,
1477                    expires_at: 0,
1478                    attested_by: None,
1479                },
1480            );
1481        }
1482        let models = tempfile::tempdir().unwrap();
1483        let ctx = ServiceContext::new(
1484            own_key.clone(),
1485            own_key.verifying_key(),
1486            true,
1487            models.path().to_owned(),
1488        )
1489        .with_service_key("model", own_key.clone())
1490        .with_quic(QuicSharedConfig {
1491            cert_chain: Vec::new(),
1492            certificate_hashes: Vec::new(),
1493            key_der: Zeroizing::new(Vec::new()),
1494            base_ip: std::net::Ipv4Addr::LOCALHOST.into(),
1495            server_name: "model.example.test".to_owned(),
1496            oauth_issuer_url: None,
1497            jwt_verifying_key: None,
1498            iroh_enabled: true,
1499            iroh_required: false,
1500            moq_relay: None,
1501            native_announcement_publisher: None,
1502            moq_relay_server_identity: None,
1503            moq_admission: None,
1504            moq_ingress_authorizer: None,
1505            moq_admission_proof: None,
1506        });
1507        assert!(!ctx.service_keys.contains_key("discovery"));
1508        let service = SeparateService {
1509            key: own_key,
1510            transport: hyprstream_rpc::transport::TransportConfig::inproc("separate-service"),
1511        };
1512        let _spawnable = ctx.into_spawnable_quic(service, None);
1513    }
1514
1515    #[test]
1516    fn quic_shared_config_preserves_optional_moq_ingress_authority() {
1517        let authority = Arc::new(
1518            |peer: &hyprstream_rpc::moq_authz::PeerIdentity, tenant: &str| {
1519                peer.subject.as_deref() == Some("did:at9p:producer") && tenant == "local"
1520            },
1521        );
1522        let shared = QuicSharedConfig {
1523            cert_chain: Vec::new(),
1524            certificate_hashes: Vec::new(),
1525            key_der: Zeroizing::new(Vec::new()),
1526            base_ip: "127.0.0.1".parse().expect("loopback"),
1527            server_name: "test".to_owned(),
1528            oauth_issuer_url: None,
1529            jwt_verifying_key: None,
1530            iroh_enabled: true,
1531            iroh_required: false,
1532            moq_relay: None,
1533            moq_relay_server_identity: None,
1534            native_announcement_publisher: None,
1535            moq_admission: None,
1536            moq_ingress_authorizer: Some(authority),
1537            moq_admission_proof: None,
1538        };
1539
1540        let wired = shared.for_service("event", 0);
1541        assert!(wired
1542            .moq_ingress_authorizer
1543            .as_ref()
1544            .is_some_and(|authorizer| authorizer.authorize_ingress(
1545                &hyprstream_rpc::moq_authz::PeerIdentity::authenticated("did:at9p:producer"),
1546                "local",
1547            )));
1548
1549        let default = QuicSharedConfig {
1550            moq_ingress_authorizer: None,
1551            ..shared
1552        }
1553        .for_service("event", 0);
1554        assert!(
1555            default.moq_ingress_authorizer.is_none(),
1556            "absence must stay read-only"
1557        );
1558    }
1559
1560    #[test]
1561    fn test_service_factory_creation() {
1562        fn dummy_factory(_ctx: &ServiceContext) -> anyhow::Result<Box<dyn Spawnable>> {
1563            Err(anyhow::anyhow!("dummy"))
1564        }
1565
1566        let factory = ServiceFactory::new("test", dummy_factory);
1567        assert_eq!(factory.name, "test");
1568    }
1569
1570    #[test]
1571    fn native_announcement_rejects_incomplete_hybrid_recipient() {
1572        let signer = SigningKey::from_bytes(&[0x51; 32]);
1573        let announcement = NativeServiceAnnouncement {
1574            service_did: hyprstream_rpc::identity::Did::from("did:at9p:test"),
1575            capabilities: vec!["hyprstream-rpc/1".to_owned(), "hyprstream-moq/1".to_owned()],
1576            accepted_state_digest: [0x31; 64],
1577            accepted_state_epoch: 1,
1578            accepted_state_expires_at_unix_ms: i64::MAX,
1579            response_key_id: "did:at9p:test#response".to_owned(),
1580            response_verifying_key: signer.verifying_key().to_bytes(),
1581            request_kem_key_id: "did:at9p:test#kem".to_owned(),
1582            request_kem_recipient: hyprstream_rpc::crypto::hybrid_kem::RecipientPublic {
1583                suite_id: hyprstream_rpc::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
1584                eks: Vec::new(),
1585            },
1586        };
1587        assert!(announcement
1588            .validate("model", &signer.verifying_key())
1589            .is_err());
1590    }
1591
1592    #[test]
1593    fn iroh_announcement_callback_propagates_publisher_error() {
1594        let signer = SigningKey::from_bytes(&[0x41; 32]);
1595        let calls = Arc::new(Mutex::new(0_u8));
1596        let publisher: NativeAnnouncementPublisher = Arc::new({
1597            let calls = Arc::clone(&calls);
1598            move |_| {
1599                *calls.lock() += 1;
1600                anyhow::bail!("discovery publish failed")
1601            }
1602        });
1603        let mut config = announcement_config(
1604            Some(publisher),
1605            Some(accepted_announcement(&signer, i64::MAX)),
1606        );
1607        let error =
1608            config.on_iroh_bound.take().expect("Iroh callback")("model".to_owned(), [0x31; 32])
1609                .expect_err("publisher failure must abort the Iroh announcement callback");
1610        assert!(error.to_string().contains("discovery publish failed"));
1611        assert_eq!(*calls.lock(), 1);
1612    }
1613
1614    #[test]
1615    fn iroh_callback_rejects_missing_or_expired_state_while_quic_compatibility_continues() {
1616        let signer = SigningKey::from_bytes(&[0x41; 32]);
1617        let publisher: NativeAnnouncementPublisher = Arc::new(|_| Ok(()));
1618        let mut missing = announcement_config(Some(Arc::clone(&publisher)), None);
1619        let missing_error =
1620            missing.on_iroh_bound.take().expect("Iroh callback")("model".to_owned(), [0x32; 32])
1621                .expect_err("missing accepted state must fail the Iroh callback");
1622        assert!(missing_error
1623            .to_string()
1624            .contains("accepted native identity/KEM bundle is unavailable"));
1625
1626        let mut expired = announcement_config(
1627            Some(Arc::clone(&publisher)),
1628            Some(accepted_announcement(&signer, 0)),
1629        );
1630        let expired_error =
1631            expired.on_iroh_bound.take().expect("Iroh callback")("model".to_owned(), [0x33; 32])
1632                .expect_err("expired accepted state must fail the Iroh callback");
1633        assert!(expired_error
1634            .to_string()
1635            .contains("accepted state is unbounded or expired"));
1636
1637        let calls = Arc::new(Mutex::new(0_u8));
1638        let compatibility_publisher: NativeAnnouncementPublisher = Arc::new({
1639            let calls = Arc::clone(&calls);
1640            move |_| {
1641                *calls.lock() += 1;
1642                anyhow::bail!("temporary discovery outage")
1643            }
1644        });
1645        let mut compatibility = announcement_config(
1646            Some(compatibility_publisher),
1647            Some(accepted_announcement(&signer, i64::MAX)),
1648        );
1649        compatibility.on_quic_bound.take().expect("QUIC callback")(
1650            "model".to_owned(),
1651            "127.0.0.1:4242".parse().expect("socket address"),
1652            "model.example.test".to_owned(),
1653        );
1654        assert_eq!(
1655            *calls.lock(),
1656            1,
1657            "compatibility callback must attempt publication"
1658        );
1659    }
1660
1661    #[test]
1662    fn factory_emits_identical_authority_bundle_for_quic_and_iroh_reach() {
1663        let signer = SigningKey::from_bytes(&[0x41; 32]);
1664        let recipient = hyprstream_rpc::crypto::hybrid_kem::generate_recipient(
1665            hyprstream_rpc::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
1666        )
1667        .expect("recipient")
1668        .public()
1669        .clone();
1670        let accepted = NativeServiceAnnouncement {
1671            service_did: hyprstream_rpc::identity::Did::from("did:at9p:factory-test"),
1672            capabilities: vec!["hyprstream-rpc/1".to_owned(), "hyprstream-moq/1".to_owned()],
1673            accepted_state_digest: [0x52; 64],
1674            accepted_state_epoch: 7,
1675            accepted_state_expires_at_unix_ms: i64::MAX,
1676            response_key_id: "did:at9p:factory-test#response".to_owned(),
1677            response_verifying_key: signer.verifying_key().to_bytes(),
1678            request_kem_key_id: "did:at9p:factory-test#mesh-kem".to_owned(),
1679            request_kem_recipient: recipient,
1680        };
1681        let published = Arc::new(Mutex::new(Vec::new()));
1682        let shared = QuicSharedConfig {
1683            cert_chain: Vec::new(),
1684            certificate_hashes: vec![[0x55; 32]],
1685            key_der: Zeroizing::new(Vec::new()),
1686            base_ip: std::net::Ipv4Addr::LOCALHOST.into(),
1687            server_name: "model.example.test".to_owned(),
1688            oauth_issuer_url: None,
1689            jwt_verifying_key: None,
1690            iroh_enabled: true,
1691            iroh_required: false,
1692            moq_relay: None,
1693            moq_relay_server_identity: None,
1694            native_announcement_publisher: Some({
1695                let published = Arc::clone(&published);
1696                Arc::new(move |request| {
1697                    published.lock().push(request);
1698                    Ok(())
1699                })
1700            }),
1701            moq_admission: None,
1702            moq_ingress_authorizer: None,
1703            moq_admission_proof: None,
1704        };
1705        let mut config = shared.for_service_with_announce(
1706            "model",
1707            0,
1708            signer.clone(),
1709            Some("same-service-jwt".to_owned()),
1710            signer.verifying_key(),
1711            signer.verifying_key(),
1712            Some(accepted),
1713        );
1714
1715        config.on_quic_bound.take().expect("QUIC callback")(
1716            "model".to_owned(),
1717            "127.0.0.1:4242".parse().expect("socket address"),
1718            "model.example.test".to_owned(),
1719        );
1720        let node_id = [0xab; 32];
1721        config.on_iroh_bound.take().expect("Iroh callback")("model".to_owned(), node_id)
1722            .expect("Iroh announcement callback");
1723
1724        let published = published.lock();
1725        assert_eq!(published.len(), 2);
1726        let quic = &published[0];
1727        let iroh = &published[1];
1728        assert_eq!(quic.reach.socket_kind(), "quic");
1729        assert_eq!(iroh.reach.socket_kind(), "iroh");
1730        use base64::Engine as _;
1731        assert_eq!(
1732            quic.reach.endpoint(),
1733            format!(
1734                "quic://model.example.test:127.0.0.1:4242#{}",
1735                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0x55; 32])
1736            )
1737        );
1738        assert_eq!(iroh.reach.endpoint(), format!("iroh://{}", "ab".repeat(32)));
1739        assert_eq!(iroh.reach.endpoint().len(), "iroh://".len() + 64);
1740        assert_eq!(quic.service_name, iroh.service_name);
1741        assert_eq!(quic.service_jwt, iroh.service_jwt);
1742        assert_eq!(quic.service_did, iroh.service_did);
1743        assert_eq!(quic.capabilities, iroh.capabilities);
1744        assert_eq!(quic.accepted_state_digest, iroh.accepted_state_digest);
1745        assert_eq!(quic.accepted_state_epoch, iroh.accepted_state_epoch);
1746        assert_eq!(quic.response_key_id, iroh.response_key_id);
1747        assert_eq!(quic.request_kem_key_id, iroh.request_kem_key_id);
1748        assert_eq!(quic.request_kem_recipient, iroh.request_kem_recipient);
1749        assert_eq!(quic.expires_at_unix_ms, iroh.expires_at_unix_ms);
1750        assert_eq!(
1751            quic.signing_key.verifying_key().to_bytes(),
1752            iroh.signing_key.verifying_key().to_bytes()
1753        );
1754        assert_eq!(
1755            quic.discovery_verifying_key.to_bytes(),
1756            iroh.discovery_verifying_key.to_bytes()
1757        );
1758    }
1759
1760    /// #1188 / #1183: a native service announcement projects from an accepted
1761    /// state whose capsule publishes a SET of subject keys. The local service
1762    /// signer must be admitted when it is ANY published subject key, not only
1763    /// position 0 — an overlap-rotating identity publishes several usable keys at
1764    /// once. The pre-fix code compared only `subject_keys.first()`, so a service
1765    /// holding the second published key failed startup.
1766    #[test]
1767    fn native_announcement_admits_non_first_published_service_key() {
1768        use ed25519_dalek::SigningKey as EdSigningKey;
1769        use hyprstream_pds::at9p::{
1770            CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
1771        };
1772        use hyprstream_pds::at9p_duplicity::AcceptedAt9pState;
1773        use hyprstream_pds::at9p_gate::verify_genesis_capsule;
1774        use hyprstream_pds::at9p_sign::sign_capsule;
1775        use hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes;
1776
1777        // Two service signers; k1 self-certifies, k2 is also published.
1778        let k1 = EdSigningKey::from_bytes(&[0x61; 32]);
1779        let k2 = EdSigningKey::from_bytes(&[0x62; 32]);
1780        let pq1 = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&k1);
1781        let pq2 = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&k2);
1782        let kp1 = HybridKeyPair::new(
1783            k1.verifying_key().to_bytes().to_vec(),
1784            ml_dsa_sk_to_vk_bytes(&pq1),
1785        )
1786        .unwrap();
1787        let kp2 = HybridKeyPair::new(
1788            k2.verifying_key().to_bytes().to_vec(),
1789            ml_dsa_sk_to_vk_bytes(&pq2),
1790        )
1791        .unwrap();
1792
1793        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://reach").unwrap();
1794        let service = ServiceEntry::new("#model", ServiceType::NinePExport, endpoint).unwrap();
1795        // k1 FIRST, k2 second; self-certify with k1.
1796        let body = CapsuleBody::new(vec![kp1.clone(), kp2], vec![service.clone()]).unwrap();
1797        let genesis = sign_capsule(body, &k1, &pq1).unwrap();
1798        let bytes = genesis.to_dag_cbor().unwrap();
1799        let cid = genesis.cid512().unwrap();
1800        let verified = verify_genesis_capsule(&cid, &bytes).unwrap();
1801        let state = AcceptedAt9pState::from_verified_genesis(&verified).unwrap();
1802
1803        // Genesis has no bounded successor expiry; from_accepted_state requires
1804        // one, so this projection is expected to reject on expiry — but it must
1805        // get PAST the signer-membership check for k2 first. We assert the error
1806        // is the expiry gate, NOT a "signer is not a current response key"
1807        // rejection (which is what the pre-fix positional check produced for k2).
1808        let signer2 = SigningKey::from_bytes(&[0x62; 32]);
1809        let err = match NativeServiceAnnouncement::from_accepted_state("model", &signer2, &state) {
1810            Ok(_) => panic!("genesis-only state has no bounded expiry"),
1811            Err(e) => e,
1812        };
1813        let msg = err.to_string();
1814        assert!(
1815            msg.contains("bounded production expiry") || msg.contains("expiry"),
1816            "second published key must pass the membership check and fail only on \
1817             the genesis expiry gate; got: {msg}"
1818        );
1819        assert!(
1820            !msg.contains("not an accepted current hybrid response key"),
1821            "the second published subject key must be accepted as a member; got: {msg}"
1822        );
1823
1824        // And a signer that is NOT published is rejected on membership.
1825        let outsider = SigningKey::from_bytes(&[0x63; 32]);
1826        let err = match NativeServiceAnnouncement::from_accepted_state("model", &outsider, &state) {
1827            Ok(_) => panic!("a non-member signer must be rejected"),
1828            Err(e) => e,
1829        };
1830        assert!(
1831            err.to_string()
1832                .contains("not an accepted current hybrid response key"),
1833            "unexpected error: {err}"
1834        );
1835
1836        // The accepted pair must contain the exact derived ML-DSA half too;
1837        // matching Ed25519 alone would advertise a proof that cannot answer
1838        // the hybrid admission challenge.
1839        let mismatched = HybridKeyPair::new(
1840            k2.verifying_key().to_bytes().to_vec(),
1841            ml_dsa_sk_to_vk_bytes(&pq1),
1842        )
1843        .unwrap();
1844        let body = CapsuleBody::new(vec![kp1, mismatched], vec![service]).unwrap();
1845        let genesis = sign_capsule(body, &k1, &pq1).unwrap();
1846        let bytes = genesis.to_dag_cbor().unwrap();
1847        let cid = genesis.cid512().unwrap();
1848        let mismatched_state = AcceptedAt9pState::from_verified_genesis(
1849            &verify_genesis_capsule(&cid, &bytes).unwrap(),
1850        )
1851        .unwrap();
1852        let err = match NativeServiceAnnouncement::from_accepted_state(
1853            "model",
1854            &signer2,
1855            &mismatched_state,
1856        ) {
1857            Ok(_) => panic!("mismatched accepted PQ half must reject before projection"),
1858            Err(err) => err,
1859        };
1860        assert!(
1861            err.to_string()
1862                .contains("accepted current hybrid response key"),
1863            "unexpected error: {err}"
1864        );
1865    }
1866
1867    #[test]
1868    fn native_announcement_refresh_reprojects_successor_and_rejects_identity_changes() {
1869        use hyprstream_pds::at9p::{
1870            CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
1871        };
1872        use hyprstream_pds::at9p_duplicity::AcceptedAt9pState;
1873        use hyprstream_pds::at9p_sign::{sign_capsule, sign_update_record};
1874        let signer = SigningKey::from_bytes(&[0x75; 32]);
1875        let pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&signer);
1876        let pair = HybridKeyPair::new(
1877            signer.verifying_key().to_bytes().to_vec(),
1878            hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq),
1879        )
1880        .unwrap();
1881        let service = ServiceEntry::new(
1882            "#model",
1883            ServiceType::NinePExport,
1884            ServiceEndpoint::new(Transport::Iroh, "iroh://test").unwrap(),
1885        )
1886        .unwrap();
1887        let mut body = CapsuleBody::new(vec![pair.clone()], vec![service]).unwrap();
1888        body.next_key_commitments = vec![pair.commitment_digest()];
1889        let genesis = sign_capsule(body.clone(), &signer, &pq).unwrap();
1890        let state =
1891            AcceptedAt9pState::from_persisted_genesis(&genesis.to_dag_cbor().unwrap()).unwrap();
1892        let mut request = NativeAnnouncementRequest {
1893            cancellation: tokio_util::sync::CancellationToken::new(),
1894            service_name: "model".into(),
1895            reach: NativeAnnouncementReach::Iroh {
1896                node_id: [0x76; 32],
1897            },
1898            signing_key: signer.clone(),
1899            service_jwt: None,
1900            discovery_verifying_key: signer.verifying_key(),
1901            service_did: state.did.clone().into(),
1902            capabilities: Vec::new(),
1903            accepted_state_digest: Vec::new(),
1904            accepted_state_epoch: 0,
1905            response_key_id: String::new(),
1906            request_kem_key_id: String::new(),
1907            request_kem_recipient: Vec::new(),
1908            expires_at_unix_ms: 0,
1909        };
1910        let reach = request.reach.endpoint();
1911        let now = chrono::Utc::now();
1912        let update = sign_update_record(
1913            state.subject_cid512.clone(),
1914            1,
1915            state.head_digest,
1916            body.clone(),
1917            (now + chrono::Duration::seconds(60))
1918                .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1919            &signer,
1920            &pq,
1921        )
1922        .unwrap();
1923        let first =
1924            AcceptedAt9pState::from_persisted_update(&update.to_dag_cbor().unwrap()).unwrap();
1925        request.refresh_from_accepted_state(&first).unwrap();
1926        let old_deadline = request.expires_at_unix_ms;
1927        let successor = sign_update_record(
1928            first.subject_cid512.clone(),
1929            2,
1930            first.head_digest,
1931            body.clone(),
1932            (now + chrono::Duration::seconds(600))
1933                .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1934            &signer,
1935            &pq,
1936        )
1937        .unwrap();
1938        let second =
1939            AcceptedAt9pState::from_persisted_update(&successor.to_dag_cbor().unwrap()).unwrap();
1940        request.refresh_from_accepted_state(&second).unwrap();
1941        assert_eq!(request.accepted_state_epoch, 2);
1942        assert_eq!(request.accepted_state_digest, second.head_digest.to_vec());
1943        assert!(request.expires_at_unix_ms > old_deadline);
1944        assert_eq!(request.reach.endpoint(), reach);
1945        assert!(!request.request_kem_recipient.is_empty());
1946        let expired = sign_update_record(
1947            second.subject_cid512.clone(),
1948            3,
1949            second.head_digest,
1950            body,
1951            (now - chrono::Duration::seconds(1)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1952            &signer,
1953            &pq,
1954        )
1955        .unwrap();
1956        let expired =
1957            AcceptedAt9pState::from_persisted_update(&expired.to_dag_cbor().unwrap()).unwrap();
1958        assert!(request.refresh_from_accepted_state(&expired).is_err());
1959        assert_eq!(
1960            request.accepted_state_epoch, 2,
1961            "failed projection must not mutate authority"
1962        );
1963        request.service_did = "did:at9p:other".into();
1964        assert!(request.refresh_from_accepted_state(&second).is_err());
1965        request.service_did = second.did.clone().into();
1966        request.signing_key = SigningKey::from_bytes(&[0x77; 32]);
1967        assert!(request.refresh_from_accepted_state(&second).is_err());
1968    }
1969
1970    #[test]
1971    fn public_context_cannot_select_production_authority() {
1972        const CHILD: &str = "HYPRSTREAM_TEST_AUTHORITY_CHILD";
1973        const EXPECTED: &str = "HYPRSTREAM_TEST_AUTHORITY_EXPECTED";
1974        if std::env::var_os(CHILD).is_some() {
1975            let expected = std::path::PathBuf::from(
1976                std::env::var_os(EXPECTED).expect("deployment-owned expected path"),
1977            );
1978            let first = SigningKey::from_bytes(&[0x71; 32]);
1979            let second = SigningKey::from_bytes(&[0x73; 32]);
1980            let caller_one = tempfile::tempdir().expect("caller models one");
1981            let caller_two = tempfile::tempdir().expect("caller models two");
1982            let local_one = ServiceContext::new(
1983                first.clone(),
1984                first.verifying_key(),
1985                false,
1986                caller_one.path().to_owned(),
1987            );
1988            let local_two = ServiceContext::new(
1989                second.clone(),
1990                second.verifying_key(),
1991                true,
1992                caller_two.path().to_owned(),
1993            );
1994            assert_eq!(local_one.deployment_data_dir().unwrap(), expected);
1995            assert_eq!(local_two.deployment_data_dir().unwrap(), expected);
1996            assert_ne!(local_one.models_dir(), local_two.models_dir());
1997            return;
1998        }
1999
2000        let deployment = tempfile::tempdir().expect("deployment data root");
2001        let caller_store = tempfile::tempdir().expect("caller store");
2002        let caller = SigningKey::from_bytes(&[0x72; 32]);
2003        let expected = deployment.path().join("hyprstream/models/.registry");
2004        let status = std::process::Command::new(std::env::current_exe().expect("test executable"))
2005            .arg("--exact")
2006            .arg("service::factory::tests::public_context_cannot_select_production_authority")
2007            .arg("--nocapture")
2008            .env(CHILD, "1")
2009            .env(EXPECTED, &expected)
2010            // The child resolves deployment paths, so it must not inherit an
2011            // instance namespace that another test in this binary may have set
2012            // in the shared process environment while this fork happens.
2013            .env_remove("HYPRSTREAM_INSTANCE")
2014            .env("XDG_DATA_HOME", deployment.path())
2015            .env("HYPRSTREAM__PDS__STORE_PATH", caller_store.path())
2016            .env(
2017                "HYPRSTREAM__PDS__ACCEPTANCE_IDENTITY",
2018                hex::encode(caller.verifying_key().to_bytes()),
2019            )
2020            .status()
2021            .expect("authority mutation subprocess");
2022        assert!(status.success(), "authority mutation subprocess failed");
2023    }
2024}
2025
2026#[cfg(test)]
2027mod dedicated_process_tests {
2028    use super::*;
2029
2030    #[test]
2031    fn process_containment_is_explicit_and_service_specific() {
2032        let key = SigningKey::from_bytes(&[9; 32]);
2033        // IPC transport alone must never authorize killing the process.
2034        let context = ServiceContext::new(key.clone(), key.verifying_key(), true, "models".into());
2035        assert!(!context.is_dedicated_process_for("oauth"));
2036        let context = context.with_dedicated_process_service("oauth".to_owned());
2037        assert!(context.is_dedicated_process_for("oauth"));
2038        assert!(!context.is_dedicated_process_for("model"));
2039    }
2040}