Skip to main content

qualia_core_db/sensing/
authorization.rs

1//! Fail-closed bridge from signed QualiaDB consent to source-bound sensing authority.
2//!
3//! The existing `ConsentScope` covers health record families, not sensor sources or
4//! acquisition/processing acts. This module therefore requires host-provided identity,
5//! sensor-scope, revocation, and trusted-clock authorities. It never treats a Quin or
6//! caller-supplied identity projection as authorization.
7//!
8//! This is one optional adapter for the existing signed grant, not the sole
9//! policy framework for sensing. The host must separately resolve data-subject
10//! ownership and any applicable guardianship through its selected policy system;
11//! this module alone does not bind or decide those relationships.
12
13use crate::governance::consent_contract::{ConsentError, ConsentGrant};
14
15/// Sensor family selected by the caller. NFC is distinct from Bluetooth even
16/// when both observations contain radio protocol identifiers. Unknown or
17/// future families need an explicit policy implementation before authorization.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum SensingModality {
20    Wifi,
21    Bluetooth,
22    Cellular,
23    Sdr,
24    Radar,
25    VisibleCamera,
26    NearInfraredCamera,
27    ThermalCamera,
28    Microphone,
29    FieldInstrument,
30    Nfc,
31}
32
33/// Distinct actions so capture consent cannot implicitly authorize later use.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum SensingAction {
36    Acquire,
37    Process,
38    Store,
39    Export,
40    Share,
41}
42
43/// Exact operation requested under a consent grant.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct SensingRequest {
46    actor_id: [u8; 32],
47    source_id: u64,
48    modality: SensingModality,
49    action: SensingAction,
50    purpose_hash: u64,
51}
52
53impl SensingRequest {
54    pub fn new(
55        actor_id: [u8; 32],
56        source_id: u64,
57        modality: SensingModality,
58        action: SensingAction,
59        purpose_hash: u64,
60    ) -> Result<Self, AuthorizationError> {
61        if source_id == 0 || purpose_hash == 0 || actor_id == [0; 32] {
62            return Err(AuthorizationError::InvalidRequest);
63        }
64        Ok(Self {
65            actor_id,
66            source_id,
67            modality,
68            action,
69            purpose_hash,
70        })
71    }
72
73    pub const fn actor_id(self) -> [u8; 32] {
74        self.actor_id
75    }
76    pub const fn source_id(self) -> u64 {
77        self.source_id
78    }
79    pub const fn modality(self) -> SensingModality {
80        self.modality
81    }
82    pub const fn action(self) -> SensingAction {
83        self.action
84    }
85    pub const fn purpose_hash(self) -> u64 {
86        self.purpose_hash
87    }
88}
89
90/// Required fail-closed integration authorities. Implementations are trust
91/// boundaries and must be backed by authenticated identity, a sensor-specific
92/// signed scope assertion, durable revocation state, and a trusted clock.
93pub trait IdentityAuthority {
94    /// Bind the grant's signing key to an accepted human/authority identity and
95    /// authenticate the actor as the grant recipient. Do not infer identity from
96    /// public-key possession or nonzero hashes alone.
97    fn verify_parties(
98        &self,
99        grant: &ConsentGrant,
100        actor_id: &[u8; 32],
101    ) -> Result<(), AuthorizationError>;
102}
103
104pub trait SensingScopeAuthority {
105    /// Verify that a signed scope bound to this grant's digest permits this exact
106    /// source, modality, action, and purpose. Mapping a health-category bit alone
107    /// to sensor permission is insufficient.
108    fn verify_scope(
109        &self,
110        grant: &ConsentGrant,
111        grant_digest: &[u8; 32],
112        request: &SensingRequest,
113    ) -> Result<(), AuthorizationError>;
114}
115
116pub trait RevocationAuthority {
117    /// Revalidate complete, restart-safe state for this exact grant digest at the
118    /// broker's trusted current time. Implementations must recheck checkpoint
119    /// freshness/anti-rollback on every call; unknown state is an error, never false.
120    fn is_revoked(
121        &self,
122        grant_id: &[u8; 32],
123        grant_digest: &[u8; 32],
124        current_time_unix: u64,
125    ) -> Result<bool, AuthorizationError>;
126}
127
128pub trait TrustedUnixClock {
129    /// Trusted anti-rollback Unix seconds. This timestamp is not supplied by the
130    /// request or inferred from the sensor's untrusted metadata.
131    fn now_unix(&mut self) -> Result<u64, AuthorizationError>;
132}
133
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135pub enum AuthorizationError {
136    InvalidRequest,
137    InvalidGrant,
138    GrantNotYetValid,
139    GrantExpired,
140    PurposeMismatch,
141    ActorMismatch,
142    IdentityUnverified,
143    UnsupportedSensorScope,
144    RevocationUnknown,
145    Revoked,
146    ClockUnavailable,
147}
148
149/// One-shot policy decision, not durable authorization. Before use, consume it
150/// through `revalidate`, which rechecks trusted time, identity, scope and live
151/// revocation. It is not a device receipt or proof that capture occurred.
152#[derive(Debug, PartialEq, Eq)]
153pub struct SensingPermit {
154    grant_id: [u8; 32],
155    grant_digest: [u8; 32],
156    request: SensingRequest,
157    issued_at_unix: u64,
158    expires_at_unix: u64,
159}
160
161impl SensingPermit {
162    pub const fn grant_id(&self) -> [u8; 32] {
163        self.grant_id
164    }
165    pub const fn grant_digest(&self) -> [u8; 32] {
166        self.grant_digest
167    }
168    pub const fn request(&self) -> SensingRequest {
169        self.request
170    }
171    pub const fn issued_at_unix(&self) -> u64 {
172        self.issued_at_unix
173    }
174    pub const fn expires_at_unix(&self) -> u64 {
175        self.expires_at_unix
176    }
177
178    /// Consume this decision and re-run every authorization gate immediately
179    /// before one operation. The returned non-copy handle is intended to be
180    /// moved directly into that operation and cannot be reused to authorize a
181    /// second request.
182    pub fn revalidate(
183        self,
184        grant: &ConsentGrant,
185        identity: &impl IdentityAuthority,
186        sensor_scope: &impl SensingScopeAuthority,
187        revocations: &impl RevocationAuthority,
188        clock: &mut impl TrustedUnixClock,
189    ) -> Result<RevalidatedSensingUse, AuthorizationError> {
190        if self.grant_id != grant.grant_id
191            || self.grant_digest != grant.compute_digest()
192            || self.request.actor_id != grant.recipient_did
193        {
194            return Err(AuthorizationError::InvalidGrant);
195        }
196        let fresh = authorize_sensing(
197            grant,
198            self.request,
199            identity,
200            sensor_scope,
201            revocations,
202            clock,
203        )?;
204        Ok(RevalidatedSensingUse {
205            grant_id: fresh.grant_id,
206            grant_digest: fresh.grant_digest,
207            request: fresh.request,
208            checked_at_unix: fresh.issued_at_unix,
209        })
210    }
211}
212
213/// Fresh, non-copy, exact-request handle for one immediate operation. It carries
214/// no persistent authority; callers must consume it at the operation boundary.
215#[derive(Debug, PartialEq, Eq)]
216pub struct RevalidatedSensingUse {
217    grant_id: [u8; 32],
218    grant_digest: [u8; 32],
219    request: SensingRequest,
220    checked_at_unix: u64,
221}
222
223impl RevalidatedSensingUse {
224    pub const fn grant_id(&self) -> [u8; 32] {
225        self.grant_id
226    }
227    pub const fn grant_digest(&self) -> [u8; 32] {
228        self.grant_digest
229    }
230    pub const fn request(&self) -> SensingRequest {
231        self.request
232    }
233    pub const fn checked_at_unix(&self) -> u64 {
234        self.checked_at_unix
235    }
236}
237
238/// Verify grant signature/expiry, principal-recipient binding, exact purpose,
239/// sensor scope, and complete revocation state before minting a permit.
240pub fn authorize_sensing(
241    grant: &ConsentGrant,
242    request: SensingRequest,
243    identity: &impl IdentityAuthority,
244    sensor_scope: &impl SensingScopeAuthority,
245    revocations: &impl RevocationAuthority,
246    clock: &mut impl TrustedUnixClock,
247) -> Result<SensingPermit, AuthorizationError> {
248    if request.actor_id != grant.recipient_did {
249        return Err(AuthorizationError::ActorMismatch);
250    }
251    if request.purpose_hash != grant.purpose_hash {
252        return Err(AuthorizationError::PurposeMismatch);
253    }
254    if grant.grant_id == [0; 32] || grant.nonce == 0 || grant.created_at >= grant.expires_at {
255        return Err(AuthorizationError::InvalidGrant);
256    }
257
258    let now = clock.now_unix()?;
259    if now < grant.created_at {
260        return Err(AuthorizationError::GrantNotYetValid);
261    }
262    grant.verify(now).map_err(map_consent_error)?;
263    identity.verify_parties(grant, &request.actor_id)?;
264    let grant_digest = grant.compute_digest();
265    let revoked = revocations
266        .is_revoked(&grant.grant_id, &grant_digest, now)
267        .map_err(|_| AuthorizationError::RevocationUnknown)?;
268    if revoked {
269        return Err(AuthorizationError::Revoked);
270    }
271    sensor_scope.verify_scope(grant, &grant_digest, &request)?;
272
273    // External authority callbacks may take time or observe revocation. Take
274    // a fresh trusted time and revocation snapshot after they return.
275    let final_now = clock.now_unix()?;
276    if final_now < now {
277        return Err(AuthorizationError::ClockUnavailable);
278    }
279    grant.verify(final_now).map_err(map_consent_error)?;
280    if revocations
281        .is_revoked(&grant.grant_id, &grant_digest, final_now)
282        .map_err(|_| AuthorizationError::RevocationUnknown)?
283    {
284        return Err(AuthorizationError::Revoked);
285    }
286    let issued_at = clock.now_unix()?;
287    if issued_at < final_now {
288        return Err(AuthorizationError::ClockUnavailable);
289    }
290    grant.verify(issued_at).map_err(map_consent_error)?;
291
292    Ok(SensingPermit {
293        grant_id: grant.grant_id,
294        grant_digest,
295        request,
296        issued_at_unix: issued_at,
297        expires_at_unix: grant.expires_at,
298    })
299}
300
301fn map_consent_error(error: ConsentError) -> AuthorizationError {
302    match error {
303        ConsentError::Expired { .. } => AuthorizationError::GrantExpired,
304        ConsentError::RequesterMismatch => AuthorizationError::ActorMismatch,
305        ConsentError::Revoked { .. } => AuthorizationError::Revoked,
306        _ => AuthorizationError::InvalidGrant,
307    }
308}
309
310#[cfg(test)]
311#[path = "authorization_tests.rs"]
312mod tests;