Skip to main content

qualia_core_db/net/qdnf/authority/
owner.rs

1//! Owner-held authority records and generation-bearing mutation handles.
2
3use crate::crypto::network::digest::sha384;
4use crate::net::peer::runtime::incarnation::CanonicalIncarnation;
5use crate::net::qdnf::errors::QdnfError;
6use crate::net::qdnf::types::{Generation, OperationId, ProfileId, StrongDigest};
7
8use super::digest_bind::AuthorityBinding;
9use super::permit::ExecutionPermit;
10use super::policy::{ContactState, TemporalGrant};
11use super::verified::{AuthorisedContact, VerifiedCredential};
12
13mod retirement;
14
15const MAX_RECORDS: usize = 8;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18struct Record {
19    occupied: bool,
20    generation: Generation,
21    principal: StrongDigest,
22    recipient: StrongDigest,
23    purpose: StrongDigest,
24    instrument: StrongDigest,
25    scope: StrongDigest,
26    operation: OperationId,
27    not_before_unix: u64,
28    resource_ceiling: u64,
29    expires_unix: u64,
30    contact: ContactState,
31    revoked: bool,
32}
33
34impl Record {
35    const EMPTY: Self = Self {
36        occupied: false,
37        generation: Generation::ZERO,
38        principal: StrongDigest::ZERO,
39        recipient: StrongDigest::ZERO,
40        purpose: StrongDigest::ZERO,
41        instrument: StrongDigest::ZERO,
42        scope: StrongDigest::ZERO,
43        operation: OperationId::ZERO,
44        not_before_unix: 0,
45        resource_ceiling: 0,
46        expires_unix: 0,
47        contact: ContactState::Request,
48        revoked: false,
49    };
50}
51
52/// Handle for an asynchronous mutation. Validated against owner-held records.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub struct MutationHandle {
55    slot: u8,
56    generation: Generation,
57    principal: StrongDigest,
58    incarnation: CanonicalIncarnation,
59}
60
61impl MutationHandle {
62    /// `Ok` when `permit` authorizes this handle; `QdnfError` otherwise.
63    pub fn matches_permit(&self, permit: &ExecutionPermit) -> Result<(), QdnfError> {
64        if !self.incarnation.assigned()
65            || !permit.incarnation().assigned()
66            || self.incarnation != permit.incarnation()
67        {
68            return Err(QdnfError::StaleGeneration);
69        }
70        if self.generation != permit.identity_generation() {
71            return Err(QdnfError::StaleGeneration);
72        }
73        if self.principal != permit.principal() {
74            return Err(QdnfError::Unauthorized);
75        }
76        Ok(())
77    }
78}
79
80/// Single owner of verified grants, contacts and permits for this process.
81pub struct AuthorityOwner {
82    incarnation: CanonicalIncarnation,
83    records: [Record; MAX_RECORDS],
84    next_generation: Generation,
85}
86
87impl AuthorityOwner {
88    /// Creates a default `AuthorityOwner`.
89    pub const fn new() -> Self {
90        Self {
91            incarnation: CanonicalIncarnation::UNASSIGNED,
92            records: [Record::EMPTY; MAX_RECORDS],
93            next_generation: Generation::ZERO,
94        }
95    }
96
97    fn free_slot(&self) -> Result<usize, QdnfError> {
98        let mut i = 0;
99        while i < MAX_RECORDS {
100            if !self.records[i].occupied {
101                return Ok(i);
102            }
103            i += 1;
104        }
105        Err(QdnfError::Capacity)
106    }
107
108    /// Compatibility admission with an unlimited per-permit resource ceiling.
109    /// Scope and operation remain pinned. New bounded hosts should use
110    /// `install_grant_with_ceiling`; neither route is a consumable budget ledger.
111    pub fn install_grant(
112        &mut self,
113        binding: AuthorityBinding,
114        now_unix: u64,
115        expires_unix: u64,
116        contact: ContactState,
117    ) -> Result<(VerifiedCredential, AuthorisedContact, MutationHandle), QdnfError> {
118        self.install_grant_with_ceiling(binding, now_unix, expires_unix, contact, u64::MAX)
119    }
120
121    /// Pin the exact admitted binding, validity start and per-permit ceiling.
122    /// This trusted host entry point does not verify human consent by itself.
123    pub fn install_grant_with_ceiling(
124        &mut self,
125        binding: AuthorityBinding,
126        now_unix: u64,
127        expires_unix: u64,
128        contact: ContactState,
129        resource_ceiling: u64,
130    ) -> Result<(VerifiedCredential, AuthorisedContact, MutationHandle), QdnfError> {
131        if expires_unix <= now_unix {
132            return Err(QdnfError::Expired);
133        }
134        if contact != ContactState::Active {
135            return Err(QdnfError::Unauthorized);
136        }
137        if binding.principal.is_zero()
138            || binding.recipient.is_zero()
139            || binding.purpose.is_zero()
140            || binding.instrument.is_zero()
141            || binding.scope.is_zero()
142            || binding.operation.is_zero()
143        {
144            return Err(QdnfError::Unauthorized);
145        }
146        if binding.principal == binding.recipient {
147            return Err(QdnfError::Conflict);
148        }
149        if resource_ceiling == 0 {
150            return Err(QdnfError::Capacity);
151        }
152        let slot = self.free_slot()?;
153        let generation = self.next_generation.next()?;
154        let cred = VerifiedCredential::new(
155            binding.principal,
156            binding.instrument,
157            binding.instrument,
158            generation,
159        )?;
160        let authorised =
161            AuthorisedContact::new(binding.principal, binding.recipient, contact, generation)?;
162        // Every fallible admission check precedes publication/capacity use.
163        // Bind identity only after those checks; a failed install must stay unassigned.
164        let incarnation = self.bind_incarnation()?;
165        let record = Record {
166            occupied: true,
167            generation,
168            principal: binding.principal,
169            recipient: binding.recipient,
170            purpose: binding.purpose,
171            instrument: binding.instrument,
172            scope: binding.scope,
173            operation: binding.operation,
174            not_before_unix: now_unix,
175            resource_ceiling,
176            expires_unix,
177            contact,
178            revoked: false,
179        };
180        let handle = MutationHandle {
181            slot: slot as u8,
182            generation,
183            principal: binding.principal,
184            incarnation,
185        };
186        self.records[slot] = record;
187        self.next_generation = generation;
188        Ok((cred, authorised, handle))
189    }
190
191    /// Revokes `handle`'s grant.
192    pub fn revoke(&mut self, handle: MutationHandle) -> Result<(), QdnfError> {
193        let rec = self.record_mut(handle)?;
194        rec.revoked = true;
195        rec.contact = ContactState::Blocked;
196        Ok(())
197    }
198
199    /// Issues an `ExecutionPermit` for a handle under the current grant.
200    pub fn issue_permit(
201        &self,
202        handle: MutationHandle,
203        binding: AuthorityBinding,
204        now_unix: u64,
205        resource_ceiling: u64,
206    ) -> Result<ExecutionPermit, QdnfError> {
207        let rec = self.record(handle)?;
208        if rec.revoked {
209            return Err(QdnfError::Revoked);
210        }
211        if rec.contact != ContactState::Active {
212            return Err(QdnfError::Denied);
213        }
214        if now_unix >= rec.expires_unix {
215            return Err(QdnfError::Expired);
216        }
217        if now_unix < rec.not_before_unix {
218            return Err(QdnfError::Denied);
219        }
220        if rec.principal != binding.principal
221            || rec.recipient != binding.recipient
222            || rec.purpose != binding.purpose
223            || rec.instrument != binding.instrument
224            || rec.scope != binding.scope
225            || rec.operation != binding.operation
226        {
227            return Err(QdnfError::Unauthorized);
228        }
229        if resource_ceiling > rec.resource_ceiling {
230            return Err(QdnfError::BudgetExhausted);
231        }
232        ExecutionPermit::issue(
233            binding.operation,
234            binding.principal,
235            binding.recipient,
236            binding.purpose,
237            binding.instrument,
238            rec.generation,
239            rec.generation,
240            rec.expires_unix,
241            resource_ceiling,
242            self.existing_incarnation(),
243        )
244    }
245
246    /// Active grant for `handle`; error when none.
247    pub fn current_grant(&self, handle: MutationHandle) -> Result<TemporalGrant, QdnfError> {
248        let rec = self.record(handle)?;
249        if rec.revoked {
250            return Err(QdnfError::Revoked);
251        }
252        Ok(TemporalGrant {
253            purpose_digest: rec.purpose,
254            audience_digest: rec.recipient,
255            authority_generation: rec.generation.0,
256            not_before_unix: rec.not_before_unix,
257            expires_unix: rec.expires_unix,
258            profile: ProfileId::QPR_PQ_1,
259        })
260    }
261
262    /// Check record association/generation only; use `issue_permit` for live rights.
263    pub fn validate_handle(&self, handle: MutationHandle) -> Result<(), QdnfError> {
264        let _ = self.record(handle)?;
265        Ok(())
266    }
267
268    fn record(&self, handle: MutationHandle) -> Result<&Record, QdnfError> {
269        self.require_identity(handle.incarnation)?;
270        let i = handle.slot as usize;
271        if i >= MAX_RECORDS {
272            return Err(QdnfError::Range);
273        }
274        let rec = &self.records[i];
275        if !rec.occupied {
276            return Err(QdnfError::Incomplete);
277        }
278        if rec.generation != handle.generation {
279            return Err(QdnfError::StaleGeneration);
280        }
281        if rec.principal != handle.principal {
282            return Err(QdnfError::Unauthorized);
283        }
284        Ok(rec)
285    }
286
287    fn record_mut(&mut self, handle: MutationHandle) -> Result<&mut Record, QdnfError> {
288        self.require_identity(handle.incarnation)?;
289        let i = handle.slot as usize;
290        if i >= MAX_RECORDS {
291            return Err(QdnfError::Range);
292        }
293        let rec = &mut self.records[i];
294        if !rec.occupied {
295            return Err(QdnfError::Incomplete);
296        }
297        if rec.generation != handle.generation {
298            return Err(QdnfError::StaleGeneration);
299        }
300        if rec.principal != handle.principal {
301            return Err(QdnfError::Unauthorized);
302        }
303        Ok(rec)
304    }
305}
306
307impl Default for AuthorityOwner {
308    fn default() -> Self {
309        Self::new()
310    }
311}
312
313impl AuthorityOwner {
314    pub(crate) fn bind_incarnation(&mut self) -> Result<CanonicalIncarnation, QdnfError> {
315        self.incarnation.bind()
316    }
317
318    pub(crate) const fn existing_incarnation(&self) -> CanonicalIncarnation {
319        self.incarnation
320    }
321
322    fn require_identity(&self, incarnation: CanonicalIncarnation) -> Result<(), QdnfError> {
323        if !incarnation.assigned() || self.incarnation != incarnation {
324            return Err(QdnfError::StaleGeneration);
325        }
326        Ok(())
327    }
328}
329
330/// Helper used by native pairing: hash two controller byte strings into a binding.
331pub fn binding_for_controllers(
332    local: &[u8],
333    remote: &[u8],
334    purpose: &[u8],
335    operation: &[u8],
336) -> Result<AuthorityBinding, QdnfError> {
337    let instrument = sha384(b"qpr-pq-1/known-peer-grant");
338    super::digest_bind::bind_authority_digests(
339        local,
340        remote,
341        &instrument.0,
342        b"qpr-scope/local",
343        purpose,
344        operation,
345    )
346}
347
348#[cfg(test)]
349#[path = "owner_tests.rs"]
350mod tests;