1use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
8use sha2::{Digest, Sha256};
9
10use crate::governance::consent_contract::ConsentGrant;
11
12use super::authorization::{
13 AuthorizationError, SensingAction, SensingModality, SensingRequest, SensingScopeAuthority,
14};
15
16const SCOPE_DOMAIN: &[u8] = b"qualia:sensing-scope:v1\0";
17pub const SIGNED_SCOPE_VERSION: u8 = 1;
18pub const SIGNED_SCOPE_ENCODED_LEN: usize = 211;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum SignedScopeEncodingError {
24 BufferTooSmall { required: usize, available: usize },
25 WrongLength { expected: usize, actual: usize },
26 UnsupportedVersion,
27 InvalidTag,
28 InvalidField,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct SignedSensingScope {
35 grant_id: [u8; 32],
36 grant_digest: [u8; 32],
37 actor_id: [u8; 32],
38 source_id: u64,
39 modality: SensingModality,
40 action: SensingAction,
41 purpose_hash: u64,
42 signer_public_key: [u8; 32],
43 signature: [u8; 64],
44}
45
46impl SignedSensingScope {
47 pub fn sign(
50 grant: &ConsentGrant,
51 signer: &SigningKey,
52 request: SensingRequest,
53 ) -> Result<Self, AuthorizationError> {
54 let signer_public_key = signer.verifying_key().to_bytes();
55 if signer_public_key != grant.principal_did {
56 return Err(AuthorizationError::IdentityUnverified);
57 }
58 verify_grant_signature(grant)?;
59
60 let mut scope = Self {
61 grant_id: grant.grant_id,
62 grant_digest: grant.compute_digest(),
63 actor_id: request.actor_id(),
64 source_id: request.source_id(),
65 modality: request.modality(),
66 action: request.action(),
67 purpose_hash: request.purpose_hash(),
68 signer_public_key,
69 signature: [0; 64],
70 };
71 let message = scope.message_digest();
72 scope.signature = signer.sign(&message).to_bytes();
73 Ok(scope)
74 }
75
76 pub fn encode_into(&self, out: &mut [u8]) -> Result<usize, SignedScopeEncodingError> {
80 if out.len() < SIGNED_SCOPE_ENCODED_LEN {
81 return Err(SignedScopeEncodingError::BufferTooSmall {
82 required: SIGNED_SCOPE_ENCODED_LEN,
83 available: out.len(),
84 });
85 }
86 let mut offset = 0;
87 out[offset] = SIGNED_SCOPE_VERSION;
88 offset += 1;
89 put_bytes(out, &mut offset, &self.grant_id);
90 put_bytes(out, &mut offset, &self.grant_digest);
91 put_bytes(out, &mut offset, &self.actor_id);
92 put_bytes(out, &mut offset, &self.source_id.to_be_bytes());
93 out[offset] = modality_tag(self.modality);
94 offset += 1;
95 out[offset] = action_tag(self.action);
96 offset += 1;
97 put_bytes(out, &mut offset, &self.purpose_hash.to_be_bytes());
98 put_bytes(out, &mut offset, &self.signer_public_key);
99 put_bytes(out, &mut offset, &self.signature);
100 debug_assert_eq!(offset, SIGNED_SCOPE_ENCODED_LEN);
101 Ok(offset)
102 }
103
104 pub fn decode(bytes: &[u8]) -> Result<Self, SignedScopeEncodingError> {
107 if bytes.len() != SIGNED_SCOPE_ENCODED_LEN {
108 return Err(SignedScopeEncodingError::WrongLength {
109 expected: SIGNED_SCOPE_ENCODED_LEN,
110 actual: bytes.len(),
111 });
112 }
113 let mut offset = 0;
114 if take_u8(bytes, &mut offset) != SIGNED_SCOPE_VERSION {
115 return Err(SignedScopeEncodingError::UnsupportedVersion);
116 }
117 let grant_id = take_array::<32>(bytes, &mut offset);
118 let grant_digest = take_array::<32>(bytes, &mut offset);
119 let actor_id = take_array::<32>(bytes, &mut offset);
120 let source_id = u64::from_be_bytes(take_array::<8>(bytes, &mut offset));
121 let modality = modality_from_tag(take_u8(bytes, &mut offset))?;
122 let action = action_from_tag(take_u8(bytes, &mut offset))?;
123 let purpose_hash = u64::from_be_bytes(take_array::<8>(bytes, &mut offset));
124 let signer_public_key = take_array::<32>(bytes, &mut offset);
125 let signature = take_array::<64>(bytes, &mut offset);
126 debug_assert_eq!(offset, SIGNED_SCOPE_ENCODED_LEN);
127 if grant_id == [0; 32]
128 || actor_id == [0; 32]
129 || source_id == 0
130 || purpose_hash == 0
131 || signer_public_key == [0; 32]
132 {
133 return Err(SignedScopeEncodingError::InvalidField);
134 }
135 Ok(Self {
136 grant_id,
137 grant_digest,
138 actor_id,
139 source_id,
140 modality,
141 action,
142 purpose_hash,
143 signer_public_key,
144 signature,
145 })
146 }
147
148 pub const fn grant_id(self) -> [u8; 32] {
149 self.grant_id
150 }
151 pub const fn grant_digest(self) -> [u8; 32] {
152 self.grant_digest
153 }
154 pub const fn actor_id(self) -> [u8; 32] {
155 self.actor_id
156 }
157 pub const fn source_id(self) -> u64 {
158 self.source_id
159 }
160 pub const fn modality(self) -> SensingModality {
161 self.modality
162 }
163 pub const fn action(self) -> SensingAction {
164 self.action
165 }
166 pub const fn purpose_hash(self) -> u64 {
167 self.purpose_hash
168 }
169
170 fn message_digest(&self) -> [u8; 32] {
171 let mut hash = Sha256::new();
172 hash.update(SCOPE_DOMAIN);
173 hash.update(self.grant_id);
174 hash.update(self.grant_digest);
175 hash.update(self.actor_id);
176 hash.update(self.source_id.to_be_bytes());
177 hash.update([modality_tag(self.modality)]);
178 hash.update([action_tag(self.action)]);
179 hash.update(self.purpose_hash.to_be_bytes());
180 hash.update(self.signer_public_key);
181 hash.finalize().into()
182 }
183
184 fn verify_for(
185 &self,
186 grant: &ConsentGrant,
187 expected_grant_digest: &[u8; 32],
188 request: &SensingRequest,
189 ) -> Result<(), AuthorizationError> {
190 if self.grant_id != grant.grant_id
191 || self.grant_digest != *expected_grant_digest
192 || self.grant_digest != grant.compute_digest()
193 {
194 return Err(AuthorizationError::InvalidGrant);
195 }
196 if self.signer_public_key != grant.principal_did {
197 return Err(AuthorizationError::IdentityUnverified);
198 }
199 if self.actor_id != request.actor_id()
200 || self.source_id != request.source_id()
201 || self.modality != request.modality()
202 || self.action != request.action()
203 || self.purpose_hash != request.purpose_hash()
204 {
205 return Err(AuthorizationError::UnsupportedSensorScope);
206 }
207 verify_grant_signature(grant)?;
208 let key = VerifyingKey::from_bytes(&self.signer_public_key)
209 .map_err(|_| AuthorizationError::IdentityUnverified)?;
210 key.verify_strict(
211 &self.message_digest(),
212 &Signature::from_bytes(&self.signature),
213 )
214 .map_err(|_| AuthorizationError::IdentityUnverified)
215 }
216}
217
218impl SensingScopeAuthority for SignedSensingScope {
219 fn verify_scope(
220 &self,
221 grant: &ConsentGrant,
222 grant_digest: &[u8; 32],
223 request: &SensingRequest,
224 ) -> Result<(), AuthorizationError> {
225 self.verify_for(grant, grant_digest, request)
226 }
227}
228
229fn verify_grant_signature(grant: &ConsentGrant) -> Result<(), AuthorizationError> {
232 let key = VerifyingKey::from_bytes(&grant.principal_did)
233 .map_err(|_| AuthorizationError::InvalidGrant)?;
234 key.verify_strict(
235 &grant.compute_digest(),
236 &Signature::from_bytes(&grant.signature),
237 )
238 .map_err(|_| AuthorizationError::InvalidGrant)
239}
240
241fn modality_tag(value: SensingModality) -> u8 {
242 match value {
243 SensingModality::Wifi => 1,
244 SensingModality::Bluetooth => 2,
245 SensingModality::Cellular => 3,
246 SensingModality::Sdr => 4,
247 SensingModality::Radar => 5,
248 SensingModality::VisibleCamera => 6,
249 SensingModality::NearInfraredCamera => 7,
250 SensingModality::ThermalCamera => 8,
251 SensingModality::Microphone => 9,
252 SensingModality::FieldInstrument => 10,
253 SensingModality::Nfc => 11,
254 }
255}
256
257fn action_tag(value: SensingAction) -> u8 {
258 match value {
259 SensingAction::Acquire => 1,
260 SensingAction::Process => 2,
261 SensingAction::Store => 3,
262 SensingAction::Export => 4,
263 SensingAction::Share => 5,
264 }
265}
266
267fn modality_from_tag(tag: u8) -> Result<SensingModality, SignedScopeEncodingError> {
268 match tag {
269 1 => Ok(SensingModality::Wifi),
270 2 => Ok(SensingModality::Bluetooth),
271 3 => Ok(SensingModality::Cellular),
272 4 => Ok(SensingModality::Sdr),
273 5 => Ok(SensingModality::Radar),
274 6 => Ok(SensingModality::VisibleCamera),
275 7 => Ok(SensingModality::NearInfraredCamera),
276 8 => Ok(SensingModality::ThermalCamera),
277 9 => Ok(SensingModality::Microphone),
278 10 => Ok(SensingModality::FieldInstrument),
279 11 => Ok(SensingModality::Nfc),
280 _ => Err(SignedScopeEncodingError::InvalidTag),
281 }
282}
283
284fn action_from_tag(tag: u8) -> Result<SensingAction, SignedScopeEncodingError> {
285 match tag {
286 1 => Ok(SensingAction::Acquire),
287 2 => Ok(SensingAction::Process),
288 3 => Ok(SensingAction::Store),
289 4 => Ok(SensingAction::Export),
290 5 => Ok(SensingAction::Share),
291 _ => Err(SignedScopeEncodingError::InvalidTag),
292 }
293}
294
295fn put_bytes<const N: usize>(out: &mut [u8], offset: &mut usize, value: &[u8; N]) {
296 out[*offset..*offset + N].copy_from_slice(value);
297 *offset += N;
298}
299
300fn take_u8(bytes: &[u8], offset: &mut usize) -> u8 {
301 let value = bytes[*offset];
302 *offset += 1;
303 value
304}
305
306fn take_array<const N: usize>(bytes: &[u8], offset: &mut usize) -> [u8; N] {
307 let mut value = [0; N];
308 value.copy_from_slice(&bytes[*offset..*offset + N]);
309 *offset += N;
310 value
311}
312
313#[cfg(test)]
314#[path = "signed_scope_tests.rs"]
315mod tests;