Skip to main content

qualia_core_db/inference/inference_agent/governed/
host.rs

1//! Privileged native policy persistence. One host instance owns a configured
2//! policy store; all its admissions share liveness and generation state.
3//! A separate trusted authority directory anchors the exact accepted record.
4//! Anchor-first publication is fail-closed, not a two-file atomic transaction:
5//! interruption leaves diagnostic bytes and requires recovery, never stale use.
6//! Rolling back the entire trusted host storage remains outside this assurance.
7use super::{
8    anchor::{
9        atomic_json_write, read_bounded, validate_json_size, AuthorityAnchor, RecordIdentity,
10    },
11    controller::{AuthorityState, InstalledController},
12    evidence::EvidenceController,
13    store::Record,
14    GovernedTokenSession, InferenceAdmission, PolicyDocument, PolicyError, PolicyRules,
15    SignedPolicy, TrustedPolicyIdentity, MAX_POLICY_JSON_BYTES, POLICY_COLD_BUDGET_BYTES,
16    POLICY_VERSION,
17};
18use ed25519_dalek::SigningKey;
19use std::{
20    fs,
21    path::{Path, PathBuf},
22    sync::{atomic::Ordering, Arc},
23};
24
25#[path = "host/evidence.rs"]
26mod evidence;
27
28const FILE_NAME: &str = "sentinel-inference-policy.json";
29
30#[derive(Debug, Clone, Copy)]
31pub struct PolicyStatus {
32    pub installed: bool,
33    pub generation: u64,
34    pub serial: u64,
35    pub digest: Option<[u8; 32]>,
36}
37
38pub struct NativePolicyHost {
39    root: PathBuf,
40    trust: TrustedPolicyIdentity,
41    record: Record,
42    authority: Arc<AuthorityState>,
43    controller: Option<Arc<InstalledController>>,
44    evidence_controller: Option<Arc<EvidenceController>>,
45    anchor: AuthorityAnchor,
46    // Persistent lockfile is never removed: unlinking would permit split locks.
47    _lock: fs::File,
48    #[cfg(test)]
49    fault: Option<PublishFault>,
50}
51#[cfg(test)]
52#[derive(Clone, Copy, PartialEq, Eq)]
53pub(super) enum PublishFault {
54    BeforeAnchor,
55    AfterAnchor,
56    AfterPolicy,
57    PanicAfterAnchor,
58}
59impl Drop for NativePolicyHost {
60    fn drop(&mut self) {
61        self.authority.disconnect();
62    }
63}
64impl NativePolicyHost {
65    /// Only the authenticated host supplies directory and trusted identity.
66    /// Do not construct a fresh host for every request: replacement/revocation
67    /// must invalidate the shared handles owned by this instance.
68    pub fn open(
69        root: &Path,
70        authority_root: &Path,
71        trust: TrustedPolicyIdentity,
72        budget: usize,
73    ) -> Result<Self, PolicyError> {
74        check_budget(budget)?;
75        if root.as_os_str().len() > 4096 || authority_root.as_os_str().len() > 4096 {
76            return Err(PolicyError::Capacity);
77        }
78        fs::create_dir_all(root).map_err(|_| PolicyError::Io)?;
79        let root = fs::canonicalize(root).map_err(|_| PolicyError::Io)?;
80        let lock = fs::OpenOptions::new()
81            .read(true)
82            .write(true)
83            .create(true)
84            .truncate(false)
85            .open(root.join("sentinel-inference-policy.lock"))
86            .map_err(|_| PolicyError::Io)?;
87        lock.try_lock().map_err(|_| PolicyError::Io)?;
88        fs::create_dir_all(authority_root).map_err(|_| PolicyError::Io)?;
89        let authority_root = fs::canonicalize(authority_root).map_err(|_| PolicyError::Io)?;
90        let anchor = AuthorityAnchor::new(&root, &authority_root)?;
91        if !root.join(FILE_NAME).exists() && anchor.exists() {
92            return Err(PolicyError::StaleGeneration);
93        }
94        let mut host = Self {
95            root,
96            trust,
97            record: Record::empty(),
98            authority: Arc::new(AuthorityState::new(0)),
99            controller: None,
100            evidence_controller: None,
101            anchor,
102            _lock: lock,
103            #[cfg(test)]
104            fault: None,
105        };
106        if host.root.join(FILE_NAME).exists() {
107            host.reload(budget)?;
108        }
109        Ok(host)
110    }
111    pub fn status(&self) -> PolicyStatus {
112        PolicyStatus {
113            installed: self.record.installed(),
114            generation: self.record.generation(),
115            serial: self.record.serial(),
116            digest: self.record.policy_digest(),
117        }
118    }
119    pub fn trusted_identity(&self) -> TrustedPolicyIdentity {
120        self.trust
121    }
122    pub fn disconnect(&self) {
123        self.authority.disconnect();
124    }
125    #[cfg(test)]
126    pub(super) fn fail_next_publication(&mut self, fault: PublishFault) {
127        self.fault = Some(fault);
128    }
129    pub fn reload(&mut self, budget: usize) -> Result<(), PolicyError> {
130        check_budget(budget)?;
131        let result = self.read_record();
132        match result {
133            Ok(record) => {
134                if record.serial() < self.record.serial()
135                    || record.generation() < self.record.generation()
136                    || record.next_session() < self.record.next_session()
137                {
138                    self.disconnect();
139                    return Err(PolicyError::StaleGeneration);
140                }
141                self.publish(record)
142            }
143            Err(error) => {
144                self.disconnect();
145                Err(error)
146            }
147        }
148    }
149    /// Explicit privileged human/host installation. Rules contain no principal
150    /// or signing key: these come from configured trust. The caller must have
151    /// authorized this operation; never expose it as an unauthenticated RPC.
152    pub fn install(
153        &mut self,
154        key: &SigningKey,
155        rules: PolicyRules,
156        not_before: u64,
157        expires_at: u64,
158        now: u64,
159        expected_generation: u64,
160        budget: usize,
161    ) -> Result<PolicyStatus, PolicyError> {
162        check_budget(budget)?;
163        self.check_key(key)?;
164        self.check_generation(expected_generation)?;
165        let generation = self
166            .record
167            .generation()
168            .checked_add(1)
169            .ok_or(PolicyError::CounterExhausted)?;
170        let doc = PolicyDocument {
171            version: POLICY_VERSION,
172            audience: self.trust.audience,
173            principal: self.trust.principal,
174            controller_generation: self.trust.controller_generation,
175            policy_generation: generation,
176            not_before,
177            expires_at,
178            rules,
179        };
180        let policy = SignedPolicy::sign(doc, key)?;
181        policy.verify(&self.trust, now)?;
182        let mut next = self.next_record()?;
183        next.set_generation(generation);
184        next.install_v2(policy);
185        self.persist(&mut next, key)?;
186        self.publish(next)?;
187        Ok(self.status())
188    }
189    pub fn revoke(
190        &mut self,
191        key: &SigningKey,
192        expected_generation: u64,
193        budget: usize,
194    ) -> Result<PolicyStatus, PolicyError> {
195        check_budget(budget)?;
196        self.check_key(key)?;
197        self.check_generation(expected_generation)?;
198        let mut next = self.next_record()?;
199        next.set_generation(
200            next.generation()
201                .checked_add(1)
202                .ok_or(PolicyError::CounterExhausted)?,
203        );
204        next.clear();
205        self.persist(&mut next, key)?;
206        self.publish(next)?;
207        Ok(self.status())
208    }
209    /// Cold admission reserves a durable, never-reused session number before
210    /// returning a session. Signature verification and disk I/O are not hot-path work.
211    pub fn admit(
212        &mut self,
213        key: &SigningKey,
214        request: InferenceAdmission,
215        budget: usize,
216        owner: Arc<crate::poet_host::native_authority::NativeAuthority>,
217        association: crate::poet_host::native_authority::inference::AuthenticatedInferenceAssociation,
218    ) -> Result<GovernedTokenSession, PolicyError> {
219        self.admit_clock(key, request, None, budget, owner, association)
220    }
221    #[cfg(test)]
222    pub(super) fn admit_at(
223        &mut self,
224        key: &SigningKey,
225        request: InferenceAdmission,
226        now: u64,
227        budget: usize,
228        owner: Arc<crate::poet_host::native_authority::NativeAuthority>,
229        association: crate::poet_host::native_authority::inference::AuthenticatedInferenceAssociation,
230    ) -> Result<GovernedTokenSession, PolicyError> {
231        self.admit_clock(key, request, Some(now), budget, owner, association)
232    }
233    fn admit_clock(
234        &mut self,
235        key: &SigningKey,
236        request: InferenceAdmission,
237        clock_override: Option<u64>,
238        budget: usize,
239        owner: Arc<crate::poet_host::native_authority::NativeAuthority>,
240        association: crate::poet_host::native_authority::inference::AuthenticatedInferenceAssociation,
241    ) -> Result<GovernedTokenSession, PolicyError> {
242        check_budget(budget)?;
243        self.check_key(key)?;
244        if self.record.v3().is_some() {
245            return Err(PolicyError::PolicyVersionRequired);
246        }
247        let controller = self.controller.as_ref().ok_or(PolicyError::MissingPolicy)?;
248        let session_id = self
249            .record
250            .next_session()
251            .checked_add(1)
252            .ok_or(PolicyError::CounterExhausted)?;
253        let session = GovernedTokenSession::admit(
254            Arc::clone(controller),
255            request,
256            session_id,
257            clock_override,
258            owner,
259            association,
260        )?;
261        let mut next = self.next_record()?;
262        next.set_next_session(session_id);
263        self.persist(&mut next, key)?;
264        // Session-number bookkeeping does not replace or reconnect authority.
265        self.record = next;
266        Ok(session)
267    }
268    fn check_key(&self, key: &SigningKey) -> Result<(), PolicyError> {
269        if key.verifying_key().to_bytes() != self.trust.key {
270            Err(PolicyError::WrongAuthority)
271        } else {
272            Ok(())
273        }
274    }
275    fn check_generation(&self, expected: u64) -> Result<(), PolicyError> {
276        if expected != self.record.generation() {
277            Err(PolicyError::StaleGeneration)
278        } else {
279            Ok(())
280        }
281    }
282    fn next_record(&self) -> Result<Record, PolicyError> {
283        let mut next = self.record.clone();
284        next.set_serial(
285            next.serial()
286                .checked_add(1)
287                .ok_or(PolicyError::CounterExhausted)?,
288        );
289        Ok(next)
290    }
291    fn publish(&mut self, record: Record) -> Result<(), PolicyError> {
292        let _gate = self.authority.lock()?;
293        let epoch = match self
294            .authority
295            .generation
296            .load(Ordering::Acquire)
297            .checked_add(1)
298        {
299            Some(epoch) => epoch,
300            None => {
301                self.authority.connected.store(false, Ordering::Release);
302                return Err(PolicyError::CounterExhausted);
303            }
304        };
305        self.authority.generation.store(epoch, Ordering::Release);
306        self.controller = record.v2().map(|policy| {
307            Arc::new(InstalledController {
308                policy: policy.clone(),
309                key: self.trust.key,
310                authority: Arc::clone(&self.authority),
311                epoch,
312            })
313        });
314        self.evidence_controller = match record
315            .v3()
316            .map(|policy| {
317                EvidenceController::new(
318                    policy.clone(),
319                    self.trust,
320                    Arc::clone(&self.authority),
321                    epoch,
322                )
323            })
324            .transpose()
325        {
326            Ok(controller) => controller.map(Arc::new),
327            Err(error) => {
328                self.authority.connected.store(false, Ordering::Release);
329                return Err(error);
330            }
331        };
332        self.record = record;
333        self.authority.connected.store(true, Ordering::Release);
334        Ok(())
335    }
336    fn read_record(&self) -> Result<Record, PolicyError> {
337        let bytes = read_bounded(&self.root.join(FILE_NAME), MAX_POLICY_JSON_BYTES)?;
338        let record = Record::decode(&bytes)?;
339        record.verify(&self.trust)?;
340        self.anchor.verify(
341            RecordIdentity {
342                serial: record.serial(),
343                generation: record.generation(),
344                digest: record.digest(&self.trust),
345            },
346            &self.trust,
347        )?;
348        Ok(record)
349    }
350    fn persist(&mut self, record: &mut Record, key: &SigningKey) -> Result<(), PolicyError> {
351        record.sign(&self.trust, key);
352        validate_json_size(record, MAX_POLICY_JSON_BYTES)?;
353        let current = if self.record.serial() == 0 {
354            if self.root.join(FILE_NAME).exists() || self.anchor.exists() {
355                Err(PolicyError::StaleGeneration)
356            } else {
357                Ok(())
358            }
359        } else {
360            self.read_record().and_then(|disk| {
361                if disk.digest(&self.trust) == self.record.digest(&self.trust) {
362                    Ok(())
363                } else {
364                    Err(PolicyError::StaleGeneration)
365                }
366            })
367        };
368        if let Err(error) = current {
369            self.disconnect();
370            return Err(error);
371        }
372        #[cfg(test)]
373        let fault = self.fault.take();
374        #[cfg(test)]
375        if fault == Some(PublishFault::BeforeAnchor) {
376            return Err(PolicyError::Io);
377        }
378        self.anchor.publish(
379            RecordIdentity {
380                serial: record.serial(),
381                generation: record.generation(),
382                digest: record.digest(&self.trust),
383            },
384            &self.trust,
385            key,
386        )?;
387        // Any failure or unwind after anchor replacement invalidates live
388        // admissions immediately, even if the caller catches the error/panic.
389        let mut guard = PublicationGuard {
390            authority: &self.authority,
391            complete: false,
392        };
393        #[cfg(test)]
394        match fault {
395            Some(PublishFault::AfterAnchor) => return Err(PolicyError::Io),
396            Some(PublishFault::PanicAfterAnchor) => panic!("injected policy publication unwind"),
397            _ => {}
398        }
399        atomic_json_write(&self.root.join(FILE_NAME), record, MAX_POLICY_JSON_BYTES)?;
400        #[cfg(test)]
401        if fault == Some(PublishFault::AfterPolicy) {
402            return Err(PolicyError::Io);
403        }
404        guard.complete = true;
405        Ok(())
406    }
407}
408fn check_budget(budget: usize) -> Result<(), PolicyError> {
409    if budget < POLICY_COLD_BUDGET_BYTES {
410        Err(PolicyError::Budget)
411    } else {
412        Ok(())
413    }
414}
415struct PublicationGuard<'a> {
416    authority: &'a AuthorityState,
417    complete: bool,
418}
419impl Drop for PublicationGuard<'_> {
420    fn drop(&mut self) {
421        if !self.complete {
422            self.authority.disconnect();
423        }
424    }
425}