1use std::sync::Arc;
5
6use astrid_core::identity::PrincipalUid;
7use astrid_core::{PrincipalId, SessionId, Timestamp};
8use astrid_crypto::{ContentHash, KeyPair, PublicKey};
9
10use super::{AuditError, AuditLog, AuditResult};
11use crate::entry::{AuditAction, AuditEntry, AuditEntryFormat, AuditOutcome, AuthorizationProof};
12use crate::entry_v2::{
13 AuditActor, EntryV2Draft, KeyRegistry, KeyRegistryRecord, KeyRole, derive_chain_id,
14};
15
16pub trait PrincipalUidResolver: Send + Sync {
18 fn resolve_uid(&self, principal: &PrincipalId) -> Option<PrincipalUid>;
20}
21
22impl PrincipalUidResolver for astrid_storage::PrincipalDirectory {
23 fn resolve_uid(&self, principal: &PrincipalId) -> Option<PrincipalUid> {
24 self.uid_for(principal).ok()
25 }
26}
27
28pub struct EntryV2Config {
30 pub audit_key: Arc<KeyPair>,
33 pub genesis_roles: Vec<(KeyRole, Arc<KeyPair>)>,
37 pub principals: Option<Arc<dyn PrincipalUidResolver>>,
40}
41
42impl std::fmt::Debug for EntryV2Config {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 formatter
45 .debug_struct("EntryV2Config")
46 .field("audit_key", &self.audit_key)
47 .field("genesis_roles", &self.genesis_roles)
48 .field("principals", &self.principals.is_some())
49 .finish()
50 }
51}
52
53pub(crate) struct V2Signer {
55 key: Arc<KeyPair>,
56 registry: Arc<KeyRegistry>,
57 principals: Option<Arc<dyn PrincipalUidResolver>>,
58}
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub(crate) struct V2Position {
63 chain_id: [u8; 32],
64 seq: u64,
65 key_epoch: u64,
66}
67
68impl V2Position {
69 pub(crate) fn of(entry: &AuditEntry) -> Option<Self> {
70 entry.v2.as_ref().map(|seal| Self {
71 chain_id: seal.chain_id,
72 seq: seal.seq,
73 key_epoch: seal.key_epoch,
74 })
75 }
76}
77
78#[derive(Clone)]
80pub(crate) struct EntryRequest {
81 pub(crate) session_id: SessionId,
82 pub(crate) principal: Option<PrincipalId>,
83 pub(crate) actor: Option<AuditActor>,
84 pub(crate) action: AuditAction,
85 pub(crate) authorization: AuthorizationProof,
86 pub(crate) outcome: AuditOutcome,
87}
88
89const REGISTRY_CHANGED: &str = "the key registry changed concurrently; reopen the audit log";
90
91impl AuditLog {
92 #[must_use]
94 pub fn entry_format(&self) -> AuditEntryFormat {
95 if self.v2_signer().is_some() {
96 AuditEntryFormat::V2
97 } else {
98 AuditEntryFormat::V1
99 }
100 }
101
102 #[must_use]
105 pub fn signing_public_key(&self) -> PublicKey {
106 self.archive_signer().0.export_public_key()
107 }
108
109 pub async fn key_registry(&self) -> AuditResult<Option<KeyRegistry>> {
117 if let Some(signer) = self.v2_signer() {
118 return Ok(Some(signer.registry.as_ref().clone()));
119 }
120 self.load_key_registry().await
121 }
122
123 pub async fn enable_entry_v2(&self, config: EntryV2Config) -> AuditResult<KeyRegistry> {
141 let _guard = self.registry_lock.lock().await;
142 let registry = match self.load_key_registry().await? {
143 Some(registry) => registry,
144 None => self.create_key_registry(&config).await?,
145 };
146 let audit_public = config.audit_key.export_public_key();
147 if registry.active_key(KeyRole::Audit, registry.head_seq()) != Some(audit_public) {
148 return Err(AuditError::KeyNotRegistered {
149 key: audit_public.to_hex(),
150 });
151 }
152 self.install_v2_signer(V2Signer {
153 key: config.audit_key,
154 registry: Arc::new(registry.clone()),
155 principals: config.principals,
156 });
157 Ok(registry)
158 }
159
160 async fn create_key_registry(&self, config: &EntryV2Config) -> AuditResult<KeyRegistry> {
161 let mut keys: Vec<(KeyRole, &KeyPair)> = vec![(KeyRole::Audit, config.audit_key.as_ref())];
162 keys.extend(
163 config
164 .genesis_roles
165 .iter()
166 .map(|(role, key)| (*role, key.as_ref())),
167 );
168 let genesis = KeyRegistry::genesis_record(Timestamp::now(), &keys)?;
169 if self.persist_registry_record(&genesis).await? {
170 return KeyRegistry::from_records(vec![genesis]);
171 }
172 self.load_key_registry()
174 .await?
175 .ok_or_else(|| AuditError::KeyRegistry(REGISTRY_CHANGED.to_owned()))
176 }
177
178 pub async fn rotate_audit_key(&self, new_key: Arc<KeyPair>) -> AuditResult<KeyRegistryRecord> {
193 let _guard = self.registry_lock.lock().await;
194 let signer = self
195 .v2_signer()
196 .ok_or_else(|| AuditError::KeyRegistry("entry format v2 is not enabled".to_owned()))?;
197 let record = signer.registry.rotation_record(
198 KeyRole::Audit,
199 &signer.key,
200 &new_key,
201 Timestamp::now(),
202 )?;
203 let mut registry = signer.registry.as_ref().clone();
204 registry.push(record.clone())?;
205 if !self.persist_registry_record(&record).await? {
206 return Err(AuditError::KeyRegistry(REGISTRY_CHANGED.to_owned()));
207 }
208 self.install_v2_signer(V2Signer {
209 key: new_key,
210 registry: Arc::new(registry),
211 principals: signer.principals.clone(),
212 });
213 Ok(record)
214 }
215
216 fn install_v2_signer(&self, signer: V2Signer) {
217 *self
218 .entry_v2
219 .write()
220 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(signer));
221 }
222
223 pub(crate) fn v2_signer(&self) -> Option<Arc<V2Signer>> {
224 self.entry_v2
225 .read()
226 .unwrap_or_else(std::sync::PoisonError::into_inner)
227 .clone()
228 }
229
230 pub(crate) fn archive_signer(&self) -> (Arc<KeyPair>, Option<u64>) {
234 self.v2_signer().map_or_else(
235 || (Arc::clone(&self.runtime_key), None),
236 |signer| (Arc::clone(&signer.key), Some(signer.registry.head_seq())),
237 )
238 }
239
240 pub(crate) async fn verification_registry(&self) -> AuditResult<Option<Arc<KeyRegistry>>> {
243 if let Some(signer) = self.v2_signer() {
244 return Ok(Some(Arc::clone(&signer.registry)));
245 }
246 Ok(self.load_key_registry().await?.map(Arc::new))
247 }
248
249 async fn load_key_registry(&self) -> AuditResult<Option<KeyRegistry>> {
250 let raw = self.storage.key_registry_records().await?;
251 if raw.is_empty() {
252 return Ok(None);
253 }
254 let records = raw
255 .iter()
256 .map(|bytes| serde_json::from_slice::<KeyRegistryRecord>(bytes))
257 .collect::<Result<Vec<_>, _>>()
258 .map_err(|error| AuditError::KeyRegistry(error.to_string()))?;
259 KeyRegistry::from_records(records).map(Some)
260 }
261
262 async fn persist_registry_record(&self, record: &KeyRegistryRecord) -> AuditResult<bool> {
263 let bytes = serde_json::to_vec(record)
264 .map_err(|error| AuditError::SerializationError(error.to_string()))?;
265 self.storage
266 .put_key_registry_record(record.seq, bytes)
267 .await
268 }
269
270 pub(crate) fn can_resign<'a>(
277 &self,
278 error: &AuditError,
279 entries: impl IntoIterator<Item = &'a AuditEntry>,
280 ) -> bool {
281 if !matches!(
282 error,
283 AuditError::V1Closed { .. } | AuditError::StaleAuditKey { .. }
284 ) {
285 return false;
286 }
287 let Some(signer) = self.v2_signer() else {
288 return false;
289 };
290 entries.into_iter().all(|entry| {
291 entry
292 .v2
293 .as_ref()
294 .is_none_or(|seal| seal.key_epoch < signer.registry.head_seq())
295 })
296 }
297
298 pub(crate) fn sign_entry(
301 &self,
302 request: EntryRequest,
303 previous_hash: ContentHash,
304 previous: Option<V2Position>,
305 ) -> AuditResult<AuditEntry> {
306 let Some(signer) = self.v2_signer() else {
307 if previous.is_some() {
310 return Err(AuditError::V1Closed {
311 reason: "the chain head is a format-v2 entry",
312 });
313 }
314 return Ok(sign_v1(request, previous_hash, &self.runtime_key));
315 };
316 let principal_uid = request.principal.as_ref().and_then(|principal| {
317 signer
318 .principals
319 .as_ref()
320 .and_then(|resolver| resolver.resolve_uid(principal))
321 });
322 let chain_id = derive_chain_id(
323 &signer.registry.registry_id(),
324 &request.session_id,
325 request.principal.as_ref(),
326 principal_uid.as_ref(),
327 );
328 let key_epoch = signer.registry.head_seq();
329 if previous.is_some_and(|head| head.key_epoch > key_epoch) {
330 return Err(AuditError::KeyRegistry(
331 "the chain head names a newer key epoch than the loaded registry".to_owned(),
332 ));
333 }
334 let seq = match previous {
335 Some(head) if head.chain_id == chain_id => {
336 head.seq.checked_add(1).ok_or_else(|| {
337 AuditError::StorageError("audit chain sequence exhausted".to_owned())
338 })?
339 },
340 _ => 1,
341 };
342 AuditEntry::create_v2(
343 EntryV2Draft {
344 session_id: request.session_id,
345 principal: request.principal,
346 principal_uid,
347 actor: request.actor,
348 action: request.action,
349 authorization: request.authorization,
350 outcome: request.outcome,
351 previous_hash,
352 chain_id,
353 seq,
354 key_epoch,
355 },
356 &signer.key,
357 )
358 }
359}
360
361fn sign_v1(request: EntryRequest, previous_hash: ContentHash, key: &KeyPair) -> AuditEntry {
363 match request.principal {
364 Some(principal) => AuditEntry::create_with_principal(
365 request.session_id,
366 principal,
367 request.action,
368 request.authorization,
369 request.outcome,
370 previous_hash,
371 key,
372 ),
373 None => AuditEntry::create(
374 request.session_id,
375 request.action,
376 request.authorization,
377 request.outcome,
378 previous_hash,
379 key,
380 ),
381 }
382}