Skip to main content

qualia_core_db/inference/inference_agent/governed/
signature.rs

1#![allow(dead_code)]
2use super::{DigestScope, PolicyDocument, PolicyError};
3use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
4use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6
7/// Host configuration, not an identity asserted by a policy/request. The host
8/// must obtain this key/principal binding from its authenticated configuration.
9#[derive(Clone, Copy)]
10pub struct TrustedPolicyIdentity {
11    pub(crate) key: [u8; 32],
12    pub(crate) principal: u64,
13    pub(crate) audience: u64,
14    pub(crate) controller_generation: u64,
15}
16impl TrustedPolicyIdentity {
17    pub fn from_host_configuration(
18        key: [u8; 32],
19        principal: u64,
20        audience: u64,
21        controller_generation: u64,
22    ) -> Result<Self, PolicyError> {
23        if principal == 0
24            || audience == 0
25            || controller_generation == 0
26            || key == [0; 32]
27            || VerifyingKey::from_bytes(&key).is_err()
28        {
29            return Err(PolicyError::WrongAuthority);
30        }
31        Ok(Self {
32            key,
33            principal,
34            audience,
35            controller_generation,
36        })
37    }
38    pub fn controller_key(&self) -> [u8; 32] {
39        self.key
40    }
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct SignedPolicy {
46    pub document: PolicyDocument,
47    pub signature: [[u8; 32]; 2],
48}
49impl SignedPolicy {
50    pub(crate) fn sign(document: PolicyDocument, key: &SigningKey) -> Result<Self, PolicyError> {
51        document.validate()?;
52        let signature = signature_parts(key.sign(&policy_digest(&document)).to_bytes());
53        Ok(Self {
54            document,
55            signature,
56        })
57    }
58    pub fn verify(&self, trust: &TrustedPolicyIdentity, now: u64) -> Result<(), PolicyError> {
59        self.document.validate()?;
60        let doc = &self.document;
61        if doc.principal != trust.principal
62            || doc.audience != trust.audience
63            || doc.controller_generation != trust.controller_generation
64        {
65            return Err(PolicyError::WrongAuthority);
66        }
67        verify_signature(trust.key, policy_digest(doc), self.signature)?;
68        doc.valid_at(now)
69    }
70}
71
72pub(crate) fn signature_parts(bytes: [u8; 64]) -> [[u8; 32]; 2] {
73    let mut parts = [[0; 32]; 2];
74    parts[0].copy_from_slice(&bytes[..32]);
75    parts[1].copy_from_slice(&bytes[32..]);
76    parts
77}
78pub(crate) fn verify_signature(
79    key: [u8; 32],
80    digest: [u8; 32],
81    parts: [[u8; 32]; 2],
82) -> Result<(), PolicyError> {
83    let mut bytes = [0; 64];
84    bytes[..32].copy_from_slice(&parts[0]);
85    bytes[32..].copy_from_slice(&parts[1]);
86    VerifyingKey::from_bytes(&key)
87        .map_err(|_| PolicyError::WrongAuthority)?
88        .verify_strict(&digest, &Signature::from_bytes(&bytes))
89        .map_err(|_| PolicyError::InvalidSignature)
90}
91
92/// Canonical digest: domain, fixed LE scalar fields, tagged digest scopes, and
93/// length-prefixed ordered collections. JSON formatting never changes identity.
94pub fn policy_digest(doc: &PolicyDocument) -> [u8; 32] {
95    let mut h = Sha256::new();
96    h.update(b"qualia:sentinel:installed-policy:v2\0");
97    h.update(doc.version.to_le_bytes());
98    for v in [
99        doc.audience,
100        doc.principal,
101        doc.controller_generation,
102        doc.policy_generation,
103        doc.not_before,
104        doc.expires_at,
105    ] {
106        h.update(v.to_le_bytes());
107    }
108    h.update((doc.rules.actors.as_slice().len() as u64).to_le_bytes());
109    for actor in doc.rules.actors.as_slice() {
110        actor.hash_into(&mut h);
111    }
112    for scope in [doc.rules.model, doc.rules.request] {
113        match scope {
114            DigestScope::Any => h.update([0]),
115            DigestScope::Exact(d) => {
116                h.update([1]);
117                h.update(d);
118            }
119        }
120    }
121    h.update((doc.rules.graph_scopes.as_slice().len() as u64).to_le_bytes());
122    for v in doc.rules.graph_scopes.as_slice() {
123        h.update(v.to_le_bytes());
124    }
125    h.update((doc.rules.program.as_slice().len() as u64).to_le_bytes());
126    for op in doc.rules.program.as_slice() {
127        h.update(op.canonical());
128    }
129    for list in [
130        doc.rules.norms.as_slice(),
131        doc.rules.facts.as_slice(),
132        doc.rules.epistemic.as_slice(),
133        doc.rules.trace.as_slice(),
134    ] {
135        h.update((list.len() as u64).to_le_bytes());
136        for q in list {
137            for v in [
138                q.subject,
139                q.predicate,
140                q.object,
141                q.context,
142                q.metadata,
143                q.parity,
144            ] {
145                h.update(v.to_le_bytes());
146            }
147        }
148    }
149    h.update(doc.rules.required_claim.to_le_bytes());
150    h.update(doc.rules.temporal_invariant.to_le_bytes());
151    h.update([u8::from(doc.rules.non_derogable)]);
152    h.finalize().into()
153}