qualia_client_core/inference_policy/
configuration.rs1use ed25519_dalek::{Signer, SigningKey};
6use qualia_cooperative_core::authoring::DocumentRevision;
7use qualia_core_db::{
8 llm_agent::governed::{TrustedPolicyIdentity, INFERENCE_POLICY_AUDIENCE},
9 poet_host::native_authority::TrustedProject,
10};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use std::{
14 io::{Read, Write},
15 path::Path,
16};
17
18pub const CONFIGURATION_BUDGET_BYTES: usize = 16 * 1024 * 1024;
19pub(super) const RECORD_LIMIT: usize = 32 * 1024;
20pub(super) const ENTRY_LIMIT: usize = 128 * 1024;
21pub(super) const ENTRY_COUNT: u64 = 256;
22const FILE: &str = "inference-host.json";
23#[derive(Clone, Serialize, Deserialize)]
24#[serde(deny_unknown_fields)]
25pub struct InferenceHostConfiguration {
26 pub installer_identifier: String,
27 pub installer_public_key: [u8; 32],
28 pub project_id: String,
29 pub project_issuer: String,
30 pub project_public_key: [u8; 32],
31}
32#[derive(Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34struct SignedConfiguration {
35 version: u32,
36 configuration: InferenceHostConfiguration,
37 document: DocumentRevision,
38 signature: [[u8; 32]; 2],
39}
40impl InferenceHostConfiguration {
41 pub(super) fn validate(&self, key: &SigningKey) -> Result<(), String> {
42 if [
43 &self.installer_identifier,
44 &self.project_id,
45 &self.project_issuer,
46 ]
47 .iter()
48 .any(|s| s.trim().is_empty() || s.len() > 4096)
49 || self.installer_public_key != key.verifying_key().to_bytes()
50 || self.project_public_key == [0; 32]
51 {
52 return Err("Invalid explicit inference host trust configuration".into());
53 }
54 self.trust()?;
55 Ok(())
56 }
57 pub(super) fn anchor(&self) -> TrustedProject {
58 TrustedProject {
59 project_id: self.project_id.clone(),
60 issuer_identifier: self.project_issuer.clone(),
61 public_key: self.project_public_key,
62 }
63 }
64 pub(super) fn trust(&self) -> Result<TrustedPolicyIdentity, String> {
65 TrustedPolicyIdentity::from_host_configuration(
66 self.installer_public_key,
67 qualia_core_db::q_hash(&self.installer_identifier),
68 INFERENCE_POLICY_AUDIENCE,
69 1,
70 )
71 .map_err(|e| e.to_string())
72 }
73 pub(super) fn digest(&self) -> [u8; 32] {
74 let mut h = Sha256::new();
75 h.update(b"qualia:inference:host-configuration:v1\0");
76 for s in [
77 &self.installer_identifier,
78 &self.project_id,
79 &self.project_issuer,
80 ] {
81 h.update((s.len() as u64).to_le_bytes());
82 h.update(s.as_bytes());
83 }
84 h.update(self.installer_public_key);
85 h.update(self.project_public_key);
86 h.finalize().into()
87 }
88}
89pub(super) fn selection_digest(c: &InferenceHostConfiguration, d: &DocumentRevision) -> [u8; 32] {
90 let mut h = Sha256::new();
91 h.update(b"qualia:inference:configured-source:v1\0");
92 h.update(c.digest());
93 for s in [&d.project_id, &d.document_id, &d.source_id] {
94 h.update((s.len() as u64).to_le_bytes());
95 h.update(s.as_bytes());
96 }
97 h.update(d.revision.to_le_bytes());
98 h.update(d.source_digest);
99 match &d.author_subject {
100 None => h.update([0]),
101 Some(s) => {
102 h.update([1]);
103 h.update((s.len() as u64).to_le_bytes());
104 h.update(s.as_bytes());
105 }
106 }
107 h.finalize().into()
108}
109fn record(
110 c: InferenceHostConfiguration,
111 d: DocumentRevision,
112 key: &SigningKey,
113) -> Result<SignedConfiguration, String> {
114 c.validate(key)?;
115 if d.project_id != c.project_id
116 || d.source_digest == [0; 32]
117 || [&d.project_id, &d.document_id, &d.source_id]
118 .iter()
119 .any(|s| s.is_empty() || s.len() > 4096)
120 || d.author_subject
121 .as_ref()
122 .is_some_and(|s| s.is_empty() || s.len() > 4096)
123 {
124 return Err(
125 "Explicit project/source revision exceeds bounds or differs from project".into(),
126 );
127 }
128 let sig = key.sign(&selection_digest(&c, &d)).to_bytes();
129 let mut signature = [[0; 32]; 2];
130 signature[0].copy_from_slice(&sig[..32]);
131 signature[1].copy_from_slice(&sig[32..]);
132 Ok(SignedConfiguration {
133 version: 1,
134 configuration: c,
135 document: d,
136 signature,
137 })
138}
139pub(super) fn preflight(
140 c: &InferenceHostConfiguration,
141 d: &DocumentRevision,
142 key: &SigningKey,
143) -> Result<(), String> {
144 c.validate(key)?;
146 if [&d.project_id, &d.document_id, &d.source_id]
147 .iter()
148 .any(|s| s.len() > 4096)
149 || d.author_subject.as_ref().is_some_and(|s| s.len() > 4096)
150 {
151 return Err("Source revision exceeds bounds".into());
152 }
153 let value = record(c.clone(), d.clone(), key)?;
154 serde_json::to_writer(
155 LimitedWriter {
156 file: std::io::sink(),
157 remaining: RECORD_LIMIT,
158 },
159 &value,
160 )
161 .map_err(|e| e.to_string())
162}
163pub(super) fn budget(bytes: usize) -> Result<(), String> {
164 if bytes < CONFIGURATION_BUDGET_BYTES {
165 Err("Inference configuration byte budget exhausted".into())
166 } else {
167 Ok(())
168 }
169}
170pub(super) fn save(
171 root: &Path,
172 c: InferenceHostConfiguration,
173 document: DocumentRevision,
174 key: &SigningKey,
175) -> Result<(), String> {
176 let record = record(c, document, key)?;
177 let scratch = tempfile::Builder::new()
178 .prefix("inference-config-")
179 .tempdir_in(root)
180 .map_err(|e| e.to_string())?;
181 let mut file = tempfile::NamedTempFile::new_in(scratch.path()).map_err(|e| e.to_string())?;
182 let mut writer = LimitedWriter {
183 file: file.as_file_mut(),
184 remaining: RECORD_LIMIT,
185 };
186 serde_json::to_writer(&mut writer, &record).map_err(|e| e.to_string())?;
187 writer.flush().map_err(|e| e.to_string())?;
188 file.as_file().sync_all().map_err(|e| e.to_string())?;
189 #[cfg(test)]
190 match SAVE_FAULT.with(|f| f.take()) {
191 Some(SaveFault::Error) => return Err("injected configuration save failure".into()),
192 Some(SaveFault::Panic) => panic!("injected configuration save unwind"),
193 None => {}
194 }
195 file.persist(root.join(FILE)).map_err(|e| e.to_string())?;
196 Ok(())
197}
198pub(super) fn load(
199 root: &Path,
200 key: &SigningKey,
201) -> Result<(InferenceHostConfiguration, DocumentRevision), String> {
202 let path = root.join(FILE);
203 let meta = std::fs::symlink_metadata(&path)
204 .map_err(|_| "Explicit inference host configuration is required")?;
205 if !meta.is_file() || meta.file_type().is_symlink() || meta.len() > RECORD_LIMIT as u64 {
206 return Err("Inference host configuration file exceeds bounds".into());
207 }
208 #[cfg(windows)]
209 {
210 use std::os::windows::fs::MetadataExt;
211 if meta.file_attributes() & 0x400 != 0 {
212 return Err("Inference host configuration reparse file refused".into());
213 }
214 }
215 if !path
216 .canonicalize()
217 .map_err(|e| e.to_string())?
218 .starts_with(root)
219 {
220 return Err("Inference host configuration escapes metadata directory".into());
221 }
222 let mut bytes = Vec::with_capacity(RECORD_LIMIT + 1);
223 std::fs::File::open(path)
224 .map_err(|e| e.to_string())?
225 .take(RECORD_LIMIT as u64 + 1)
226 .read_to_end(&mut bytes)
227 .map_err(|e| e.to_string())?;
228 if bytes.len() > RECORD_LIMIT {
229 return Err("Inference host configuration grew beyond bounds".into());
230 }
231 let record: SignedConfiguration = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
232 if record.version != 1 {
233 return Err("Unsupported inference host configuration".into());
234 }
235 record.configuration.validate(key)?;
236 let mut signature = [0; 64];
237 signature[..32].copy_from_slice(&record.signature[0]);
238 signature[32..].copy_from_slice(&record.signature[1]);
239 key.verifying_key()
240 .verify_strict(
241 &selection_digest(&record.configuration, &record.document),
242 &ed25519_dalek::Signature::from_bytes(&signature),
243 )
244 .map_err(|_| "Inference host configuration signature rejected")?;
245 preflight(&record.configuration, &record.document, key)?;
246 Ok((record.configuration, record.document))
247}
248struct LimitedWriter<W> {
249 file: W,
250 remaining: usize,
251}
252impl<W: Write> Write for LimitedWriter<W> {
253 fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
254 if b.len() > self.remaining {
255 return Err(std::io::Error::other("configuration output budget"));
256 }
257 let n = self.file.write(b)?;
258 self.remaining -= n;
259 Ok(n)
260 }
261 fn flush(&mut self) -> std::io::Result<()> {
262 self.file.flush()
263 }
264}
265
266#[cfg(test)]
267#[derive(Clone, Copy)]
268pub(super) enum SaveFault {
269 Error,
270 Panic,
271}
272#[cfg(test)]
273thread_local! {static SAVE_FAULT:std::cell::Cell<Option<SaveFault>>=const{std::cell::Cell::new(None)};}
274#[cfg(test)]
275pub(super) fn fail_next_save(fault: SaveFault) {
276 SAVE_FAULT.with(|f| f.set(Some(fault)));
277}