Skip to main content

astrid_audit/log/
v2.rs

1//! Format-v2 signing state of the audit log: enabling v2, rotating the audit
2//! key, and signing each new entry in the log's current format.
3
4use 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
16/// Resolves a principal alias to its durable UID for v2 chain ids.
17pub trait PrincipalUidResolver: Send + Sync {
18    /// The durable UID currently bound to `principal`, if any.
19    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
28/// How to sign format-v2 entries.
29pub struct EntryV2Config {
30    /// The audit signing key. It must be the registry's active audit key,
31    /// or become it when this call creates the registry.
32    pub audit_key: Arc<KeyPair>,
33    /// Keys registered for other roles when this call creates the registry,
34    /// for example the runtime key as capability, build and audit-v1 key.
35    /// Ignored when the registry already exists.
36    pub genesis_roles: Vec<(KeyRole, Arc<KeyPair>)>,
37    /// Resolves principal aliases to durable UIDs. Without it, and for an
38    /// alias it cannot resolve, entries carry a `null` UID.
39    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
53/// The active v2 signer: the audit key and the registry it is valid in.
54pub(crate) struct V2Signer {
55    key: Arc<KeyPair>,
56    registry: Arc<KeyRegistry>,
57    principals: Option<Arc<dyn PrincipalUidResolver>>,
58}
59
60/// A v2 chain position, cached with a chain head.
61#[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/// What to record, independent of the entry format.
79#[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    /// The format new entries are written in.
93    #[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    /// The public key that signs new entries: the audit key under format v2,
103    /// the runtime key under format v1.
104    #[must_use]
105    pub fn signing_public_key(&self) -> PublicKey {
106        self.archive_signer().0.export_public_key()
107    }
108
109    /// The verified key registry of this store, if format v2 was ever enabled
110    /// on it.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error when the stored registry cannot be read or does not
115    /// verify.
116    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    /// Switch new entries to format v2, signed by `config.audit_key`.
124    ///
125    /// On a store without a key registry this writes the genesis record,
126    /// binding `config.audit_key` to the audit role and `config.genesis_roles`
127    /// to theirs, signed by every one of those keys. On a store with a
128    /// registry, `config.audit_key` must be the registry's active audit key.
129    ///
130    /// Enabling is one-way for the store: once a registry exists, format-v1
131    /// appends are refused (see [`AuditError::V1Closed`]). Existing v1 entries
132    /// are kept as they are; the next entry of each chain opens a v2 chain
133    /// linked to the last v1 entry.
134    ///
135    /// # Errors
136    ///
137    /// Returns [`AuditError::KeyNotRegistered`] when the key is not the
138    /// registry's active audit key, or [`AuditError::KeyRegistry`] when the
139    /// registry is invalid or cannot be written.
140    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        // Another opener of this store wrote a genesis first; use it.
173        self.load_key_registry()
174            .await?
175            .ok_or_else(|| AuditError::KeyRegistry(REGISTRY_CHANGED.to_owned()))
176    }
177
178    /// Replace the audit key with `new_key`.
179    ///
180    /// Appends a registry record retiring the current audit key and adding
181    /// `new_key`, signed by both, then signs new entries with `new_key` at the
182    /// new key epoch. Entries already signed by the old key stay valid.
183    ///
184    /// The caller must store `new_key` durably before calling this and keep
185    /// the old key until it returns: after the record is written only
186    /// `new_key` can be enabled on this store.
187    ///
188    /// # Errors
189    ///
190    /// Returns an error when format v2 is not enabled, `new_key` was
191    /// registered before, or the record cannot be written.
192    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    /// The key that signs archive receipts and the registry epoch it holds
231    /// the audit role in: the audit key under format v2, the runtime key
232    /// (without an epoch) otherwise.
233    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    /// The registry to verify v2 entries against: the active one, else the
241    /// stored one.
242    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    /// Whether storage refused `entries` only because this log's signing state
271    /// advanced after they were signed (v2 enabled, or the audit key rotated,
272    /// in this log), so signing them again succeeds. A refusal caused by
273    /// another writer of the store, whose new key this log does not hold, is
274    /// final. Only a single-entry append re-signs: its commit is all or
275    /// nothing.
276    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    /// Create and sign the next entry of a chain whose head hash is
299    /// `previous_hash` and whose head v2 position is `previous`.
300    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            // Storage refuses a v1 commit once the store holds a key registry;
308            // a v2 chain head is refused here already.
309            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
361/// Format-v1 entry; v1 has no actor field, so an actor is not recorded.
362fn 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}