ic-bn-lib 0.10.0

Internet Computer Boundary Nodes shared modules
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
//! # Canister Client
//!
//! This module provides a client for interacting with the custom domains canister.
//! It handles all communication, serialization, encryption, and error handling.

use std::{
    str::FromStr,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::Duration,
};

use anyhow::{Context, anyhow};
use arc_swap::ArcSwap;
use async_trait::async_trait;
use candid::{CandidType, Decode, Deserialize, Encode, Principal};
use derive_new::new;
use fqdn::FQDN;
use ic_custom_domains_canister_api::{
    CertificatesPage, DomainStatus as DomainStatusApi, FetchTaskError, GetDomainStatusError,
    GetLastChangeTimeError, HasNextTaskError, InputTask as InputTaskApi, ListCertificatesPageError,
    ListCertificatesPageInput, ScheduledTask as ScheduledTaskApi, SubmitTaskError,
    TaskResult as TaskResultApi, TryAddTaskError,
};
use tokio::{
    select,
    time::{interval, sleep},
};
use tokio_util::sync::CancellationToken;
use tracing::{info, instrument, warn};

use crate::{
    DurationDisplay,
    custom_domains::{
        CustomDomain, ProvidesCustomDomains,
        base::{
            traits::{
                cipher::CiphersCertificates,
                repository::{Repository, RepositoryError},
                time::UtcTimestamp,
            },
            types::{
                domain::{DomainStatus, RegisteredDomain},
                task::{InputTask, ScheduledTask, TaskOutcome, TaskOutput, TaskResult},
            },
        },
        flags::DomainFlags,
    },
    ic_agent::Agent,
    tasks::Run,
    tls::{Pem, ProvidesCertificates},
};

#[derive(new)]
pub struct CanisterClient {
    agent: Agent,
    canister_id: Principal,
    certificate_cipher: Arc<dyn CiphersCertificates>,
    poll_interval: Duration,
    refresh_interval: Duration,
    priority: u8,
    custom_domain_flags: Option<DomainFlags>,
    #[new(default)]
    last_change_time: AtomicU64,
    #[new(default)]
    certificates: ArcSwap<Vec<Pem>>,
    #[new(default)]
    custom_domains: ArcSwap<Vec<CustomDomain>>,
}

impl std::fmt::Debug for CanisterClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CanisterClient({})", self.canister_id)
    }
}

impl CanisterClient {
    /// Fetch and cache registrations if changes happened
    async fn update_cache_conditional(&self) -> Result<(), anyhow::Error> {
        let last_change = self.get_last_change_time().await?;
        let cached_timestamp = self.last_change_time.load(Ordering::SeqCst);

        if last_change == cached_timestamp {
            return Ok(());
        }

        self.update_cache(Some(last_change), true).await
    }

    /// Fetch and cache registrations
    async fn update_cache(
        &self,
        last_change: Option<u64>,
        use_update: bool,
    ) -> Result<(), anyhow::Error> {
        // TODO update canister to send last change together with domains?
        let last_change = if let Some(v) = last_change {
            v
        } else {
            self.get_last_change_time().await?
        };

        let (certificates, custom_domains) = self
            .fetch_data(use_update)
            .await
            .context("unable to fetch registrations data")?;

        // Update cache
        self.certificates.store(Arc::new(certificates));
        self.custom_domains.store(Arc::new(custom_domains));
        self.last_change_time.store(last_change, Ordering::SeqCst);

        info!("Cache updated: {} certs", self.certificates.load().len());
        Ok(())
    }

    /// Fetch & convert registrations
    async fn fetch_data(
        &self,
        use_update: bool,
    ) -> Result<(Vec<Pem>, Vec<CustomDomain>), anyhow::Error> {
        let domains = self.all_registrations(use_update).await?;

        let mut certificates = Vec::with_capacity(domains.len());
        let mut custom_domains = Vec::with_capacity(domains.len());

        for d in domains {
            certificates.push(Pem([d.cert, d.priv_key].concat()));
            custom_domains.push(CustomDomain {
                name: d.domain,
                canister_id: d.canister_id,
                timestamp: 0,
                priority: self.priority,
                flags: self.custom_domain_flags,
            });
        }

        Ok((certificates, custom_domains))
    }

    /// Encrypts sensitive data before sending it to canister
    fn encrypt_field(&self, field_name: &str, data: &[u8]) -> Result<Vec<u8>, RepositoryError> {
        self.certificate_cipher.encrypt(data).map_err(|err| {
            RepositoryError::InternalError(anyhow!("Failed to encrypt {field_name}: {err}"))
        })
    }

    /// Decrypts sensitive data received from canister
    fn decrypt_field(&self, data: &[u8]) -> Result<Vec<u8>, RepositoryError> {
        self.certificate_cipher
            .decrypt(data)
            .map_err(|err| RepositoryError::InternalError(anyhow!("Failed to decrypt data: {err}")))
    }

    /// Makes a query call to the canister, decodes the response, and handles canister API errors
    async fn query<T, R, E>(&self, method: &str, args: &T) -> Result<R, RepositoryError>
    where
        T: CandidType + Sync,
        R: for<'de> Deserialize<'de> + CandidType,
        E: for<'de> Deserialize<'de> + CandidType + std::fmt::Debug,
        RepositoryError: TryFrom<E>,
    {
        let arg = Encode!(args).map_err(|err| {
            RepositoryError::InternalError(anyhow!(
                "Failed to encode arguments for {method}: {err}"
            ))
        })?;

        let result = self
            .agent
            .query(&self.canister_id, method)
            .with_arg(arg)
            .call()
            .await
            .map_err(|err| {
                RepositoryError::InternalError(anyhow!("Canister query {method} failed: {err}"))
            })?;

        let response = Decode!(&result, Result<R, E>).map_err(|err| {
            RepositoryError::InternalError(anyhow!("Failed to decode {method} response: {err}"))
        })?;

        response.map_err(|err| {
            let err_debug = format!("{err:?}");
            RepositoryError::try_from(err).unwrap_or_else(|_| {
                RepositoryError::InternalError(anyhow!(
                    "Failed to convert canister error: {err_debug}"
                ))
            })
        })
    }

