auths-sdk 0.1.2

Application services layer for Auths identity operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! SDK transparency verification workflows.

use std::path::Path;

use auths_core::ports::network::{NetworkError, RegistryClient};
use auths_keri::witness::independence::{
    IndependencePolicy, Infrastructure, Jurisdiction, OperatorId, Organization, WitnessOperatorInfo,
};
use auths_transparency::{
    BundleVerificationReport, ConsistencyProof, LogOrigin, OfflineBundle, SignedCheckpoint,
    TrustRoot, TrustRootWitness,
};
use auths_verifier::Ed25519PublicKey;
use chrono::{DateTime, Utc};
use thiserror::Error;

/// Errors from transparency verification workflows.
#[derive(Debug, Error)]
pub enum TransparencyWorkflowError {
    /// Bundle verification found issues.
    #[error("bundle verification found issues")]
    VerificationFailed(Box<BundleVerificationReport>),

    /// Checkpoint consistency check failed.
    #[error("checkpoint inconsistent: {0}")]
    CheckpointInconsistent(String),

    /// Cache I/O error.
    #[error("cache I/O error: {0}")]
    CacheError(#[source] std::io::Error),

    /// JSON deserialization error.
    #[error("deserialization error: {0}")]
    DeserializationError(String),

    /// Network error fetching trust root or other remote data.
    #[error("network error: {0}")]
    NetworkError(#[source] NetworkError),
}

/// Wire-format response from the registry trust-root endpoint.
#[derive(Debug, serde::Deserialize)]
struct TrustRootResponse {
    log_origin: String,
    log_public_key: String,
    witnesses: Vec<TrustRootWitnessResponse>,
    #[allow(dead_code)]
    version: u32,
}

/// Wire-format witness entry from the trust-root response.
#[derive(Debug, serde::Deserialize)]
struct TrustRootWitnessResponse {
    name: String,
    public_key: String,
    #[allow(dead_code)]
    url: String,
    /// Operator-independence attributes. Carried through to the trust root so the
    /// diversity gate can evaluate the actual cosigners; absent ⇒ this witness
    /// cannot contribute to independence.
    #[serde(default)]
    organization: Option<String>,
    #[serde(default)]
    jurisdiction: Option<String>,
    #[serde(default)]
    infrastructure: Option<String>,
}

/// Build the operator-independence attributes for a wire witness entry, if all
/// three axes are present and valid. Returns `None` (not an error) when any axis
/// is missing — an untagged witness simply cannot prove independence.
fn operator_info_from_wire(w: &TrustRootWitnessResponse) -> Option<WitnessOperatorInfo> {
    Some(WitnessOperatorInfo {
        operator: OperatorId::new(w.name.clone()).ok()?,
        organization: Organization::new(w.organization.clone()?).ok()?,
        jurisdiction: Jurisdiction::new(w.jurisdiction.clone()?).ok()?,
        infrastructure: Infrastructure::new(w.infrastructure.clone()?).ok()?,
    })
}

/// Fetch the trust root from a registry URL.
///
/// Issues a GET to `{registry_url}/v1/trust-root`, parses the JSON
/// response, and converts it into a domain [`TrustRoot`].
///
/// Args:
/// * `registry_url` — Base URL of the auths registry.
/// * `client` — Network client for HTTP communication.
///
/// Usage:
/// ```ignore
/// let trust_root = fetch_trust_root("https://registry.auths.dev", &http_client).await?;
/// ```
pub async fn fetch_trust_root(
    registry_url: &str,
    client: &impl RegistryClient,
) -> Result<TrustRoot, TransparencyWorkflowError> {
    let bytes = client
        .fetch_registry_data(registry_url, "v1/trust-root")
        .await
        .map_err(TransparencyWorkflowError::NetworkError)?;

    let resp: TrustRootResponse = serde_json::from_slice(&bytes)
        .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;

    let log_public_key_bytes: [u8; 32] = hex::decode(&resp.log_public_key)
        .map_err(|e| {
            TransparencyWorkflowError::DeserializationError(format!(
                "invalid hex in log_public_key: {e}"
            ))
        })?
        .try_into()
        .map_err(|_| {
            TransparencyWorkflowError::DeserializationError(
                "log_public_key must be exactly 32 bytes".into(),
            )
        })?;

    let log_origin = LogOrigin::new(&resp.log_origin).map_err(|e| {
        TransparencyWorkflowError::DeserializationError(format!("invalid log origin: {e}"))
    })?;

    let witnesses = resp
        .witnesses
        .into_iter()
        .filter(|w| !w.public_key.is_empty())
        .filter_map(|w| {
            let pk_bytes: [u8; 32] = hex::decode(&w.public_key).ok()?.try_into().ok()?;
            let public_key = Ed25519PublicKey::from_bytes(pk_bytes);
            let witness_did = auths_verifier::CanonicalDid::from_public_key_did_key(
                public_key.as_bytes(),
                auths_crypto::CurveType::Ed25519,
            );
            let operator_info = operator_info_from_wire(&w);
            Some(TrustRootWitness {
                witness_did,
                name: w.name,
                public_key,
                operator_info,
            })
        })
        .collect();

    Ok(TrustRoot {
        log_public_key: Ed25519PublicKey::from_bytes(log_public_key_bytes),
        log_origin,
        witnesses,
        signature_algorithm: Default::default(),
        ecdsa_log_public_key_der: None,
        // The registry trust-root wire format does not yet carry diversity
        // thresholds; the pinned `witness_policy.json` is the enforcement source.
        independence_policy: IndependencePolicy::unconstrained(),
    })
}

/// Configuration for bundle verification.
pub struct BundleVerifyConfig {
    /// The offline bundle serialized as JSON.
    pub bundle_json: String,
    /// The trust root serialized as JSON.
    pub trust_root_json: String,
}

/// Result of a consistency check between cached and new checkpoints.
#[derive(Debug)]
pub struct ConsistencyReport {
    /// Tree size of the previously cached checkpoint (0 if none).
    pub old_size: u64,
    /// Tree size of the newly cached checkpoint.
    pub new_size: u64,
    /// Whether consistency was verified.
    pub consistent: bool,
}

/// Verify an offline transparency bundle.
///
/// Deserializes the bundle and trust root from JSON, delegates to
/// `auths_transparency::verify_bundle`, and returns the report.
/// Returns `Err(VerificationFailed)` when the bundle does not pass
/// all verification checks.
///
/// Args:
/// * `config` — Bundle and trust root JSON strings.
/// * `now` — Injected wall-clock time.
///
/// Usage:
/// ```ignore
/// let report = verify_artifact_bundle(&config, now)?;
/// ```
pub fn verify_artifact_bundle(
    config: &BundleVerifyConfig,
    now: DateTime<Utc>,
) -> Result<BundleVerificationReport, TransparencyWorkflowError> {
    let bundle: OfflineBundle = serde_json::from_str(&config.bundle_json)
        .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;
    let trust_root: TrustRoot = serde_json::from_str(&config.trust_root_json)
        .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;

    let report = auths_transparency::verify_bundle(&bundle, &trust_root, now);

    if !report.is_valid() {
        return Err(TransparencyWorkflowError::VerificationFailed(Box::new(
            report,
        )));
    }

    Ok(report)
}

/// Update the local checkpoint cache after verifying consistency.
///
/// Loads the cached checkpoint from disk, verifies that the new checkpoint
/// is a consistent append-only extension of the cached one, and writes the
/// new checkpoint to disk.
///
/// **Note:** Uses blocking `std::fs` I/O (not `tokio::fs`). This is acceptable
/// for the current use case — a single small JSON file read/write from CLI context.
/// If called from a multi-threaded async server, wrap in `tokio::task::spawn_blocking`.
///
/// Args:
/// * `cache_path` — Path to the cached checkpoint JSON file.
/// * `new_checkpoint` — The newly received signed checkpoint.
/// * `consistency_proof` — Proof that old tree is a prefix of the new tree.
/// * `_trust_root` — Trust root for checkpoint signature verification (reserved for future use).
/// * `_now` — Injected wall-clock time (reserved for future use).
///
/// Usage:
/// ```ignore
/// let report = update_checkpoint_cache(
///     &cache_path,
///     &new_checkpoint,
///     &consistency_proof,
///     &trust_root,
///     now,
/// )?;
/// ```
#[allow(clippy::disallowed_methods)] // Filesystem I/O is intentional here — this is a top-level SDK workflow
pub fn update_checkpoint_cache(
    cache_path: &Path,
    new_checkpoint: &SignedCheckpoint,
    consistency_proof: &ConsistencyProof,
    _trust_root: &TrustRoot,
    _now: DateTime<Utc>,
) -> Result<ConsistencyReport, TransparencyWorkflowError> {
    let old_checkpoint = match std::fs::read_to_string(cache_path) {
        Ok(json) => {
            let cp: SignedCheckpoint = serde_json::from_str(&json)
                .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;
            Some(cp)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(TransparencyWorkflowError::CacheError(e)),
    };

    if let Some(ref old) = old_checkpoint {
        auths_transparency::verify_consistency(
            old.checkpoint.size,
            new_checkpoint.checkpoint.size,
            &consistency_proof.hashes,
            &old.checkpoint.root,
            &new_checkpoint.checkpoint.root,
        )
        .map_err(|e| TransparencyWorkflowError::CheckpointInconsistent(e.to_string()))?;
    }

    let json = serde_json::to_string_pretty(new_checkpoint)
        .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;

    if let Some(parent) = cache_path.parent() {
        std::fs::create_dir_all(parent).map_err(TransparencyWorkflowError::CacheError)?;
    }
    std::fs::write(cache_path, json.as_bytes()).map_err(TransparencyWorkflowError::CacheError)?;

    let old_size = old_checkpoint.map(|c| c.checkpoint.size).unwrap_or(0);

    Ok(ConsistencyReport {
        old_size,
        new_size: new_checkpoint.checkpoint.size,
        consistent: true,
    })
}

/// Cache a checkpoint using trust-on-first-use (TOFU) semantics.
///
/// If no cached checkpoint exists, the new checkpoint is accepted and written.
/// If a cached checkpoint exists with the same or smaller tree size and matching
/// root, the cache is left unchanged. If the cached checkpoint has the same size
/// but a different root, this is equivocation — returns a hard error.
/// If a consistency proof is provided, full Merkle consistency is verified.
///
/// Args:
/// * `cache_path` — Path to the cached checkpoint JSON file (`~/.auths/log_checkpoint.json`).
/// * `new_checkpoint` — The checkpoint to cache.
/// * `consistency_proof` — Optional consistency proof for cache-hit cases.
///
/// Usage:
/// ```ignore
/// try_cache_checkpoint(
///     &Path::new("~/.auths/log_checkpoint.json"),
///     &bundle.signed_checkpoint,
///     None,
/// )?;
/// ```
#[allow(clippy::disallowed_methods)] // Filesystem I/O is intentional — top-level SDK workflow
pub fn try_cache_checkpoint(
    cache_path: &Path,
    new_checkpoint: &SignedCheckpoint,
    consistency_proof: Option<&ConsistencyProof>,
) -> Result<ConsistencyReport, TransparencyWorkflowError> {
    let old_checkpoint = match std::fs::read_to_string(cache_path) {
        Ok(json) => {
            let cp: SignedCheckpoint = serde_json::from_str(&json)
                .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;
            Some(cp)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(TransparencyWorkflowError::CacheError(e)),
    };

    if let Some(ref old) = old_checkpoint {
        // Equivocation: same size, different root
        if old.checkpoint.size == new_checkpoint.checkpoint.size
            && old.checkpoint.root != new_checkpoint.checkpoint.root
        {
            return Err(TransparencyWorkflowError::CheckpointInconsistent(format!(
                "equivocation detected: same tree size {} but different roots",
                old.checkpoint.size
            )));
        }

        // New checkpoint must not be smaller
        if new_checkpoint.checkpoint.size < old.checkpoint.size {
            return Err(TransparencyWorkflowError::CheckpointInconsistent(format!(
                "new checkpoint size {} is smaller than cached size {}",
                new_checkpoint.checkpoint.size, old.checkpoint.size
            )));
        }

        // Same checkpoint — no update needed
        if old.checkpoint.size == new_checkpoint.checkpoint.size {
            return Ok(ConsistencyReport {
                old_size: old.checkpoint.size,
                new_size: new_checkpoint.checkpoint.size,
                consistent: true,
            });
        }

        // If we have a consistency proof, verify it
        if let Some(proof) = consistency_proof {
            auths_transparency::verify_consistency(
                old.checkpoint.size,
                new_checkpoint.checkpoint.size,
                &proof.hashes,
                &old.checkpoint.root,
                &new_checkpoint.checkpoint.root,
            )
            .map_err(|e| TransparencyWorkflowError::CheckpointInconsistent(e.to_string()))?;
        }
    }

    let json = serde_json::to_string_pretty(new_checkpoint)
        .map_err(|e| TransparencyWorkflowError::DeserializationError(e.to_string()))?;

    if let Some(parent) = cache_path.parent() {
        std::fs::create_dir_all(parent).map_err(TransparencyWorkflowError::CacheError)?;
    }
    std::fs::write(cache_path, json.as_bytes()).map_err(TransparencyWorkflowError::CacheError)?;

    let old_size = old_checkpoint.map(|c| c.checkpoint.size).unwrap_or(0);

    Ok(ConsistencyReport {
        old_size,
        new_size: new_checkpoint.checkpoint.size,
        consistent: true,
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::disallowed_methods)]
mod tests {
    use super::*;
    use auths_transparency::checkpoint::{Checkpoint, SignedCheckpoint};
    use auths_transparency::entry::{Entry, EntryBody, EntryContent, EntryType};
    use auths_transparency::proof::InclusionProof;
    use auths_transparency::types::{LogOrigin, MerkleHash};
    use auths_verifier::{CanonicalDid, Ed25519PublicKey, Ed25519Signature};

    fn dummy_signed_checkpoint(size: u64, root: MerkleHash) -> SignedCheckpoint {
        SignedCheckpoint {
            checkpoint: Checkpoint {
                origin: LogOrigin::new("test.dev/log").unwrap(),
                size,
                root,
                timestamp: chrono::DateTime::parse_from_rfc3339("2025-06-15T00:00:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
            },
            log_signature: Ed25519Signature::from_bytes([0u8; 64]),
            log_public_key: Ed25519PublicKey::from_bytes([0u8; 32]),
            witnesses: vec![],
            ecdsa_checkpoint_signature: None,
            ecdsa_checkpoint_key: None,
        }
    }

    fn dummy_trust_root() -> TrustRoot {
        TrustRoot {
            log_public_key: Ed25519PublicKey::from_bytes([0u8; 32]),
            log_origin: LogOrigin::new("test.dev/log").unwrap(),
            witnesses: vec![],
            signature_algorithm: Default::default(),
            ecdsa_log_public_key_der: None,
            independence_policy: IndependencePolicy::unconstrained(),
        }
    }

    /// A registry client that returns a fixed trust-root document.
    struct CannedRegistry {
        trust_root_json: Vec<u8>,
    }

    impl RegistryClient for CannedRegistry {
        async fn fetch_registry_data(
            &self,
            _registry_url: &str,
            _path: &str,
        ) -> Result<Vec<u8>, NetworkError> {
            Ok(self.trust_root_json.clone())
        }

        async fn push_registry_data(
            &self,
            _registry_url: &str,
            _path: &str,
            _data: &[u8],
        ) -> Result<(), NetworkError> {
            Ok(())
        }

        async fn post_json(
            &self,
            _registry_url: &str,
            _path: &str,
            _json_body: &[u8],
        ) -> Result<auths_core::ports::network::RegistryResponse, NetworkError> {
            Ok(auths_core::ports::network::RegistryResponse {
                status: 200,
                body: vec![],
                rate_limit: None,
            })
        }
    }

    #[tokio::test]
    async fn fetch_trust_root_round_trips_independence_attributes() {
        let log_pk = hex::encode([0u8; 32]);
        let w_pk = hex::encode([7u8; 32]);
        let json = format!(
            r#"{{"version":1,"log_origin":"test.dev/log","log_public_key":"{log_pk}","witnesses":[{{"name":"w1","public_key":"{w_pk}","url":"http://w1","organization":"org-a","jurisdiction":"US","infrastructure":"aws/us-east-1"}}]}}"#
        );
        let client = CannedRegistry {
            trust_root_json: json.into_bytes(),
        };

        let trust_root = fetch_trust_root("https://registry.test", &client)
            .await
            .unwrap();

        assert_eq!(trust_root.witnesses.len(), 1);
        let attrs = trust_root.witnesses[0]
            .operator_attributes()
            .expect("operator attributes survive ingestion");
        assert_eq!(attrs.organization.as_str(), "org-a");
        assert_eq!(attrs.jurisdiction.as_str(), "US");
        assert_eq!(attrs.infrastructure.as_str(), "aws/us-east-1");
    }

    #[test]
    fn verify_artifact_bundle_invalid_bundle_json() {
        let config = BundleVerifyConfig {
            bundle_json: "not valid json".into(),
            trust_root_json: "{}".into(),
        };
        let now = chrono::DateTime::parse_from_rfc3339("2025-07-01T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let err = verify_artifact_bundle(&config, now).unwrap_err();
        assert!(matches!(
            err,
            TransparencyWorkflowError::DeserializationError(_)
        ));
    }

    fn dummy_bundle() -> OfflineBundle {
        let ts = chrono::DateTime::parse_from_rfc3339("2025-06-15T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let entry = Entry {
            sequence: 0,
            timestamp: ts,
            content: EntryContent {
                entry_type: EntryType::DeviceBind,
                body: EntryBody::DeviceBind {
                    device_did: CanonicalDid::new_unchecked("did:key:z6MkTest"),
                    public_key: Ed25519PublicKey::from_bytes([0u8; 32]),
                },
                actor_did: CanonicalDid::new_unchecked("did:key:z6MkTest"),
            },
            actor_sig: Ed25519Signature::empty(),
        };
        let root = MerkleHash::from_bytes([0u8; 32]);
        OfflineBundle {
            entry,
            inclusion_proof: InclusionProof {
                index: 0,
                size: 1,
                root,
                hashes: vec![],
            },
            signed_checkpoint: dummy_signed_checkpoint(1, root),
            delegation_chain: vec![],
        }
    }

    #[test]
    fn verify_artifact_bundle_invalid_trust_root_json() {
        let bundle = dummy_bundle();
        let bundle_json = serde_json::to_string(&bundle).unwrap();

        let config = BundleVerifyConfig {
            bundle_json,
            trust_root_json: "not valid json".into(),
        };
        let now = chrono::DateTime::parse_from_rfc3339("2025-07-01T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let err = verify_artifact_bundle(&config, now).unwrap_err();
        assert!(matches!(
            err,
            TransparencyWorkflowError::DeserializationError(_)
        ));
    }

    #[test]
    fn update_checkpoint_cache_writes_new_file() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("checkpoint.json");

        let root = MerkleHash::from_bytes([0xaa; 32]);
        let new_cp = dummy_signed_checkpoint(10, root);
        let proof = ConsistencyProof {
            old_size: 0,
            new_size: 10,
            old_root: MerkleHash::from_bytes([0u8; 32]),
            new_root: root,
            hashes: vec![],
        };
        let trust_root = dummy_trust_root();
        let now = chrono::DateTime::parse_from_rfc3339("2025-07-01T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);

        let report =
            update_checkpoint_cache(&cache_path, &new_cp, &proof, &trust_root, now).unwrap();

        assert_eq!(report.old_size, 0);
        assert_eq!(report.new_size, 10);
        assert!(report.consistent);
        assert!(cache_path.exists());

        let written: SignedCheckpoint =
            serde_json::from_str(&std::fs::read_to_string(&cache_path).unwrap()).unwrap();
        assert_eq!(written.checkpoint.size, 10);
    }

    #[test]
    fn update_checkpoint_cache_creates_parent_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir
            .path()
            .join("nested")
            .join("dir")
            .join("checkpoint.json");

        let root = MerkleHash::from_bytes([0xbb; 32]);
        let new_cp = dummy_signed_checkpoint(5, root);
        let proof = ConsistencyProof {
            old_size: 0,
            new_size: 5,
            old_root: MerkleHash::from_bytes([0u8; 32]),
            new_root: root,
            hashes: vec![],
        };
        let trust_root = dummy_trust_root();
        let now = chrono::DateTime::parse_from_rfc3339("2025-07-01T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);

        let report =
            update_checkpoint_cache(&cache_path, &new_cp, &proof, &trust_root, now).unwrap();

        assert!(report.consistent);
        assert!(cache_path.exists());
    }

    #[test]
    fn try_cache_checkpoint_tofu_writes_new_file() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("log_checkpoint.json");

        let root = MerkleHash::from_bytes([0xaa; 32]);
        let cp = dummy_signed_checkpoint(10, root);

        let report = try_cache_checkpoint(&cache_path, &cp, None).unwrap();
        assert_eq!(report.old_size, 0);
        assert_eq!(report.new_size, 10);
        assert!(report.consistent);
        assert!(cache_path.exists());
    }

    #[test]
    fn try_cache_checkpoint_same_checkpoint_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("log_checkpoint.json");

        let root = MerkleHash::from_bytes([0xaa; 32]);
        let cp = dummy_signed_checkpoint(10, root);

        try_cache_checkpoint(&cache_path, &cp, None).unwrap();
        let report = try_cache_checkpoint(&cache_path, &cp, None).unwrap();
        assert_eq!(report.old_size, 10);
        assert_eq!(report.new_size, 10);
        assert!(report.consistent);
    }

    #[test]
    fn try_cache_checkpoint_detects_equivocation() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("log_checkpoint.json");

        let root1 = MerkleHash::from_bytes([0xaa; 32]);
        let cp1 = dummy_signed_checkpoint(10, root1);
        try_cache_checkpoint(&cache_path, &cp1, None).unwrap();

        let root2 = MerkleHash::from_bytes([0xbb; 32]);
        let cp2 = dummy_signed_checkpoint(10, root2);
        let err = try_cache_checkpoint(&cache_path, &cp2, None).unwrap_err();
        assert!(matches!(
            err,
            TransparencyWorkflowError::CheckpointInconsistent(_)
        ));
    }

    #[test]
    fn try_cache_checkpoint_rejects_smaller_size() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("log_checkpoint.json");

        let cp1 = dummy_signed_checkpoint(10, MerkleHash::from_bytes([0xaa; 32]));
        try_cache_checkpoint(&cache_path, &cp1, None).unwrap();

        let cp2 = dummy_signed_checkpoint(5, MerkleHash::from_bytes([0xbb; 32]));
        let err = try_cache_checkpoint(&cache_path, &cp2, None).unwrap_err();
        assert!(matches!(
            err,
            TransparencyWorkflowError::CheckpointInconsistent(_)
        ));
    }
}