Skip to main content

hoike_server/
state.rs

1use hoike_core::ResponderState;
2use hoike_core::config::Config;
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::Instant;
6use tokio::sync::Mutex;
7
8#[derive(Clone)]
9pub struct AppState {
10    pub responder: Arc<ResponderState>,
11    pub live_signers: Arc<std::sync::RwLock<HashMap<String, Arc<LiveSignerState>>>>,
12    pub signer: Option<Arc<SignerContext>>,
13    /// Handle to the running gossip node, when this process participates in the
14    /// SWIM mesh. `None` when gossip is disabled — admin fleet endpoints then
15    /// report an empty/disabled roster instead of members and generations.
16    pub gossip: Option<Arc<hoike_gossip::GossipNode>>,
17    pub admin: Arc<AdminState>,
18    /// Startup-validated outbound clients for nonce forwarding (F10/S8),
19    /// keyed by CA label. Built once by `forwarding::build_forward_clients`;
20    /// each forward-enabled CA gets exactly one client under its own trust
21    /// policy, so two CAs can never share (or silently overwrite) roots.
22    pub forward_clients: Arc<HashMap<String, reqwest::Client>>,
23}
24
25pub struct LiveSignerState {
26    pub signer: Mutex<hoike_sign::live::LiveSignerKey>,
27    pub responder_key_bytes: Vec<u8>,
28    pub validity_secs: u64,
29    pub responder_cert_der: Option<Vec<u8>>,
30}
31
32/// Shared on-demand signing context. Holds the persistent revocation sources
33/// (DogtagSync retains a sync cookie — must be shared, not rebuilt each pass)
34/// behind a mutex that serializes on-demand signing (admin API) against the
35/// background signer loop, so epoch derivation (from the state store) and
36/// `{label}.ahu` writes never interleave.
37pub struct SignerContext {
38    pub sources: Mutex<hoike_sign::PersistentSources>,
39}
40
41pub struct AdminState {
42    pub config: Config,
43    pub started_at: Instant,
44    pub sessions: Mutex<HashMap<String, Session>>,
45}
46
47#[derive(Clone)]
48pub struct Session {
49    pub operator_name: String,
50    pub role: OperatorRole,
51    pub expires_at: Instant,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
55#[serde(rename_all = "lowercase")]
56pub enum OperatorRole {
57    Administrator,
58    Operator,
59    Viewer,
60}
61
62impl OperatorRole {
63    pub fn rank(self) -> u8 {
64        match self {
65            Self::Viewer => 1,
66            Self::Operator => 2,
67            Self::Administrator => 3,
68        }
69    }
70
71    pub fn has_at_least(self, min: Self) -> bool {
72        self.rank() >= min.rank()
73    }
74}
75
76impl std::str::FromStr for OperatorRole {
77    type Err = String;
78    fn from_str(s: &str) -> Result<Self, Self::Err> {
79        match s {
80            "administrator" => Ok(Self::Administrator),
81            "operator" => Ok(Self::Operator),
82            "viewer" => Ok(Self::Viewer),
83            other => Err(format!("unknown role: {other}")),
84        }
85    }
86}
87
88impl std::fmt::Display for OperatorRole {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        match self {
91            Self::Administrator => write!(f, "administrator"),
92            Self::Operator => write!(f, "operator"),
93            Self::Viewer => write!(f, "viewer"),
94        }
95    }
96}
97
98impl AppState {
99    /// Fallible since F10: building the per-CA forwarding clients validates
100    /// the `forward_ca` material at startup, so an unreadable, empty, or
101    /// malformed root bundle (or a root pinned to a non-HTTPS target) fails
102    /// here instead of degrading the forward channel at request time.
103    pub fn new(responder: ResponderState, config: Config) -> Result<Self, String> {
104        let forward_clients = crate::forwarding::build_forward_clients(&config)?;
105        Ok(AppState {
106            responder: Arc::new(responder),
107            live_signers: Arc::new(std::sync::RwLock::new(HashMap::new())),
108            signer: None,
109            gossip: None,
110            admin: Arc::new(AdminState {
111                config,
112                started_at: Instant::now(),
113                sessions: Mutex::new(HashMap::new()),
114            }),
115            forward_clients: Arc::new(forward_clients),
116        })
117    }
118
119    /// Outbound forwarding client for a CA label (F10/S8). `None` when the CA
120    /// has no client — a forwarding lookup without one is a configuration
121    /// mismatch the handler reports, never a cross-CA trust fallback.
122    pub fn forward_client_for(&self, label: &str) -> Option<&reqwest::Client> {
123        self.forward_clients.get(label)
124    }
125
126    /// Single-CA compatibility builder; never provides a cross-CA fallback.
127    pub fn with_live_signer(self, live: LiveSignerState) -> Self {
128        let labels: Vec<_> = self
129            .admin
130            .config
131            .ca
132            .iter()
133            .filter(|ca| ca.nonce_policy == "live")
134            .map(|ca| ca.label.clone())
135            .collect();
136        assert_eq!(
137            labels.len(),
138            1,
139            "with_live_signer requires exactly one live CA"
140        );
141        self.with_live_signer_for(&labels[0], live)
142    }
143
144    pub fn with_live_signer_for(self, label: &str, live: LiveSignerState) -> Self {
145        self.live_signers
146            .write()
147            .expect("live signer lock poisoned")
148            .insert(label.into(), Arc::new(live));
149        self
150    }
151
152    pub fn live_signer_for(&self, label: &str) -> Option<Arc<LiveSignerState>> {
153        self.live_signers.read().ok()?.get(label).cloned()
154    }
155
156    pub fn reload_live_signer(&self, ca: &hoike_core::config::CaConfig) -> Result<(), String> {
157        if ca.nonce_policy != "live" {
158            return Ok(());
159        }
160        let live = LiveSignerState::from_config(ca)?;
161        self.live_signers
162            .write()
163            .map_err(|e| e.to_string())?
164            .insert(ca.label.clone(), Arc::new(live));
165        Ok(())
166    }
167
168    /// Attach the shared on-demand signing context. The returned `Arc` is also
169    /// cloned into the background signer loop so both paths share one mutex.
170    pub fn with_signer_context(mut self, ctx: SignerContext) -> Self {
171        self.signer = Some(Arc::new(ctx));
172        self
173    }
174
175    /// Attach a handle to the running gossip node so admin fleet endpoints can
176    /// read membership and the generation table, and so the signer path can
177    /// announce new generations.
178    pub fn with_gossip(mut self, gossip: Arc<hoike_gossip::GossipNode>) -> Self {
179        self.gossip = Some(gossip);
180        self
181    }
182}
183
184impl LiveSignerState {
185    pub fn from_config(ca: &hoike_core::config::CaConfig) -> Result<Self, String> {
186        let material = hoike_sign::live::load_live_material(ca)?;
187        Ok(Self {
188            signer: Mutex::new(material.key),
189            responder_key_bytes: material.responder_key_bytes,
190            validity_secs: ca.validity_secs,
191            responder_cert_der: material.responder_cert_der,
192        })
193    }
194}