Skip to main content

qualia_core_db/bundle/stream/policy/
grant.rs

1//! Explicit local admin adoption through the existing concrete QDNF grant owner.
2mod scoped;
3pub use scoped::LocalEffectControl;
4
5use super::{BoundClosure, PolicyError as E};
6use crate::crypto::network::{authority::PinAuthority, digest::sha384};
7use crate::net::qdnf::{
8    authority::{AuthorityBinding, AuthorityOwner, ContactState, MutationHandle},
9    types::{OperationId, StrongDigest},
10};
11
12/// Trusted local administrative decision, NOT a wire grant or consent proof.
13/// The host establishes rights for ALL bytes (header/index/gaps/all entries),
14/// exact recipient and purpose through its existing governance owners first.
15/// No partial/mixed/unknown coverage profile is supported by this entry point.
16pub struct LocalGrantRequest {
17    pub principal: StrongDigest,
18    pub recipient: StrongDigest,
19    pub purpose: StrongDigest,
20    pub operation: OperationId,
21    pub not_before: u64,
22    pub expires: u64,
23    pub resource_ceiling: u64,
24}
25/// Concrete owner borrow is retained from installation through final use. The
26/// private handle cannot be rebound to an unrelated similarly populated owner.
27/// Holding this guard excludes other grant mutations; hosts must keep it short.
28pub struct LocalWholeSourceGrant<'a, 'data> {
29    owner: &'a mut AuthorityOwner,
30    closure: &'a BoundClosure<'data>,
31    handle: MutationHandle,
32    binding: AuthorityBinding,
33    ceiling: u64,
34    spent: bool,
35    closed: bool,
36}
37fn whole_scope(closure: &BoundClosure<'_>) -> StrongDigest {
38    let identity = closure.identity();
39    let manifest = closure.closure();
40    let fields = manifest.manifest().fields();
41    let mut frame = [0u8; 512];
42    let prefix = b"QBDL-LOCAL-WHOLE-SOURCE-V1\0";
43    frame[..prefix.len()].copy_from_slice(prefix);
44    let mut n = prefix.len();
45    for digest in [
46        identity.descriptor_id(),
47        identity.context_id(),
48        manifest.manifest_digest(),
49        fields.source,
50        fields.policy,
51        fields.consumer,
52    ] {
53        frame[n..n + 48].copy_from_slice(&digest.0);
54        n += 48;
55    }
56    frame[n..n + 8].copy_from_slice(&fields.source_length.to_be_bytes());
57    n += 8;
58    frame[n] = 1; // Whole source, including framing and gaps. No partial variant.
59    sha384(&frame[..n + 1])
60}
61/// Trusted admin bootstrap, analogous to AuthorityOwner's existing installer.
62/// This is NOT remote Share/Sentinel/consent integration. No policy evaluator or
63/// wire parser may call this merely because a manifest signature verified.
64pub fn adopt_local_whole_source<'a, 'data>(
65    owner: &'a mut AuthorityOwner,
66    pins: &PinAuthority,
67    closure: &'a BoundClosure<'data>,
68    request: LocalGrantRequest,
69) -> Result<LocalWholeSourceGrant<'a, 'data>, E> {
70    closure.recheck(pins, request.not_before)?;
71    let source_length = closure.closure().manifest().fields().source_length;
72    if request.resource_ceiling < source_length {
73        return Err(E::Limit);
74    }
75    let binding = AuthorityBinding {
76        principal: request.principal,
77        recipient: request.recipient,
78        purpose: request.purpose,
79        operation: request.operation,
80        instrument: closure.closure().manifest_digest(),
81        scope: whole_scope(closure),
82    };
83    let (_, _, handle) = owner
84        .install_grant_with_ceiling(
85            binding,
86            request.not_before,
87            request.expires,
88            ContactState::Active,
89            request.resource_ceiling,
90        )
91        .map_err(E::Authority)?;
92    Ok(LocalWholeSourceGrant {
93        owner,
94        closure,
95        handle,
96        binding,
97        ceiling: request.resource_ceiling,
98        spent: false,
99        closed: false,
100    })
101}
102impl LocalWholeSourceGrant<'_, '_> {
103    /// Host cancellation/revocation is terminal and goes through the SAME owner.
104    pub fn cancel(&mut self) -> Result<(), E> {
105        self.spent = true;
106        self.owner.revoke(self.handle).map_err(E::Authority)
107    }
108    pub fn binding(&self) -> AuthorityBinding {
109        self.binding
110    }
111    /// Drain this synchronous guard, revoke and explicitly reclaim its record.
112    pub fn close(mut self) -> Result<(), E> {
113        self.release()
114    }
115    fn release(&mut self) -> Result<(), E> {
116        if self.closed {
117            return Ok(());
118        }
119        self.spent = true;
120        self.owner.revoke(self.handle).map_err(E::Authority)?;
121        self.owner
122            .retire_revoked(self.handle)
123            .map_err(E::Authority)?;
124        self.closed = true;
125        Ok(())
126    }
127    /// One bounded synchronous host effect. The host clock is trusted and must
128    /// be freshly sampled; this is not a wire timestamp. Callback must not await
129    /// or retain authority. Failure/unwind is terminal. No ExecutionPermit escapes.
130    /// This does not certify payload proofs, resource reservations or durable IO.
131    pub fn accept_local<T>(
132        &mut self,
133        pins: &PinAuthority,
134        clock: impl Fn() -> u64,
135        accept: impl FnOnce(&BoundClosure<'_>) -> Result<T, E>,
136    ) -> Result<T, E> {
137        if self.spent {
138            return Err(E::Spent);
139        }
140        self.spent = true;
141        let now = clock();
142        self.closure.recheck(pins, now)?;
143        let _permit = self
144            .owner
145            .issue_permit(self.handle, self.binding, now, self.ceiling)
146            .map_err(E::Authority)?;
147        // The second sample closes verification work time; concrete borrows keep
148        // both authority owners unchanged through this final check and effect.
149        let now = clock();
150        self.closure.recheck(pins, now)?;
151        self.owner
152            .issue_permit(self.handle, self.binding, now, self.ceiling)
153            .map_err(E::Authority)?;
154        accept(self.closure)
155    }
156}
157
158impl Drop for LocalWholeSourceGrant<'_, '_> {
159    fn drop(&mut self) {
160        // Exclusive owner borrow and synchronous callback exclude pending uses.
161        let _ = self.release();
162    }
163}