    /// Makes an update call to the canister, decodes the response, and handles canister API errors
    async fn update<T, R, E>(&self, method: &str, args: &T) -> Result<R, RepositoryError>
    where
        T: CandidType + Sync,
        R: for<'de> Deserialize<'de> + CandidType + std::fmt::Debug,
        E: for<'de> Deserialize<'de> + CandidType + std::fmt::Debug,
        RepositoryError: TryFrom<E>,
    {
        let arg = Encode!(args).map_err(|err| {
            RepositoryError::InternalError(anyhow!(
                "Failed to encode arguments for {method}: {err}"
            ))
        })?;

        let result = self
            .agent
            .update(&self.canister_id, method)
            .with_arg(arg)
            .call_and_wait()
            .await
            .map_err(|err| {
                RepositoryError::InternalError(anyhow!("Canister update {method} failed: {err}"))
            })?;

        let response = Decode!(&result, Result<R, E>).map_err(|err| {
            RepositoryError::InternalError(anyhow!("Failed to decode {method} response: {err}"))
        })?;

        response.map_err(|err| {
            let err_debug = format!("{err:?}");
            RepositoryError::try_from(err).unwrap_or_else(|_| {
                RepositoryError::InternalError(anyhow!(
                    "Failed to convert canister error: {err_debug}"
                ))
            })
        })
    }
}

#[async_trait]
impl Repository for CanisterClient {
    async fn get_domain_status(
        &self,
        domain: &FQDN,
    ) -> Result<Option<DomainStatus>, RepositoryError> {
        let response = self
            .query::<String, Option<DomainStatusApi>, GetDomainStatusError>(
                "get_domain_status",
                &domain.to_string(),
            )
            .await?;

        match response {
            None => Ok(None),
            Some(api_status) => {
                let status = DomainStatus::try_from(api_status).map_err(|err| {
                    RepositoryError::InternalError(anyhow!(
                        "Failed to convert domain status: {err}"
                    ))
                })?;
                Ok(Some(status))
            }
        }
    }

    async fn has_next_task(&self) -> Result<bool, RepositoryError> {
        let response = self
            .query::<(), bool, HasNextTaskError>("has_next_task", &())
            .await?;

        Ok(response)
    }

    async fn fetch_next_task(&self) -> Result<Option<ScheduledTask>, RepositoryError> {
        let has_next_task = self
            .query::<(), bool, HasNextTaskError>("has_next_task", &())
            .await?;

        if !has_next_task {
            return Ok(None);
        }

        let response = self
            .update::<(), Option<ScheduledTaskApi>, FetchTaskError>("fetch_next_task", &())
            .await?;

        match response {
            None => Ok(None),
            Some(api_task) => {
                // Decrypt certificate if present
                let certificate = api_task
                    .enc_cert
                    .map(|encrypted_cert| self.decrypt_field(encrypted_cert.as_slice()))
                    .transpose()?;

                let domain = FQDN::from_str(&api_task.domain).map_err(|err| {
                    RepositoryError::InternalError(anyhow!("Invalid domain from canister: {err}"))
                })?;

                let task = ScheduledTask::new(
                    api_task.kind.into(),
                    domain,
                    api_task.id,
                    certificate,
                    api_task.wildcard.unwrap_or(false),
                    api_task.canister_id,
                );
                Ok(Some(task))
            }
        }
    }

    async fn submit_task_result(&self, mut task_result: TaskResult) -> Result<(), RepositoryError> {
        // We encrypt certificate and private_key and pass the result further to the canister.
        if let TaskOutcome::Success(TaskOutput::Issue(issued_certificate)) =
            &mut task_result.outcome
        {
            issued_certificate.cert =
                self.encrypt_field("certificate", &issued_certificate.cert)?;

            issued_certificate.priv_key =
                self.encrypt_field("private key", &issued_certificate.priv_key)?;
        }

        self.update::<TaskResultApi, (), SubmitTaskError>(
            "submit_task_result",
            &TaskResultApi::from(task_result),
        )
        .await
    }

    async fn try_add_task(&self, input_task: InputTask) -> Result<(), RepositoryError> {
        let response = self
            .update::<InputTaskApi, (), TryAddTaskError>(
                "try_add_task",
                &InputTaskApi::from(input_task),
            )
            .await;

        response?;

        Ok(())
    }

    async fn get_last_change_time(&self) -> Result<UtcTimestamp, RepositoryError> {
        let response = self
            .query::<(), UtcTimestamp, GetLastChangeTimeError>("get_last_change_time", &())
            .await?;

        Ok(response)
    }

