qualia_core_db/inference/inference_agent/governed/
policy.rs1use super::{ActorPolicyScope, ConstraintInstruction};
2use crate::NQuin;
3use serde::{de::SeqAccess, Deserialize, Deserializer, Serialize};
4use std::{fmt, marker::PhantomData};
5
6pub const POLICY_VERSION: u32 = 2;
7pub const INFERENCE_POLICY_AUDIENCE: u64 = crate::q_hash("qualia:inference:token-acceptance:v2");
8pub const MAX_POLICY_JSON_BYTES: usize = 128 * 1024;
9pub const POLICY_COLD_BUDGET_BYTES: usize = 512 * 1024;
12
13#[derive(Debug, Clone, Serialize)]
16#[serde(transparent)]
17pub struct PolicyList<T, const N: usize>(Vec<T>);
18impl<T, const N: usize> PolicyList<T, N> {
19 pub fn from_vec(values: Vec<T>) -> Result<Self, PolicyError> {
20 if values.len() > N || values.capacity() > N {
21 return Err(PolicyError::Capacity);
22 }
23 Ok(Self(values))
24 }
25 pub fn as_slice(&self) -> &[T] {
26 &self.0
27 }
28}
29impl<T, const N: usize> Default for PolicyList<T, N> {
30 fn default() -> Self {
31 Self(Vec::new())
32 }
33}
34impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for PolicyList<T, N> {
35 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
36 struct Visitor<T, const N: usize>(PhantomData<T>);
37 impl<'de, T: Deserialize<'de>, const N: usize> serde::de::Visitor<'de> for Visitor<T, N> {
38 type Value = PolicyList<T, N>;
39 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
40 write!(f, "at most {N} policy elements")
41 }
42 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
43 if seq.size_hint().is_some_and(|n| n > N) {
44 return Err(serde::de::Error::custom(
45 "policy collection exceeds capacity",
46 ));
47 }
48 let mut values = Vec::with_capacity(N);
49 while values.len() < N {
50 match seq.next_element()? {
51 Some(value) => values.push(value),
52 None => return Ok(PolicyList(values)),
53 }
54 }
55 if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
56 return Err(serde::de::Error::custom(
57 "policy collection exceeds capacity",
58 ));
59 }
60 Ok(PolicyList(values))
61 }
62 }
63 d.deserialize_seq(Visitor::<T, N>(PhantomData))
64 }
65}
66
67#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
68#[serde(tag = "kind", content = "digest", deny_unknown_fields)]
69pub enum DigestScope {
70 Any,
71 Exact([u8; 32]),
72}
73impl DigestScope {
74 pub(crate) fn allows(self, digest: [u8; 32]) -> bool {
75 matches!(self, Self::Any) || self == Self::Exact(digest)
76 }
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct PolicyRules {
84 pub actors: PolicyList<ActorPolicyScope, 32>,
86 pub model: DigestScope,
87 pub request: DigestScope,
88 pub graph_scopes: PolicyList<u64, 32>,
89 pub program: PolicyList<ConstraintInstruction, 64>,
90 pub norms: PolicyList<NQuin, 256>,
91 pub facts: PolicyList<NQuin, 255>,
92 pub epistemic: PolicyList<NQuin, 256>,
93 pub trace: PolicyList<NQuin, 255>,
94 pub required_claim: u64,
95 pub temporal_invariant: u64,
96 pub non_derogable: bool,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct PolicyDocument {
102 pub version: u32,
103 pub audience: u64,
104 pub principal: u64,
105 pub controller_generation: u64,
106 pub policy_generation: u64,
107 pub not_before: u64,
108 pub expires_at: u64,
109 pub rules: PolicyRules,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum PolicyError {
114 Capacity,
115 Budget,
116 InvalidProgram,
117 InvalidPolicy,
118 InvalidSignature,
119 WrongAuthority,
120 MissingPolicy,
121 Expired,
122 Revoked,
123 StaleGeneration,
124 Scope,
125 InvalidCandidate,
126 Clock,
127 CounterExhausted,
128 Session,
129 Io,
130 Encoding,
131 PolicyVersionRequired,
132}
133impl fmt::Display for PolicyError {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 write!(f, "Sentinel policy: {self:?}")
136 }
137}
138impl std::error::Error for PolicyError {}
139
140impl PolicyDocument {
141 pub(crate) fn validate(&self) -> Result<(), PolicyError> {
142 if self.version != POLICY_VERSION
143 || self.principal == 0
144 || self.audience == 0
145 || self.controller_generation == 0
146 || self.policy_generation == 0
147 || self.not_before >= self.expires_at
148 || self.expires_at > u32::MAX as u64
149 {
150 return Err(PolicyError::InvalidPolicy);
151 }
152 if self.rules.actors.as_slice().is_empty() {
153 return Err(PolicyError::Scope);
154 }
155 for actor in self.rules.actors.as_slice() {
156 actor.validate()?;
157 }
158 for instruction in self.rules.program.as_slice() {
159 instruction.lower()?;
160 }
161 for quins in [
162 self.rules.norms.as_slice(),
163 self.rules.facts.as_slice(),
164 self.rules.epistemic.as_slice(),
165 self.rules.trace.as_slice(),
166 ] {
167 for q in quins {
168 if q.parity != q.subject ^ q.predicate ^ q.object ^ q.context {
169 return Err(PolicyError::InvalidPolicy);
170 }
171 }
172 }
173 Ok(())
174 }
175 pub(crate) fn valid_at(&self, now: u64) -> Result<(), PolicyError> {
176 if now < self.not_before || now >= self.expires_at {
177 Err(PolicyError::Expired)
178 } else {
179 Ok(())
180 }
181 }
182}