qualia_core_db/bundle/stream/policy/remote/
grant.rs1use super::decision::DisclosureDecision;
3use super::{
4 check_recipient_against_independent, decode_decision_ticket, IndependentAdmission,
5 PolicyError as E, RecognizedController, DECISION_TICKET_BYTES, DISCLOSURE_DECISION_PURPOSE,
6 RECIPIENT_PURPOSE,
7};
8use crate::crypto::network::authority::{
9 AuthorityReceipt, AuthoritySource, PinAuthority, PinHandle,
10};
11use crate::crypto::network::cose::{self, Binding};
12use crate::crypto::network::digest::sha384;
13use crate::crypto::network::entropy::fill_os;
14use crate::crypto::network::errors::CryptoError;
15use crate::crypto::network::object_stream::RecipientRecord;
16use crate::net::peer::runtime::incarnation::CanonicalIncarnation;
17use crate::net::qdnf::authority::{
18 AuthorityBinding, AuthorityOwner, ContactState, CurrentAuthorityGuard, MutationHandle,
19};
20use crate::net::qdnf::errors::QdnfError;
21use crate::net::qdnf::types::{OperationId, StrongDigest};
22use std::sync::{Mutex, TryLockError};
23
24pub struct VerifierChallengeSlot {
26 owner: usize,
27 incarnation: CanonicalIncarnation,
28 transcript: StrongDigest,
29 request_id: OperationId,
30 challenge: [u8; 32],
31 state: SlotState,
32}
33
34#[derive(Clone, Copy, PartialEq, Eq)]
35enum SlotState {
36 Empty,
37 Outstanding,
38 Consumed,
39}
40
41impl VerifierChallengeSlot {
42 pub const fn new() -> Self {
43 Self {
44 owner: 0,
45 incarnation: CanonicalIncarnation::UNASSIGNED,
46 transcript: StrongDigest::ZERO,
47 request_id: OperationId::ZERO,
48 challenge: [0; 32],
49 state: SlotState::Empty,
50 }
51 }
52
53 pub fn issue(
55 &mut self,
56 owner: &Mutex<AuthorityOwner>,
57 transcript: StrongDigest,
58 request_id: OperationId,
59 ) -> Result<[u8; 32], E> {
60 if self.state == SlotState::Outstanding {
61 return Err(E::Capacity);
62 }
63 if transcript.is_zero() || request_id.is_zero() {
64 return Err(E::Reference);
65 }
66 let incarnation = snapshot_incarnation(owner)?;
67 let mut challenge = [0u8; 32];
68 fill_os(&mut challenge).map_err(E::Crypto)?;
69 if challenge.iter().all(|b| *b == 0) {
70 return Err(E::Crypto(CryptoError::EntropyFailure));
71 }
72 self.owner = owner as *const Mutex<AuthorityOwner> as usize;
73 self.incarnation = incarnation;
74 self.transcript = transcript;
75 self.request_id = request_id;
76 self.challenge = challenge;
77 self.state = SlotState::Outstanding;
78 Ok(challenge)
79 }
80
81 fn consume(
82 &mut self,
83 owner: &Mutex<AuthorityOwner>,
84 transcript: StrongDigest,
85 request_id: OperationId,
86 challenge: [u8; 32],
87 ) -> Result<(), E> {
88 match self.state {
89 SlotState::Empty => return Err(E::Crypto(CryptoError::Unauthorized)),
90 SlotState::Consumed => return Err(E::Authority(QdnfError::Replay)),
91 SlotState::Outstanding => {}
92 }
93 let incarnation = snapshot_incarnation(owner)?;
94 if self.owner != owner as *const Mutex<AuthorityOwner> as usize
95 || self.transcript != transcript
96 || self.request_id != request_id
97 || self.challenge != challenge
98 {
99 return Err(E::Authority(QdnfError::Replay));
100 }
101 if self.incarnation != incarnation {
102 return Err(E::Authority(QdnfError::StaleGeneration));
103 }
104 self.state = SlotState::Consumed;
105 Ok(())
106 }
107}
108
109impl Default for VerifierChallengeSlot {
110 fn default() -> Self {
111 Self::new()
112 }
113}
114
115fn snapshot_incarnation(owner: &Mutex<AuthorityOwner>) -> Result<CanonicalIncarnation, E> {
116 let inner = owner.try_lock().map_err(lock_err)?;
117 Ok(inner.existing_incarnation())
118}
119
120fn lock_err(e: TryLockError<std::sync::MutexGuard<'_, AuthorityOwner>>) -> E {
121 match e {
122 TryLockError::WouldBlock => E::Authority(QdnfError::WouldBlock),
123 TryLockError::Poisoned(_) => E::Authority(QdnfError::Unauthorized),
124 }
125}
126
127pub struct InstallRequest<'owner, 'tmp> {
130 pub owner: &'owner Mutex<AuthorityOwner>,
131 pub pins: &'tmp PinAuthority,
132 pub recognition: &'tmp super::ControllerRecognition,
133 pub recognized: RecognizedController,
134 pub decision_pin: PinHandle,
135 pub independent: IndependentAdmission,
136 pub recipient_bytes: &'tmp [u8],
137 pub recipient_envelope: &'tmp [u8],
138 pub ticket_bytes: &'tmp [u8],
139 pub ticket_envelope: &'tmp [u8],
140 pub audience: &'tmp [u8],
141 pub now: u64,
142 pub ceiling: u64,
143}
144
145pub struct RemoteDisclosureGrant<'a> {
147 pub(super) owner: &'a Mutex<AuthorityOwner>,
148 pub(super) handle: MutationHandle,
149 pub(super) binding: AuthorityBinding,
150 pub(super) ceiling: u64,
151 pub(super) decision: DisclosureDecision,
152 pub(super) recognized: RecognizedController,
153 pub(super) receipt_a: AuthorityReceipt,
154 pub(super) receipt_ticket: AuthorityReceipt,
155 pub(super) descriptor_a: [u8; 48],
156 pub(super) descriptor_ticket: [u8; 48],
157 pub(super) revoked: bool,
158 pub(super) closed: bool,
159}
160
161impl<'a> RemoteDisclosureGrant<'a> {
162 pub fn receipt_a(&self) -> &AuthorityReceipt {
163 &self.receipt_a
164 }
165 pub fn receipt_ticket(&self) -> &AuthorityReceipt {
166 &self.receipt_ticket
167 }
168 pub fn decision(&self) -> &DisclosureDecision {
169 &self.decision
170 }
171 pub fn binding(&self) -> AuthorityBinding {
172 self.binding
173 }
174 pub fn recognized(&self) -> RecognizedController {
175 self.recognized
176 }
177}
178
179pub fn install_remote_disclosure<'owner, 'tmp>(
181 request: InstallRequest<'owner, 'tmp>,
182 challenge: &mut VerifierChallengeSlot,
183 workspace: &mut cose::Workspace,
184) -> Result<RemoteDisclosureGrant<'owner>, E> {
185 if request.ceiling == 0 {
186 return Err(E::Limit);
187 }
188 request.recognized.current_at(request.now)?;
189 let record = RecipientRecord::parse(request.recipient_bytes).map_err(E::Crypto)?;
190 check_recipient_against_independent(&record, &request.independent)?;
191 record.valid_at(request.now).map_err(E::Crypto)?;
192 if request.ticket_bytes.len() != DECISION_TICKET_BYTES {
193 return Err(E::Encoding);
194 }
195 let ticket = decode_decision_ticket(request.ticket_bytes)?;
196 let live = super::issuer::join_enrollment(
197 request.recognition,
198 &request.recognized,
199 &request.independent,
200 ticket.action,
201 request.now,
202 )?;
203
204 let rec_id = record.id();
205 let rec_binding = expected_binding(
206 request.recipient_envelope,
207 &rec_id.0,
208 RECIPIENT_PURPOSE,
209 request.audience,
210 )?;
211 let receipt_a = request
212 .pins
213 .verify_source(
214 AuthoritySource::LocalPin(request.recognized.pin()),
215 request.recipient_envelope,
216 &rec_binding,
217 request.now,
218 workspace,
219 )
220 .map_err(E::Crypto)?;
221 request
222 .pins
223 .recheck(&receipt_a, &rec_id.0, request.now)
224 .map_err(E::Crypto)?;
225 if receipt_a.principal() != request.recognized.principal() {
226 return Err(E::Reference);
227 }
228
229 if ticket.recipient_record_id != rec_id {
230 return Err(E::Reference);
231 }
232 let ticket_digest = sha384(request.ticket_bytes);
233 let tkt_binding = expected_binding(
234 request.ticket_envelope,
235 &ticket_digest.0,
236 DISCLOSURE_DECISION_PURPOSE,
237 request.audience,
238 )?;
239 let receipt_ticket = request
240 .pins
241 .verify_source(
242 AuthoritySource::LocalPin(request.decision_pin),
243 request.ticket_envelope,
244 &tkt_binding,
245 request.now,
246 workspace,
247 )
248 .map_err(E::Crypto)?;
249 request
250 .pins
251 .recheck(&receipt_ticket, &ticket_digest.0, request.now)
252 .map_err(E::Crypto)?;
253 if receipt_ticket.principal() != request.recognized.principal() {
254 return Err(E::Reference);
255 }
256
257 let decision = DisclosureDecision::bind(&live, &ticket, request.now)?;
258 challenge.consume(
259 request.owner,
260 ticket.transcript,
261 ticket.request_id,
262 ticket.challenge,
263 )?;
264
265 let binding = AuthorityBinding {
266 principal: request.recognized.principal(),
267 recipient: request.independent.recipient,
268 instrument: request.independent.instrument,
269 scope: request.independent.scope,
270 purpose: request.independent.purpose,
271 operation: OperationId(request.independent.operation),
272 };
273 if binding.principal == binding.recipient {
274 return Err(E::Authority(QdnfError::Conflict));
275 }
276
277 let handle = install_under_current(
278 request.owner,
279 binding,
280 request.now,
281 decision.expires(),
282 request.ceiling,
283 )?;
284
285 Ok(RemoteDisclosureGrant {
286 owner: request.owner,
287 handle,
288 binding,
289 ceiling: request.ceiling,
290 decision,
291 recognized: live,
292 receipt_a,
293 receipt_ticket,
294 descriptor_a: rec_id.0,
295 descriptor_ticket: ticket_digest.0,
296 revoked: false,
297 closed: false,
298 })
299}
300
301fn expected_binding<'a>(
304 envelope: &'a [u8],
305 descriptor: &[u8; 48],
306 purpose: &[u8],
307 audience: &[u8],
308) -> Result<Binding<'a>, E> {
309 let parsed = cose::decode_pair(envelope).map_err(E::Crypto)?;
310 let binding = *parsed.binding();
311 if binding.descriptor_digest != descriptor
312 || binding.purpose != purpose
313 || binding.audience != audience
314 {
315 return Err(E::Crypto(CryptoError::Unauthorized));
316 }
317 Ok(binding)
318}
319
320fn install_under_current(
321 owner: &Mutex<AuthorityOwner>,
322 binding: AuthorityBinding,
323 now: u64,
324 expires: u64,
325 ceiling: u64,
326) -> Result<MutationHandle, E> {
327 {
331 let _guard = CurrentAuthorityGuard::try_lock(owner).map_err(E::Authority)?;
332 }
333 let mut inner = owner.try_lock().map_err(lock_err)?;
334 let (_, _, handle) = inner
335 .install_grant_with_ceiling(binding, now, expires, ContactState::Active, ceiling)
336 .map_err(E::Authority)?;
337 Ok(handle)
338}