    async fn all_registrations(
        &self,
        use_update: bool,
    ) -> Result<Vec<RegisteredDomain>, RepositoryError> {
        let mut registered_domains = vec![];
        let mut start_key = None;

        loop {
            let response = if use_update {
                self.update::<ListCertificatesPageInput, CertificatesPage, ListCertificatesPageError>(
                    "list_certificates_page",
                    &ListCertificatesPageInput {
                        start_key,
                        limit: None,
                    },
                )
                .await?
            } else {
                self.query::<ListCertificatesPageInput, CertificatesPage, ListCertificatesPageError>(
                        "list_certificates_page",
                        &ListCertificatesPageInput {
                            start_key,
                            limit: None,
                        },
                    )
                    .await?
            };

            let registrations = response
                .items
                .into_iter()
                .map(|mut reg| {
                    reg.enc_cert = self.decrypt_field(&reg.enc_cert)?;
                    reg.enc_priv_key = self.decrypt_field(&reg.enc_priv_key)?;

                    RegisteredDomain::try_from(reg).map_err(|err| {
                        RepositoryError::InternalError(anyhow!(
                            "Failed to convert RegisteredDomain: {err}"
                        ))
                    })
                })
                .collect::<Result<Vec<_>, _>>()?;

            registered_domains.extend(registrations);
            start_key = response.next_key;

            if start_key.is_none() {
                break;
            }
        }

        Ok(registered_domains)
    }
}

#[async_trait]
impl ProvidesCertificates for CanisterClient {
    async fn get_certificates(&self) -> Result<Vec<Pem>, crate::tls::Error> {
        Ok(self.certificates.load().as_ref().clone())
    }
}

#[async_trait]
impl ProvidesCustomDomains for CanisterClient {
    async fn get_custom_domains(&self) -> Result<Vec<CustomDomain>, anyhow::Error> {
        Ok(self.custom_domains.load().as_ref().clone())
    }
}

