Skip to main content

qualia_client_core/inference_policy/
actor.rs

1//! Explicit actor login through real native key possession and signed admission.
2use super::{configuration, registry, store};
3use qualia_core_db::{
4    key_vault::KeyVault,
5    llm_agent::governed::ActorPolicyScope,
6    poet_host::native_authority::{
7        enrollment::NativeSigner,
8        inference::{AuthenticatedInferenceAssociation, IdentifierSelection},
9        NativeAuthority, SessionHandle,
10    },
11};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::{path::PathBuf, sync::Arc};
15use zeroize::Zeroizing;
16
17/// Selection data is not a credential. Exact association must exist in the
18/// configured signed admission, independent of subject kind or controller key.
19#[derive(Clone, Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct SelectedInferenceIdentifier {
22    pub value: String,
23    pub scheme: String,
24    pub issuer: String,
25    pub project_id: String,
26    pub evidence_ref: String,
27}
28impl SelectedInferenceIdentifier {
29    fn selection(&self) -> IdentifierSelection<'_> {
30        IdentifierSelection {
31            value: &self.value,
32            scheme: &self.scheme,
33            issuer: &self.issuer,
34            project_id: &self.project_id,
35            evidence_ref: &self.evidence_ref,
36        }
37    }
38    fn validate(&self) -> Result<(), String> {
39        if [
40            &self.value,
41            &self.scheme,
42            &self.issuer,
43            &self.project_id,
44            &self.evidence_ref,
45        ]
46        .iter()
47        .any(|s| s.is_empty() || s.len() > 4096)
48        {
49            return Err("Identifier selection exceeds bounds".into());
50        }
51        Ok(())
52    }
53}
54/// Opaque authenticated client handle, not serializable or constructible from
55/// selected identifier strings. The native owner retains all liveness checks.
56pub struct InferenceActorSession {
57    owner: Arc<NativeAuthority>,
58    session: SessionHandle,
59    selected: SelectedInferenceIdentifier,
60    epoch: u64,
61}
62impl InferenceActorSession {
63    pub(super) fn product_session(
64        &self,
65        capability: Arc<qualia_core_db::llm_agent::native_request::NativeHostCapability>,
66        preparation: qualia_core_db::llm_agent::native_request::NativePreparationSpec,
67    ) -> Result<qualia_core_db::llm_agent::native_request::NativeProductSession, String> {
68        self.current()?;
69        qualia_core_db::llm_agent::native_request::NativeProductSession::new(
70            capability,
71            self.session.clone(),
72            self.selected.selection(),
73            preparation,
74        )
75        .map_err(|e| e.to_string())
76    }
77    pub(super) fn owner(&self) -> &Arc<NativeAuthority> {
78        &self.owner
79    }
80    pub(super) fn bind(&self) -> Result<AuthenticatedInferenceAssociation, String> {
81        self.current()?;
82        self.owner
83            .bind_inference_association(&self.session, self.selected.selection())
84            .map_err(|e| format!("Inference actor association: {e:?}"))
85    }
86    /// Policy-authoring metadata only; copying it cannot create a live session.
87    pub fn policy_scope(&self) -> Result<ActorPolicyScope, String> {
88        let association = self.bind()?;
89        self.owner
90            .with_current_inference_association(&association, ActorPolicyScope::from_evidence)
91            .map_err(|e| format!("Inference actor expired: {e:?}"))
92    }
93    pub fn logout(&self) -> Result<(), String> {
94        self.current()?;
95        let result = self.owner.disconnect(&self.session);
96        registry::forget(&self.owner, &self.session);
97        result
98    }
99    fn current(&self) -> Result<(), String> {
100        if registry::epoch()? != self.epoch {
101            Err("Inference actor requires fresh login after controller loss".into())
102        } else {
103            Ok(())
104        }
105    }
106}
107fn signer_path(label: &str) -> Result<PathBuf, String> {
108    if label.trim().is_empty() || label.len() > 1024 {
109        return Err("Explicit bounded signer label required".into());
110    }
111    let root = store::meta_root()?;
112    let directory = store::child_directory(&root, "inference-actor-keys")?;
113    Ok(directory.join(format!(
114        "{}.sealed",
115        hex::encode(Sha256::digest(label.as_bytes()))
116    )))
117}
118fn wrapping(vault: &KeyVault, label: &str) -> Zeroizing<[u8; 32]> {
119    Zeroizing::new(
120        vault
121            .derive_key(&format!(
122                "qualia.inference.signer.wrap.v1:{}:{label}",
123                label.len()
124            ))
125            .to_bytes(),
126    )
127}
128fn open_signer(vault: &KeyVault, label: &str) -> Result<NativeSigner, String> {
129    let path = signer_path(label)?;
130    NativeSigner::open_sealed(&path, &wrapping(vault, label))
131}
132/// Explicit key creation, NOT identity enrollment or admission. Never called by
133/// login or inference. Existing keys are not overwritten, even on a racing create.
134pub fn create_inference_actor_signer(label: &str, budget: usize) -> Result<[u8; 32], String> {
135    configuration::budget(budget)?;
136    store::with_vault(|vault| {
137        let path = signer_path(label)?;
138        if path.exists() {
139            return Err("Inference actor signer already exists".into());
140        }
141        let scratch = tempfile::Builder::new()
142            .prefix("inference-signer-")
143            .tempdir_in(path.parent().expect("child path"))
144            .map_err(|e| e.to_string())?;
145        let temporary = scratch.path().join("controller.sealed");
146        let signer = NativeSigner::create_sealed(&temporary, &wrapping(vault, label))?;
147        if std::fs::metadata(&temporary)
148            .map_err(|e| e.to_string())?
149            .len()
150            != 76
151        {
152            return Err("Unexpected sealed signer size".into());
153        }
154        // Same-filesystem create-new link is atomic and never replaces a winner.
155        // RAII removes the temporary name on success/error/unwind.
156        std::fs::hard_link(&temporary, &path).map_err(|e| e.to_string())?;
157        Ok(signer.public_key())
158    })
159}
160/// Actual signed challenge, not identifier matching or a boolean authentication
161/// assertion. No signer is created and no missing admission is synthesized.
162pub fn login_inference_actor(
163    subject: &str,
164    selected: SelectedInferenceIdentifier,
165    signer_label: &str,
166    lifetime_seconds: u64,
167    budget: usize,
168) -> Result<InferenceActorSession, String> {
169    configuration::budget(budget)?;
170    selected.validate()?;
171    if subject.is_empty() || subject.len() > 4096 {
172        return Err("Actor subject exceeds bounds".into());
173    }
174    store::with_host(|host, _, vault| {
175        let epoch = registry::epoch()?;
176        let signer = open_signer(vault, signer_label)?;
177        let challenge = host.owner.begin_session(subject, lifetime_seconds)?;
178        let proof = signer.prove_session(&challenge)?;
179        let session = host.owner.complete_session(challenge, &proof)?;
180        let actor = InferenceActorSession {
181            owner: Arc::clone(&host.owner),
182            session,
183            selected,
184            epoch,
185        };
186        let association = match actor.bind() {
187            Ok(a) => a,
188            Err(error) => {
189                let _ = host.owner.disconnect(&actor.session);
190                return Err(error);
191            }
192        };
193        if let Err(error) = registry::track(&host.owner, &actor.session, association) {
194            let _ = host.owner.disconnect(&actor.session);
195            return Err(error);
196        }
197        Ok(actor)
198    })
199}