#[async_trait]
impl Run for CanisterClient {
    #[instrument(skip_all, name = "canister_client")]
    async fn run(&self, token: CancellationToken) -> Result<(), anyhow::Error> {
        // Wait a bit until the rest is initialized
        // TODO get rid of
        sleep(Duration::from_secs(15)).await;

        let mut interval_poll = interval(self.poll_interval);
        interval_poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
        let mut interval_refresh = interval(self.refresh_interval);
        interval_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

        warn!(
            "Started polling every {}, full refresh every {}",
            self.poll_interval.display(),
            self.refresh_interval.display()
        );

        loop {
            select! {
                biased;

                () = token.cancelled() => {
                    warn!("{self:?}: stopping");
                    return Ok(())
                },

                _ = interval_refresh.tick() => {
                    if let Err(e) = self.update_cache(None, false).await {
                        warn!("Unable to refresh data: {e:#}");
                    }
                }

                _ = interval_poll.tick() => {
                    if let Err(e) = self.update_cache_conditional().await {
                        warn!("Unable to poll for changes: {e:#}");
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::{
        collections::{HashMap, VecDeque},
        net::SocketAddr,
        sync::Mutex,
    };

    use axum::{
        Router,
        body::Bytes,
        extract::State,
        http::{StatusCode, Uri, header::CONTENT_TYPE},
        response::{IntoResponse, Response},
    };
    use axum_server::tls_rustls::RustlsConfig;
    use fqdn::fqdn;
    use ic_custom_domains_canister_api::{
        RegisteredDomain as RegisteredDomainApi, RegistrationStatus as RegistrationStatusApi,
        TaskKind as TaskKindApi, TaskOutcome as TaskOutcomeApi, TaskOutput as TaskOutputApi,
    };
    use ic_transport_types::{
        Envelope, EnvelopeContent, QueryResponse, RejectCode, RejectResponse, ReplyResponse,
    };

    use super::*;
    use crate::{
        custom_domains::{
            base::{
                traits::cipher::CipherError,
                types::{
                    domain::RegistrationStatus,
                    task::{IssueCertificateOutput, TaskFailReason, TaskKind},
                },
            },
            flags::FLAG_TEST,
        },
        principal,
        tests::{TEST_CERT_1, TEST_KEY_1},
    };

    const CANISTER_ID: &str = "qoctq-giaaa-aaaaa-aaaea-cai";
    /// Prefix that [`PrefixCipher`] adds on encryption and strips on decryption.
    const ENC: &[u8] = b"ENC:";
    /// A syntactically invalid domain name (the space is not allowed in a label).
    const BAD_DOMAIN: &str = "exa mple.com";

    // ---------------------------------------------------------------------------------------
    // Cipher test doubles
    // ---------------------------------------------------------------------------------------

    /// Reversible, observable stand-in for the real cipher: encryption prepends a marker and
    /// decryption removes it, so tests can tell whether data went through the cipher at all
    /// and in which direction.
    #[derive(Debug)]
    struct PrefixCipher;

    impl CiphersCertificates for PrefixCipher {
        fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, CipherError> {
            Ok([ENC, data].concat())
        }

        fn decrypt(&self, encrypted_data: &[u8]) -> Result<Vec<u8>, CipherError> {
            encrypted_data
                .strip_prefix(ENC)
                .map(<[u8]>::to_vec)
                .ok_or_else(|| CipherError::DecryptionFailed("missing marker".into()))
        }
    }

    /// Cipher that always fails, to exercise the error-mapping paths.
    #[derive(Debug)]
    struct FailingCipher;

    impl CiphersCertificates for FailingCipher {
        fn encrypt(&self, _: &[u8]) -> Result<Vec<u8>, CipherError> {
            Err(CipherError::EncryptionFailed("no key".into()))
        }

        fn decrypt(&self, _: &[u8]) -> Result<Vec<u8>, CipherError> {
            Err(CipherError::DecryptionFailed("no key".into()))
        }
    }

    // ---------------------------------------------------------------------------------------
    // Mock replica
    // ---------------------------------------------------------------------------------------

    /// What the mock replica answers for the next call of a given method.
    enum Reply {
        /// A successful reply carrying a Candid-encoded `Result<R, E>`
        Candid(Vec<u8>),
        /// A replica-level rejection of the call
        Reject(String),
        /// HTTP 200 with a body that is not valid CBOR
        NotCbor,
        /// An HTTP-level failure
        Status(StatusCode),
    }

    /// A single request that reached the mock replica.
    #[derive(Clone)]
    struct RecordedCall {
        /// Canister ID as taken from the request path (verifies URL construction)
        canister: String,
        method: String,
        /// Raw Candid-encoded argument blob
        arg: Vec<u8>,
        /// `true` for the update (`/call`) endpoint, `false` for `/query`
        update: bool,
    }

    #[derive(Default)]
    struct MockState {
        replies: HashMap<String, VecDeque<Reply>>,
        calls: Vec<RecordedCall>,
    }

    /// Owned snapshot of the calls the mock recorded. [`Mock::state`] returns one of these
    /// rather than the `MutexGuard` itself, so assertions never keep the lock alive across a
    /// later `.await` (clippy::await_holding_lock / clippy::significant_drop_tightening).
    struct Calls {
        calls: Vec<RecordedCall>,
    }

    impl Calls {
        /// Names of the called canister methods, in call order.
        fn methods(&self) -> Vec<&str> {
            self.calls.iter().map(|x| x.method.as_str()).collect()
        }

        /// Candid-decodes the argument of the n-th recorded call.
        fn arg<T: CandidType + for<'de> Deserialize<'de>>(&self, idx: usize) -> T {
            Decode!(&self.calls[idx].arg, T).expect("argument does not decode")
        }
    }

    type Shared = Arc<Mutex<MockState>>;

    struct Mock {
        state: Shared,
        url: String,
    }

    impl Mock {
        /// Spawns an HTTPS mock replica on a random loopback port.
        async fn start() -> Self {
            // rustls 0.23+ needs a process-wide provider; idempotent.
            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

            let state: Shared = Arc::new(Mutex::new(MockState::default()));
            let router = Router::new().fallback(handler).with_state(state.clone());

            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            listener.set_nonblocking(true).unwrap();
            let addr: SocketAddr = listener.local_addr().unwrap();

            let config = RustlsConfig::from_pem(
                TEST_CERT_1.as_bytes().to_vec(),
                TEST_KEY_1.as_bytes().to_vec(),
            )
            .await
            .unwrap();

            tokio::spawn(async move {
                axum_server::from_tcp_rustls(listener, config)
                    .unwrap()
                    .serve(router.into_make_service())
                    .await
                    .unwrap();
            });

            Self {
                state,
                url: format!("https://{addr}/"),
            }
        }

        fn push(&self, method: &str, reply: Reply) {
            self.state
                .lock()
                .unwrap()
                .replies
                .entry(method.to_string())
                .or_default()
                .push_back(reply);
        }

        /// Programs the Candid-encoded `Result` that `method` will return next.
        fn reply<R: CandidType, E: CandidType>(&self, method: &str, res: Result<R, E>) {
            self.push(method, Reply::Candid(Encode!(&res).unwrap()));
        }

        fn state(&self) -> Calls {
            Calls {
                calls: self.state.lock().unwrap().calls.clone(),
            }
        }

        fn methods(&self) -> Vec<String> {
            self.state()
                .methods()
                .into_iter()
                .map(ToString::to_string)
                .collect()
        }

        fn client(&self, cipher: Arc<dyn CiphersCertificates>) -> CanisterClient {
            client_at(&self.url, cipher)
        }
    }

    fn cbor(response: &QueryResponse) -> Response {
        (
            [(CONTENT_TYPE, "application/cbor")],
            serde_cbor::to_vec(response).unwrap(),
        )
            .into_response()
    }

    /// Single handler for every replica endpoint: the path shape (`.../canister/<id>/query`
    /// vs `.../call`) is derived from the URI so the mock doesn't hardcode the API version.
    async fn handler(State(state): State<Shared>, uri: Uri, body: Bytes) -> Response {
        let path = uri.path();
        let update = path.ends_with("/call");
        let canister = path.rsplit('/').nth(1).unwrap_or_default().to_string();

        let Ok(envelope) = serde_cbor::from_slice::<Envelope>(&body) else {
            return (StatusCode::BAD_REQUEST, "not a CBOR envelope").into_response();
        };

        let (method, arg) = match &*envelope.content {
            EnvelopeContent::Query {
                method_name, arg, ..
            }
            | EnvelopeContent::Call {
                method_name, arg, ..
            } => (method_name.clone(), arg.clone()),
            EnvelopeContent::ReadState { .. } => {
                return (StatusCode::BAD_REQUEST, "read_state is not mocked").into_response();
            }
        };

        let reply = {
            let mut state = state.lock().unwrap();
            state.calls.push(RecordedCall {
                canister,
                method: method.clone(),
                arg,
                update,
            });
            state.replies.get_mut(&method).and_then(VecDeque::pop_front)
        };

        match reply {
            Some(Reply::Candid(arg)) => cbor(&QueryResponse::Replied {
                reply: ReplyResponse { arg },
                signatures: vec![],
            }),
            Some(Reply::Reject(msg)) => cbor(&QueryResponse::Rejected {
                reject: RejectResponse {
                    reject_code: RejectCode::CanisterReject,
                    reject_message: msg,
                    error_code: None,
                },
                signatures: vec![],
            }),
            Some(Reply::NotCbor) => (StatusCode::OK, "definitely not cbor").into_response(),
            Some(Reply::Status(code)) => (code, "mock failure").into_response(),
            // Nothing programmed: fail fast at the HTTP layer so the client errors out
            // instead of hanging (this is also how update calls are made to fail).
            None => (
                StatusCode::BAD_REQUEST,
                format!("no reply programmed for {method}"),
            )
                .into_response(),
        }
    }

    /// `reqwest` client that trusts the self-signed test certificate.
    fn insecure_client() -> reqwest::Client {
        reqwest::Client::builder()
            .danger_accept_invalid_certs(true)
            // Avoid reusing connections that the mock may have torn down.
            .pool_max_idle_per_host(0)
            .build()
            .unwrap()
    }

    fn client_at(url: &str, cipher: Arc<dyn CiphersCertificates>) -> CanisterClient {
        let agent = Agent::builder()
            .with_url(url)
            .with_http_client(insecure_client())
            // Our mock cannot produce node signatures.
            .with_verify_query_signatures(false)
            .build()
            .unwrap();

        CanisterClient::new(
            agent,
            principal!(CANISTER_ID),
            cipher,
            Duration::from_secs(60),
            Duration::from_secs(600),
            7,
            Some(DomainFlags::new([FLAG_TEST])),
        )
    }

    fn api_status(domain: &str, status: RegistrationStatusApi) -> DomainStatusApi {
        DomainStatusApi {
            domain: domain.to_string(),
            canister_id: Some(principal!("aaaaa-aa")),
            status,
        }
    }

    fn api_domain(domain: &str, suffix: &str) -> RegisteredDomainApi {
        RegisteredDomainApi {
            domain: domain.to_string(),
            canister_id: principal!("aaaaa-aa"),
            enc_cert: [ENC, b"CERT-", suffix.as_bytes()].concat(),
            enc_priv_key: [ENC, b"KEY-", suffix.as_bytes()].concat(),
        }
    }

    // ---------------------------------------------------------------------------------------
    // Debug
    // ---------------------------------------------------------------------------------------

    #[test]
    fn debug_shows_only_the_canister_id() {
        let client = client_at("https://127.0.0.1:1/", Arc::new(PrefixCipher));
        assert_eq!(
            format!("{client:?}"),
            format!("CanisterClient({CANISTER_ID})")
        );
    }

    // ---------------------------------------------------------------------------------------
    // get_domain_status
    // ---------------------------------------------------------------------------------------

    #[tokio::test]
    async fn get_domain_status_sends_the_domain_and_converts_the_reply() {
        let mock = Mock::start().await;
        mock.reply::<_, GetDomainStatusError>(
            "get_domain_status",
            Ok(Some(api_status(
                "my.example.com",
                RegistrationStatusApi::Failed("boom".into()),
            ))),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let status = client
            .get_domain_status(&fqdn!("my.example.com"))
            .await
            .unwrap()
            .expect("expected a status");

        assert_eq!(status.domain, fqdn!("my.example.com"));
        assert_eq!(status.canister_id, Some(principal!("aaaaa-aa")));
        // The internal type keeps the real failure reason; only serialization redacts it.
        assert_eq!(status.status, RegistrationStatus::Failed("boom".into()));

        let state = mock.state();
        assert_eq!(state.methods(), ["get_domain_status"]);
        assert_eq!(state.calls[0].canister, CANISTER_ID);
        assert!(!state.calls[0].update, "must be a query, not an update");
        assert_eq!(state.arg::<String>(0), "my.example.com");
    }

    #[tokio::test]
    async fn get_domain_status_returns_none_for_unknown_domain() {
        let mock = Mock::start().await;
        mock.reply::<Option<DomainStatusApi>, GetDomainStatusError>("get_domain_status", Ok(None));

        let client = mock.client(Arc::new(PrefixCipher));
        assert!(
            client
                .get_domain_status(&fqdn!("example.com"))
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn get_domain_status_rejects_a_malformed_domain_from_the_canister() {
        let mock = Mock::start().await;
        mock.reply::<_, GetDomainStatusError>(
            "get_domain_status",
            Ok(Some(api_status(BAD_DOMAIN, RegistrationStatusApi::Expired))),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client
            .get_domain_status(&fqdn!("example.com"))
            .await
            .unwrap_err();

        assert!(
            matches!(err, RepositoryError::InternalError(_)),
            "unexpected error: {err}"
        );
        assert!(
            err.to_string().contains("Failed to convert domain status"),
            "unexpected error: {err}"
        );
    }

    // ---------------------------------------------------------------------------------------
    // Canister / transport error mapping
    // ---------------------------------------------------------------------------------------

    #[tokio::test]
    async fn canister_error_is_mapped_to_a_typed_repository_error() {
        let mock = Mock::start().await;
        mock.reply::<Option<DomainStatusApi>, _>(
            "get_domain_status",
            Err(GetDomainStatusError::Unauthorized),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client
            .get_domain_status(&fqdn!("example.com"))
            .await
            .unwrap_err();

        assert!(
            matches!(err, RepositoryError::Unauthorized),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn canister_internal_error_keeps_its_message() {
        let mock = Mock::start().await;
        mock.reply::<u64, _>(
            "get_last_change_time",
            Err(GetLastChangeTimeError::InternalError("db is down".into())),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.get_last_change_time().await.unwrap_err();

        assert!(
            matches!(err, RepositoryError::InternalError(_)),
            "unexpected error: {err}"
        );
        assert!(
            err.to_string().contains("db is down"),
            "lost message: {err}"
        );
    }

    #[tokio::test]
    async fn undecodable_reply_is_an_internal_error() {
        let mock = Mock::start().await;
        // A bare text instead of the expected `Result<bool, HasNextTaskError>`.
        mock.push(
            "has_next_task",
            Reply::Candid(Encode!(&"surprise").unwrap()),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.has_next_task().await.unwrap_err();

        assert!(
            err.to_string()
                .contains("Failed to decode has_next_task response"),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn replica_rejection_is_an_internal_error() {
        let mock = Mock::start().await;
        mock.push(
            "get_last_change_time",
            Reply::Reject("canister trapped".into()),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.get_last_change_time().await.unwrap_err();

        assert!(
            matches!(err, RepositoryError::InternalError(_)),
            "unexpected error: {err}"
        );
        assert!(
            err.to_string()
                .contains("Canister query get_last_change_time failed"),
            "unexpected error: {err}"
        );
        // The wrapper must not swallow the cause: the canister's reject message survives.
        assert!(
            err.to_string().contains("canister trapped"),
            "lost the rejection message: {err}"
        );
    }

    #[tokio::test]
    async fn http_failure_is_an_internal_error() {
        let mock = Mock::start().await;
        mock.push(
            "has_next_task",
            Reply::Status(StatusCode::INTERNAL_SERVER_ERROR),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.has_next_task().await.unwrap_err();

        assert!(
            err.to_string()
                .contains("Canister query has_next_task failed"),
            "unexpected error: {err}"
        );
        // The wrapper must not swallow the cause: the HTTP status survives.
        assert!(
            err.to_string().contains("500"),
            "lost the HTTP status: {err}"
        );
    }

    #[tokio::test]
    async fn non_cbor_response_is_an_internal_error() {
        let mock = Mock::start().await;
        mock.push("has_next_task", Reply::NotCbor);

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.has_next_task().await.unwrap_err();

        assert!(
            err.to_string()
                .contains("Canister query has_next_task failed"),
            "unexpected error: {err}"
        );
        // The wrapper must not swallow the cause: this failure is distinguishable from the
        // HTTP-level one above because the underlying decoding error is carried along.
        assert!(
            err.to_string().to_lowercase().contains("cbor"),
            "lost the decoding cause: {err}"
        );
    }

    // ---------------------------------------------------------------------------------------
    // has_next_task / get_last_change_time
    // ---------------------------------------------------------------------------------------

    #[tokio::test]
    async fn has_next_task_returns_the_canister_value() {
        let mock = Mock::start().await;
        mock.reply::<bool, HasNextTaskError>("has_next_task", Ok(true));
        mock.reply::<bool, HasNextTaskError>("has_next_task", Ok(false));

        let client = mock.client(Arc::new(PrefixCipher));
        assert!(client.has_next_task().await.unwrap());
        assert!(!client.has_next_task().await.unwrap());

        let state = mock.state();
        assert_eq!(state.methods(), ["has_next_task", "has_next_task"]);
        // The method takes no arguments, so a Candid-encoded unit is sent.
        state.arg::<()>(0);
    }

    #[tokio::test]
    async fn get_last_change_time_returns_the_timestamp() {
        let mock = Mock::start().await;
        mock.reply::<u64, GetLastChangeTimeError>("get_last_change_time", Ok(12_345));

        let client = mock.client(Arc::new(PrefixCipher));
        assert_eq!(client.get_last_change_time().await.unwrap(), 12_345);
    }

    // ---------------------------------------------------------------------------------------
    // all_registrations
    // ---------------------------------------------------------------------------------------

    #[tokio::test]
    async fn all_registrations_walks_all_pages_and_decrypts() {
        let mock = Mock::start().await;
        mock.reply::<_, ListCertificatesPageError>(
            "list_certificates_page",
            Ok(CertificatesPage::new(
                vec![api_domain("a.example.com", "A")],
                Some("b.example.com".into()),
            )),
        );
        mock.reply::<_, ListCertificatesPageError>(
            "list_certificates_page",
            Ok(CertificatesPage::new(
                vec![api_domain("b.example.com", "B")],
                None,
            )),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let domains = client.all_registrations(false).await.unwrap();

        assert_eq!(domains.len(), 2);
        assert_eq!(domains[0].domain, fqdn!("a.example.com"));
        assert_eq!(domains[0].canister_id, principal!("aaaaa-aa"));
        assert_eq!(domains[0].cert, b"CERT-A");
        assert_eq!(domains[0].priv_key, b"KEY-A");
        assert_eq!(domains[1].domain, fqdn!("b.example.com"));
        assert_eq!(domains[1].cert, b"CERT-B");
        assert_eq!(domains[1].priv_key, b"KEY-B");

        let state = mock.state();
        assert_eq!(
            state.methods(),
            ["list_certificates_page", "list_certificates_page"]
        );
        assert!(!state.calls[0].update, "use_update=false must query");

        // First page starts at the beginning, the second continues from `next_key`.
        let first = state.arg::<ListCertificatesPageInput>(0);
        assert_eq!(first.start_key, None);
        assert_eq!(first.limit, None);
        let second = state.arg::<ListCertificatesPageInput>(1);
        assert_eq!(second.start_key, Some("b.example.com".into()));
        assert_eq!(second.limit, None);
    }

    #[tokio::test]
    async fn all_registrations_with_use_update_hits_the_update_endpoint() {
        let mock = Mock::start().await;

        let client = mock.client(Arc::new(PrefixCipher));
        // Update calls cannot be served by the mock, so this fails - but only after the
        // request has been recorded, which is what we assert on.
        let err = client.all_registrations(true).await.unwrap_err();
        assert!(
            err.to_string()
                .contains("Canister update list_certificates_page failed"),
            "unexpected error: {err}"
        );
        // The wrapper must not swallow the cause of a failed update either.
        assert!(
            err.to_string().contains("400"),
            "lost the HTTP status: {err}"
        );

        let state = mock.state();
        assert_eq!(state.methods(), ["list_certificates_page"]);
        assert!(state.calls[0].update, "use_update=true must be an update");
        assert_eq!(state.calls[0].canister, CANISTER_ID);
        assert_eq!(state.arg::<ListCertificatesPageInput>(0).start_key, None);
    }

    #[tokio::test]
    async fn all_registrations_propagates_decryption_failures() {
        let mock = Mock::start().await;
        mock.reply::<_, ListCertificatesPageError>(
            "list_certificates_page",
            Ok(CertificatesPage::new(
                vec![api_domain("a.example.com", "A")],
                None,
            )),
        );

        let client = mock.client(Arc::new(FailingCipher));
        let err = client.all_registrations(false).await.unwrap_err();

        assert!(
            err.to_string().contains("Failed to decrypt data"),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn all_registrations_rejects_a_malformed_domain() {
        let mock = Mock::start().await;
        mock.reply::<_, ListCertificatesPageError>(
            "list_certificates_page",
            Ok(CertificatesPage::new(
                vec![api_domain(BAD_DOMAIN, "A")],
                None,
            )),
        );

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.all_registrations(false).await.unwrap_err();

        assert!(
            err.to_string()
                .contains("Failed to convert RegisteredDomain"),
            "unexpected error: {err}"
        );
    }

    // ---------------------------------------------------------------------------------------
    // fetch_next_task
    // ---------------------------------------------------------------------------------------

    #[tokio::test]
    async fn fetch_next_task_skips_the_update_when_nothing_is_pending() {
        let mock = Mock::start().await;
        mock.reply::<bool, HasNextTaskError>("has_next_task", Ok(false));

        let client = mock.client(Arc::new(PrefixCipher));
        assert!(client.fetch_next_task().await.unwrap().is_none());

        // No update call must be made when there is no task.
        assert_eq!(mock.methods(), ["has_next_task"]);
    }

    #[tokio::test]
    async fn fetch_next_task_issues_an_update_when_a_task_is_pending() {
        let mock = Mock::start().await;
        mock.reply::<bool, HasNextTaskError>("has_next_task", Ok(true));

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client.fetch_next_task().await.unwrap_err();
        assert!(
            err.to_string()
                .contains("Canister update fetch_next_task failed"),
            "unexpected error: {err}"
        );

        let state = mock.state();
        assert_eq!(state.methods(), ["has_next_task", "fetch_next_task"]);
        assert!(!state.calls[0].update);
        assert!(state.calls[1].update, "fetch_next_task must be an update");
    }

    // ---------------------------------------------------------------------------------------
    // submit_task_result
    // ---------------------------------------------------------------------------------------

    fn issue_result() -> TaskResult {
        TaskResult::success(
            fqdn!("example.com"),
            TaskOutput::Issue(IssueCertificateOutput::new(
                principal!("aaaaa-aa"),
                b"CERT".to_vec(),
                b"KEY".to_vec(),
                1,
                2,
            )),
            99,
            TaskKind::Renew,
        )
        .with_duration(Duration::from_secs(42))
    }

    #[tokio::test]
    async fn submit_task_result_encrypts_certificate_and_key() {
        let mock = Mock::start().await;

        let client = mock.client(Arc::new(PrefixCipher));
        // The update itself cannot succeed against the mock; we assert on what was sent.
        let err = client.submit_task_result(issue_result()).await.unwrap_err();
        assert!(
            err.to_string()
                .contains("Canister update submit_task_result failed"),
            "unexpected error: {err}"
        );

        let state = mock.state();
        assert_eq!(state.methods(), ["submit_task_result"]);
        assert!(state.calls[0].update);

        let sent = state.arg::<TaskResultApi>(0);
        assert_eq!(sent.domain, "example.com");
        assert_eq!(sent.task_id, 99);
        assert_eq!(sent.task_kind, TaskKindApi::Renew);
        assert_eq!(sent.duration_secs, 42);

        let TaskOutcomeApi::Success(TaskOutputApi::Issue(issued)) = sent.outcome else {
            panic!("expected a successful issuance outcome");
        };
        assert_eq!(issued.enc_cert, b"ENC:CERT");
        assert_eq!(issued.enc_priv_key, b"ENC:KEY");
        assert_eq!(issued.canister_id, principal!("aaaaa-aa"));
        assert_eq!(issued.not_before, 1);
        assert_eq!(issued.not_after, 2);
    }

    #[tokio::test]
    async fn submit_task_result_reports_which_field_failed_to_encrypt() {
        let mock = Mock::start().await;

        let client = mock.client(Arc::new(FailingCipher));
        let err = client.submit_task_result(issue_result()).await.unwrap_err();

        assert!(
            matches!(err, RepositoryError::InternalError(_)),
            "unexpected error: {err}"
        );
        // The certificate is encrypted first, so it is the field that is reported.
        assert!(
            err.to_string().contains("Failed to encrypt certificate"),
            "unexpected error: {err}"
        );
        // Nothing must be sent to the canister if encryption failed.
        assert!(mock.methods().is_empty());
    }

    #[tokio::test]
    async fn submit_task_result_does_not_encrypt_non_issue_outcomes() {
        let mock = Mock::start().await;

        // A failing cipher must not matter: there is nothing to encrypt in a failure result.
        let client = mock.client(Arc::new(FailingCipher));
        let err = client
            .submit_task_result(
                TaskResult::failure(
                    fqdn!("example.com"),
                    TaskFailReason::RateLimited,
                    7,
                    TaskKind::Delete,
                )
                .with_duration(Duration::from_secs(3)),
            )
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("Canister update submit_task_result failed"),
            "unexpected error: {err}"
        );

        let state = mock.state();
        let sent = state.arg::<TaskResultApi>(0);
        assert_eq!(sent.task_kind, TaskKindApi::Delete);
        assert_eq!(sent.task_id, 7);
        assert_eq!(sent.duration_secs, 3);
        assert!(
            matches!(sent.outcome, TaskOutcomeApi::Failure(_)),
            "unexpected outcome: {:?}",
            sent.outcome
        );
    }

    // ---------------------------------------------------------------------------------------
    // try_add_task
    // ---------------------------------------------------------------------------------------

    #[tokio::test]
    async fn try_add_task_sends_the_converted_task() {
        let mock = Mock::start().await;

        let client = mock.client(Arc::new(PrefixCipher));
        let err = client
            .try_add_task(InputTask::new(
                TaskKind::Issue,
                fqdn!("example.com"),
                true,
                Some(principal!("aaaaa-aa")),
            ))
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("Canister update try_add_task failed"),
            "unexpected error: {err}"
        );

        let state = mock.state();
        assert_eq!(state.methods(), ["try_add_task"]);
        assert!(state.calls[0].update);

        let sent = state.arg::<InputTaskApi>(0);
        assert_eq!(sent.kind, TaskKindApi::Issue);
        assert_eq!(sent.domain, "example.com");
        assert_eq!(sent.wildcard, Some(true));
        assert_eq!(sent.canister_id, Some(principal!("aaaaa-aa")));
    }

    // ---------------------------------------------------------------------------------------
    // Caching
    // ---------------------------------------------------------------------------------------

    /// Programs a `get_last_change_time` + single-page `list_certificates_page` pair.
    fn program_refresh(mock: &Mock, timestamp: u64) {
        mock.reply::<u64, GetLastChangeTimeError>("get_last_change_time", Ok(timestamp));
        mock.reply::<_, ListCertificatesPageError>(
            "list_certificates_page",
            Ok(CertificatesPage::new(
                vec![api_domain("a.example.com", "A")],
                None,
            )),
        );
    }

    #[tokio::test]
    async fn update_cache_fills_both_caches() {
        let mock = Mock::start().await;
        program_refresh(&mock, 555);

        let client = mock.client(Arc::new(PrefixCipher));
        assert!(client.get_certificates().await.unwrap().is_empty());
        assert!(client.get_custom_domains().await.unwrap().is_empty());

        client.update_cache(None, false).await.unwrap();

        // The certificate cache holds the decrypted cert followed by the private key.
        assert_eq!(
            client.get_certificates().await.unwrap(),
            vec![Pem(b"CERT-AKEY-A".to_vec())]
        );
        assert_eq!(
            client.get_custom_domains().await.unwrap(),
            vec![CustomDomain {
                name: fqdn!("a.example.com"),
                canister_id: principal!("aaaaa-aa"),
                timestamp: 0,
                priority: 7,
                flags: Some(DomainFlags::new([FLAG_TEST])),
            }]
        );
        assert_eq!(client.last_change_time.load(Ordering::SeqCst), 555);
        assert_eq!(
            mock.methods(),
            ["get_last_change_time", "list_certificates_page"]
        );
    }

    #[tokio::test]
    async fn update_cache_uses_the_supplied_timestamp_without_querying() {
        let mock = Mock::start().await;
        program_refresh(&mock, 555);

        let client = mock.client(Arc::new(PrefixCipher));
        client.update_cache(Some(77), false).await.unwrap();

        assert_eq!(client.last_change_time.load(Ordering::SeqCst), 77);
        assert_eq!(mock.methods(), ["list_certificates_page"]);
    }

    #[tokio::test]
    async fn failed_refresh_leaves_the_cache_intact() {
        let mock = Mock::start().await;
        program_refresh(&mock, 555);

        let client = mock.client(Arc::new(PrefixCipher));
        client.update_cache(None, false).await.unwrap();

        // Only the timestamp is programmed this time, so fetching the pages fails.
        mock.reply::<u64, GetLastChangeTimeError>("get_last_change_time", Ok(999));
        let err = client.update_cache(None, false).await.unwrap_err();
        assert!(
            format!("{err:#}").contains("unable to fetch registrations data"),
            "unexpected error: {err:#}"
        );

        assert_eq!(
            client.get_certificates().await.unwrap(),
            vec![Pem(b"CERT-AKEY-A".to_vec())]
        );
        assert_eq!(client.last_change_time.load(Ordering::SeqCst), 555);
    }

    #[tokio::test]
    async fn conditional_update_skips_the_fetch_when_nothing_changed() {
        let mock = Mock::start().await;
        mock.reply::<u64, GetLastChangeTimeError>("get_last_change_time", Ok(42));

        let client = mock.client(Arc::new(PrefixCipher));
        client.last_change_time.store(42, Ordering::SeqCst);

        client.update_cache_conditional().await.unwrap();

        assert_eq!(mock.methods(), ["get_last_change_time"]);
    }

    #[tokio::test]
    async fn conditional_update_refetches_when_the_timestamp_moved() {
        let mock = Mock::start().await;
        mock.reply::<u64, GetLastChangeTimeError>("get_last_change_time", Ok(43));

        let client = mock.client(Arc::new(PrefixCipher));
        client.last_change_time.store(42, Ordering::SeqCst);

        // A changed timestamp triggers a full refresh, which uses update calls.
        let err = client.update_cache_conditional().await.unwrap_err();
        assert!(
            format!("{err:#}").contains("unable to fetch registrations data"),
            "unexpected error: {err:#}"
        );

        let state = mock.state();
        assert_eq!(
            state.methods(),
            ["get_last_change_time", "list_certificates_page"]
        );
        assert!(
            state.calls[1].update,
            "a conditional refresh must use update calls"
        );
        // The cached timestamp must only advance after a successful refresh.
        assert_eq!(client.last_change_time.load(Ordering::SeqCst), 42);
    }
}