Skip to main content

vcon_server/store/
purge.rs

1//! When a kept version is erased: the purge rule, apart from the files and
2//! rows it touches, so its boundaries can be tested directly.
3
4use time::OffsetDateTime;
5use uuid::Uuid;
6
7use super::{Store, StoreError, commit, io};
8use crate::audit::{Action, Actor, Entry};
9use crate::backend::ObjectError;
10use crate::clock::{from_nanos, nanos};
11use crate::ids::VersionId;
12use crate::retention::Retention;
13
14/// What the purge rule reads of one version.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct Kept {
17    /// When the version was stored; retention counts from here.
18    pub stored_at: OffsetDateTime,
19    /// Whether it was replaced or its uuid deleted. A current version is
20    /// never purged.
21    pub hidden: bool,
22    /// Whether its uuid is under a legal hold.
23    pub held: bool,
24}
25
26/// Whether `version` is due for purge at `now` under `retention`: it is
27/// hidden, its uuid has no hold, and `retention` has passed since it was
28/// stored, counted in calendar time in UTC. A period that ends past the
29/// last time this build can hold never passes. A version hidden after it
30/// reached that age is due at once.
31pub fn due(version: &Kept, retention: Retention, now: OffsetDateTime) -> bool {
32    version.hidden
33        && !version.held
34        && retention
35            .after(version.stored_at)
36            .is_some_and(|end| now >= end)
37}
38
39/// What a purge did.
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
41pub struct PurgeReport {
42    /// Versions erased.
43    pub purged: u64,
44}
45
46impl Store {
47    /// Erases every version due under `retention`. Each goes in a
48    /// transaction of its own that checks the rule again, so a restore or
49    /// a hold that commits first keeps it. The transaction deletes the
50    /// version's row, and with it the only copy of its wrapped data key,
51    /// and records the purge; a deleted uuid left with no version gives up
52    /// its row for a tombstone. The object file is removed after the
53    /// commit. Last, the WAL is checkpointed with truncation, tried again
54    /// while readers finish, so no page that held a purged key is left in
55    /// it.
56    pub fn purge_due(&self, retention: Retention) -> Result<PurgeReport, StoreError> {
57        self.purge_hidden(Actor::Sweep, retention, None)
58    }
59
60    /// Purges, as `purge_due` does, the hidden versions that are due, with
61    /// `who` as the actor of each record; with `uuid`, only that uuid's.
62    pub(super) fn purge_hidden(
63        &self,
64        who: Actor,
65        retention: Retention,
66        uuid: Option<Uuid>,
67    ) -> Result<PurgeReport, StoreError> {
68        let hidden = self.read(|tx| tx.hidden_versions(uuid))?;
69        // A restore, hold or read may commit here, between the listing and
70        // each version's own transaction, which checks the rule again.
71        self.pause();
72        let mut report = PurgeReport::default();
73        for version in hidden {
74            if self.purge(who, version, retention)? {
75                report.purged += 1;
76            }
77        }
78        // Every pack file a purge listed, this one's or one cut off before,
79        // is rewritten and the old file deleted and confirmed gone, before
80        // the sweep returns.
81        self.finish_purges()?;
82        if report.purged > 0 {
83            self.catalog.after_purge()?;
84        }
85        Ok(report)
86    }
87
88    /// Purges `version` if it is due; false if it is not, or is gone.
89    fn purge(
90        &self,
91        who: Actor,
92        version: VersionId,
93        retention: Retention,
94    ) -> Result<bool, StoreError> {
95        let mut tx = self.catalog.immediate()?;
96        let Some(row) = tx.hidden_row(version)? else {
97            return Ok(false);
98        };
99        // The version's store time was written by the catalog's clock in
100        // its write's transaction, on whichever server took the write: it
101        // is judged by the same clock here.
102        let now = from_nanos(self.now_in(tx.as_mut())?).ok_or(StoreError::Damaged)?;
103        let kept = Kept {
104            stored_at: from_nanos(row.stored_at).ok_or(StoreError::Damaged)?,
105            hidden: true,
106            held: row.held,
107        };
108        if !due(&kept, retention, now) {
109            return Ok(false);
110        }
111        // A packed version's bytes are in a file with other rows: the file
112        // is listed here, in the same transaction, and rewritten without
113        // them before the sweep returns.
114        let file = tx
115            .version_row(version)?
116            .and_then(|r| r.place)
117            .map(|p| p.file);
118        if let Some(file) = file {
119            tx.add_purge_pending(file)?;
120        }
121        tx.delete_version(version)?;
122        if row.deleted && tx.versions_of(row.uuid)? == 0 {
123            tx.tombstone(row.uuid, nanos(now))?;
124        }
125        let entry = Entry {
126            actor: who,
127            action: Action::Purge,
128            target: Some(row.uuid.to_string()),
129            version: Some(version),
130            status: 200,
131        };
132        self.record(&mut tx, &entry)?;
133        commit(tx)?;
134        if file.is_some() {
135            return Ok(true);
136        }
137        // An object already gone is what the purge wants: it was lost, or
138        // removed by a purge cut off after its commit. Some storage (S3)
139        // cannot tell such a removal from any other.
140        match self.objects.remove(version) {
141            Ok(()) | Err(ObjectError::Missing) => Ok(true),
142            Err(e) => Err(io(e)),
143        }
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use time::Duration;
150    use time::macros::datetime;
151
152    use super::*;
153
154    const SECOND: Duration = Duration::seconds(1);
155
156    fn hidden(stored_at: OffsetDateTime) -> Kept {
157        Kept {
158            stored_at,
159            hidden: true,
160            held: false,
161        }
162    }
163
164    #[test]
165    fn a_hidden_version_is_due_from_the_second_its_period_ends() {
166        let seven = Retention::Years(7);
167        let cases = [
168            // Stored on an ordinary day: due seven calendar years later.
169            (
170                datetime!(2026-03-15 10:00 UTC),
171                datetime!(2033-03-15 10:00 UTC),
172            ),
173            // Stored on 29 February: due on 28 February seven years later,
174            // not on 1 March.
175            (
176                datetime!(2028-02-29 12:00 UTC),
177                datetime!(2035-02-28 12:00 UTC),
178            ),
179        ];
180        for (stored_at, end) in cases {
181            let version = hidden(stored_at);
182            assert!(
183                !due(&version, seven, end - SECOND),
184                "{stored_at}: a second short"
185            );
186            assert!(due(&version, seven, end), "{stored_at}: at the end");
187            assert!(
188                due(&version, seven, end + SECOND),
189                "{stored_at}: a second past"
190            );
191        }
192    }
193
194    #[test]
195    fn a_hold_keeps_a_version_past_its_end() {
196        let stored_at = datetime!(2028-02-29 12:00 UTC);
197        let end = datetime!(2035-02-28 12:00 UTC);
198        let version = Kept {
199            held: true,
200            ..hidden(stored_at)
201        };
202        for now in [end - SECOND, end, end + SECOND, end + Duration::days(3650)] {
203            assert!(!due(&version, Retention::Years(7), now), "{now}");
204        }
205    }
206
207    #[test]
208    fn a_current_version_is_never_due() {
209        let version = Kept {
210            hidden: false,
211            ..hidden(datetime!(2026-03-15 10:00 UTC))
212        };
213        let end = datetime!(2033-03-15 10:00 UTC);
214        for now in [end - SECOND, end, end + SECOND] {
215            assert!(!due(&version, Retention::Years(7), now), "{now}");
216        }
217    }
218
219    #[test]
220    fn a_zero_period_makes_a_hidden_version_due_at_once() {
221        let stored_at = datetime!(2026-03-15 10:00 UTC);
222        let version = hidden(stored_at);
223        assert!(due(&version, Retention::Days(0), stored_at));
224        assert!(!due(&version, Retention::Days(0), stored_at - SECOND));
225    }
226
227    #[test]
228    fn a_period_ending_past_the_last_time_held_is_never_due() {
229        let version = hidden(datetime!(9998-06-01 00:00 UTC));
230        let last = datetime!(9999-12-31 23:59:59 UTC);
231        assert!(!due(&version, Retention::Years(7), last));
232    }
233}
234
235#[cfg(test)]
236mod purge_tests {
237    use std::path::Path;
238    use std::sync::{Arc, mpsc};
239    use std::time::Duration as Wait;
240
241    use aws_lc_rs::cipher::{AES_256, DecryptingKey, DecryptionContext, UnboundCipherKey};
242    use aws_lc_rs::iv::FixedLength;
243    use serde_json::Value;
244    use time::Duration;
245    use uuid::Uuid;
246
247    use super::super::testing::vcon;
248    use super::super::tests::{Fixture, fixture};
249    use super::*;
250    use crate::catalog;
251    use crate::clock::Clock;
252    use crate::envelope::{self, Key};
253    use crate::fs::Fs;
254    use crate::ids::VersionId;
255    use crate::store::{Created, StoreError};
256
257    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
258    const DAY: Retention = Retention::Days(1);
259
260    /// Stores a vCon and returns its uuid and version.
261    fn stored(f: &Fixture, subject: &str) -> (Uuid, VersionId) {
262        let (found, body) = vcon(UUID, subject);
263        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
264            panic!("a new vCon")
265        };
266        (found.uuid, version)
267    }
268
269    fn later(f: &Fixture, by: Duration) {
270        f.clock.set(f.clock.now() + by);
271    }
272
273    fn count(f: &Fixture, sql: &str, uuid: Uuid) -> i64 {
274        f.store
275            .conn()
276            .query_row(sql, [uuid.as_bytes()], |r| r.get(0))
277            .expect(sql)
278    }
279
280    fn wrapped_key(f: &Fixture, version: VersionId) -> Vec<u8> {
281        f.store
282            .conn()
283            .query_row(
284                "SELECT wrapped_key FROM version WHERE version = ?1",
285                [version.0],
286                |r| r.get(0),
287            )
288            .expect("row")
289    }
290
291    fn object_exists(f: &Fixture, version: VersionId) -> bool {
292        f.fs.read(&f.store.objects_dir.join(version.to_string()))
293            .is_ok()
294    }
295
296    fn purges(f: &Fixture) -> Vec<Value> {
297        f.store
298            .records()
299            .into_iter()
300            .filter(|r| r["action"] == "purge")
301            .collect()
302    }
303
304    #[test]
305    fn a_purge_erases_a_deleted_vcon_and_leaves_a_tombstone() {
306        let f = fixture();
307        let (uuid, version) = stored(&f, "first");
308        f.store
309            .delete(&f.caller, uuid, Retention::Years(7))
310            .expect("deletes");
311        later(&f, Duration::days(2));
312
313        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 1 }));
314
315        assert_eq!(
316            count(&f, "SELECT count(*) FROM version WHERE uuid = ?1", uuid),
317            0
318        );
319        assert_eq!(
320            count(&f, "SELECT count(*) FROM vcon WHERE uuid = ?1", uuid),
321            0
322        );
323        assert_eq!(
324            count(&f, "SELECT count(*) FROM tombstone WHERE uuid = ?1", uuid),
325            1
326        );
327        let purged_at: i64 = f
328            .store
329            .conn()
330            .query_row(
331                "SELECT purged_at FROM tombstone WHERE uuid = ?1",
332                [uuid.as_bytes()],
333                |r| r.get(0),
334            )
335            .expect("tombstone");
336        assert_eq!(
337            purged_at,
338            nanos(f.clock.now()),
339            "the tombstone holds the purge time"
340        );
341        assert!(!object_exists(&f, version), "the object file is removed");
342        let records = purges(&f);
343        assert_eq!(records.len(), 1);
344        assert_eq!(records[0]["actor"], "sweep");
345        assert_eq!(records[0]["target"], uuid.to_string());
346        assert_eq!(records[0]["version"], version.to_string());
347        assert_eq!(f.store.get(&f.caller, uuid), Err(StoreError::Gone));
348        let (found, body) = vcon(UUID, "again");
349        assert_eq!(
350            f.store.create(&f.caller, &found, &body),
351            Err(StoreError::Gone),
352            "a purged uuid cannot be stored again"
353        );
354    }
355
356    #[test]
357    fn a_purge_of_a_replaced_version_keeps_the_live_vcon() {
358        let f = fixture();
359        let (uuid, old) = stored(&f, "first");
360        let (found, body) = vcon(UUID, "second");
361        let new = f
362            .store
363            .replace(&f.caller, old, &found, &body)
364            .expect("replaces");
365        later(&f, Duration::days(2));
366
367        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 1 }));
368
369        assert_eq!(
370            count(&f, "SELECT count(*) FROM version WHERE uuid = ?1", uuid),
371            1
372        );
373        assert_eq!(
374            count(&f, "SELECT count(*) FROM tombstone WHERE uuid = ?1", uuid),
375            0
376        );
377        assert!(!object_exists(&f, old));
378        assert!(object_exists(&f, new));
379        assert_eq!(f.store.get(&f.caller, uuid).expect("reads").body, body);
380    }
381
382    #[test]
383    fn versions_not_due_are_kept() {
384        let f = fixture();
385        // Current: never due.
386        let (current, _) = stored(&f, "current");
387        // Deleted, but held.
388        let (found, body) = vcon("0199e5c6-0d7a-7c11-8000-000000000001", "held");
389        f.store.create(&f.caller, &found, &body).expect("stores");
390        f.store
391            .delete(&f.caller, found.uuid, Retention::Years(7))
392            .expect("deletes");
393        f.store
394            .conn()
395            .execute(
396                "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
397                [found.uuid.as_bytes()],
398            )
399            .expect("holds");
400        later(&f, Duration::days(2));
401        // Deleted, but stored too recently.
402        let (young, body) = vcon("0199e5c6-0d7a-7c11-8000-000000000002", "young");
403        f.store.create(&f.caller, &young, &body).expect("stores");
404        f.store
405            .delete(&f.caller, young.uuid, Retention::Years(7))
406            .expect("deletes");
407
408        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 0 }));
409
410        for uuid in [current, found.uuid, young.uuid] {
411            assert_eq!(
412                count(&f, "SELECT count(*) FROM version WHERE uuid = ?1", uuid),
413                1
414            );
415        }
416        assert!(purges(&f).is_empty());
417    }
418
419    #[test]
420    fn deleting_an_old_vcon_erases_it_at_once() {
421        let f = fixture();
422        let (uuid, version) = stored(&f, "first");
423        later(&f, Duration::days(2));
424
425        assert_eq!(f.store.delete(&f.caller, uuid, DAY), Ok(()));
426
427        assert_eq!(
428            count(&f, "SELECT count(*) FROM version WHERE uuid = ?1", uuid),
429            0
430        );
431        assert_eq!(
432            count(&f, "SELECT count(*) FROM tombstone WHERE uuid = ?1", uuid),
433            1
434        );
435        assert!(!object_exists(&f, version));
436        let records = purges(&f);
437        assert_eq!(records.len(), 1);
438        assert_eq!(
439            records[0]["actor"],
440            f.caller.key.to_string(),
441            "the delete that caused the purge is its actor"
442        );
443    }
444
445    #[test]
446    fn deleting_a_young_vcon_keeps_it_hidden() {
447        let f = fixture();
448        let (uuid, version) = stored(&f, "first");
449        later(&f, Duration::hours(23));
450
451        assert_eq!(f.store.delete(&f.caller, uuid, DAY), Ok(()));
452
453        assert_eq!(
454            count(
455                &f,
456                "SELECT count(*) FROM version WHERE uuid = ?1 AND hidden_at IS NOT NULL",
457                uuid
458            ),
459            1
460        );
461        assert!(object_exists(&f, version));
462        assert!(purges(&f).is_empty());
463    }
464
465    #[test]
466    fn a_zero_period_erases_inside_the_delete() {
467        let f = fixture();
468        let (uuid, version) = stored(&f, "first");
469
470        assert_eq!(f.store.delete(&f.caller, uuid, Retention::Days(0)), Ok(()));
471
472        assert_eq!(
473            count(&f, "SELECT count(*) FROM tombstone WHERE uuid = ?1", uuid),
474            1
475        );
476        assert!(!object_exists(&f, version));
477    }
478
479    #[test]
480    fn a_delete_purges_only_its_own_uuid() {
481        let f = fixture();
482        let (uuid, _) = stored(&f, "first");
483        let (other, body) = vcon("0199e5c6-0d7a-7c11-8000-000000000003", "other");
484        f.store.create(&f.caller, &other, &body).expect("stores");
485        f.store
486            .delete(&f.caller, other.uuid, Retention::Years(7))
487            .expect("deletes");
488        later(&f, Duration::days(2));
489
490        f.store.delete(&f.caller, uuid, DAY).expect("deletes");
491
492        assert_eq!(
493            count(
494                &f,
495                "SELECT count(*) FROM version WHERE uuid = ?1",
496                other.uuid
497            ),
498            1,
499            "the other uuid waits for the sweep"
500        );
501    }
502
503    #[test]
504    fn a_delete_whose_purge_fails_stands_and_answers_the_failure() {
505        let f = fixture();
506        let (uuid, version) = stored(&f, "first");
507        later(&f, Duration::days(2));
508        f.store
509            .conn()
510            .execute_batch(
511                "CREATE TEMP TRIGGER no_purge BEFORE DELETE ON version
512                 BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
513            )
514            .expect("trigger");
515
516        assert_eq!(
517            f.store.delete(&f.caller, uuid, DAY),
518            Err(StoreError::Io),
519            "the delete answers the failed purge: the store's I/O error, not a refusal"
520        );
521
522        assert_eq!(f.store.get(&f.caller, uuid), Err(StoreError::Gone));
523        assert_eq!(
524            count(
525                &f,
526                "SELECT count(*) FROM version WHERE uuid = ?1 AND hidden_at IS NOT NULL",
527                uuid
528            ),
529            1,
530            "kept hidden for the sweep to purge"
531        );
532        assert!(object_exists(&f, version));
533    }
534
535    #[test]
536    fn deleting_again_erases_what_has_since_come_due() {
537        let f = fixture();
538        let (uuid, version) = stored(&f, "first");
539        f.store
540            .delete(&f.caller, uuid, Retention::Years(7))
541            .expect("deletes");
542        later(&f, Duration::days(2));
543
544        assert_eq!(f.store.delete(&f.caller, uuid, DAY), Ok(()));
545
546        assert!(!object_exists(&f, version));
547    }
548
549    /// Stores a vCon, deletes it while seven years apply, and moves the
550    /// clock two days on, so under one day it is due for purge.
551    fn due_for_purge(f: &Fixture) -> (Uuid, VersionId, Vec<u8>) {
552        let (found, body) = vcon(UUID, "first");
553        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
554            panic!("a new vCon")
555        };
556        f.store
557            .delete(&f.caller, found.uuid, Retention::Years(7))
558            .expect("deleted");
559        later(f, Duration::days(2));
560        (found.uuid, version, body)
561    }
562
563    #[test]
564    fn a_purge_cut_off_before_its_commit_leaves_the_version_whole() {
565        let mut f = fixture();
566        let (uuid, version, body) = due_for_purge(&f);
567        let other = super::super::tests::second_connection(&f);
568        other
569            .execute_batch(
570                "CREATE TRIGGER dead BEFORE INSERT ON audit
571                 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
572            )
573            .expect("trigger");
574
575        assert!(f.store.purge_due(DAY).is_err());
576        drop(other);
577        super::super::tests::restart(&mut f);
578
579        let read = f.store.legal_get(&f.caller, uuid, None).expect("whole");
580        assert_eq!((read.stored.version, read.stored.body), (version, body));
581        assert!(object_exists(&f, version));
582        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 1 }));
583        assert!(!object_exists(&f, version));
584    }
585
586    #[test]
587    fn a_purge_cut_off_at_its_file_step_is_finished_by_recovery() {
588        // Step 0 fails the removal itself; step 1 removes it unsynced, so a
589        // crash brings the file back.
590        for step in 0..=1 {
591            let mut f = fixture();
592            let (uuid, version, _) = due_for_purge(&f);
593            f.fs.fail_from(f.fs.log().len() + step);
594            let _ = f.store.purge_due(DAY);
595            super::super::tests::restart(&mut f);
596
597            assert_eq!(
598                count(&f, "SELECT count(*) FROM version WHERE uuid = ?1", uuid),
599                0,
600                "step {step}: the commit stands"
601            );
602            assert_eq!(
603                count(&f, "SELECT count(*) FROM tombstone WHERE uuid = ?1", uuid),
604                1,
605                "step {step}"
606            );
607            assert!(
608                !object_exists(&f, version),
609                "step {step}: recovery removes the file"
610            );
611            assert_eq!(
612                f.store.legal_get(&f.caller, uuid, None),
613                Err(StoreError::Gone),
614                "step {step}"
615            );
616        }
617    }
618
619    /// Runs `legal` on the store between the purge's listing of hidden
620    /// versions and its transaction for each, as a racing request would.
621    fn between_listing_and_purge(f: &Arc<Fixture>, legal: impl FnOnce(&Fixture) + Send + 'static) {
622        let racer = f.clone();
623        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || legal(&racer)));
624    }
625
626    #[test]
627    fn a_restore_that_commits_before_the_purge_keeps_the_vcon_live() {
628        let f = Arc::new(fixture());
629        let (uuid, version, body) = due_for_purge(&f);
630        between_listing_and_purge(&f, move |racer| {
631            racer.store.restore(&racer.caller, uuid).expect("restored");
632        });
633
634        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 0 }));
635
636        let read = f.store.get(&f.caller, uuid).expect("live");
637        assert_eq!((read.version, read.body), (version, body));
638    }
639
640    #[test]
641    fn a_hold_that_commits_before_the_purge_keeps_the_version() {
642        let f = Arc::new(fixture());
643        let (uuid, version, body) = due_for_purge(&f);
644        between_listing_and_purge(&f, move |racer| {
645            racer
646                .store
647                .set_hold(&racer.caller, uuid, true)
648                .expect("held");
649        });
650
651        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 0 }));
652
653        let read = f.store.legal_get(&f.caller, uuid, None).expect("kept");
654        assert_eq!((read.stored.version, read.stored.body), (version, body));
655    }
656
657    #[test]
658    fn a_legal_read_racing_a_purge_gets_the_whole_body_or_gone() {
659        let f = Arc::new(fixture());
660        let (uuid, _, body) = due_for_purge(&f);
661        let (seen_tx, seen) = mpsc::channel();
662        between_listing_and_purge(&f, move |racer| {
663            seen_tx
664                .send(racer.store.legal_get(&racer.caller, uuid, None))
665                .expect("send");
666        });
667
668        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 1 }));
669
670        let before = seen
671            .recv_timeout(Wait::from_secs(5))
672            .expect("the racing read ran");
673        assert_eq!(before.expect("before the purge").stored.body, body);
674        assert_eq!(
675            f.store.legal_get(&f.caller, uuid, None),
676            Err(StoreError::Gone),
677            "after it"
678        );
679    }
680
681    /// The plain contents of every page of the catalog at `path` and of
682    /// every frame in its WAL, decrypted as SQLCipher 4 writes them:
683    /// AES-256-CBC under the raw catalog key, the last 80 bytes of each
684    /// page reserved for its 16-byte IV and 64-byte HMAC, and the first 16
685    /// bytes of page 1 holding the salt in the clear.
686    fn plain_pages(path: &Path, key: &Key, page_size: usize) -> Vec<Vec<u8>> {
687        const RESERVED: usize = 80;
688        const IV: usize = 16;
689        const SALT: usize = 16;
690        let raw = key.sqlcipher_raw();
691        let hex = &raw[2..66];
692        let key: Vec<u8> = (0..32)
693            .map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).expect("hex"))
694            .collect();
695        let decrypt = |number: u32, page: &[u8]| {
696            let start = if number == 1 { SALT } else { 0 };
697            let end = page_size - RESERVED;
698            let iv: [u8; IV] = page[end..end + IV].try_into().expect("an IV");
699            let mut text = page[start..end].to_vec();
700            let cipher = DecryptingKey::cbc(UnboundCipherKey::new(&AES_256, &key).expect("key"))
701                .expect("CBC");
702            cipher
703                .decrypt(&mut text, DecryptionContext::Iv128(FixedLength::from(iv)))
704                .expect("decrypts");
705            text
706        };
707        let mut pages = Vec::new();
708        let db = std::fs::read(path).expect("catalog");
709        for (i, page) in db.chunks_exact(page_size).enumerate() {
710            pages.push(decrypt(u32::try_from(i + 1).expect("page number"), page));
711        }
712        let mut wal_path = path.as_os_str().to_owned();
713        wal_path.push("-wal");
714        let wal = std::fs::read(&wal_path).unwrap_or_default();
715        if let Some(frames) = wal.get(32..) {
716            for frame in frames.chunks_exact(24 + page_size) {
717                let number = u32::from_be_bytes(frame[..4].try_into().expect("4 bytes"));
718                pages.push(decrypt(number, &frame[24..]));
719            }
720        }
721        pages
722    }
723
724    fn holds(pages: &[Vec<u8>], needle: &[u8]) -> bool {
725        pages
726            .iter()
727            .any(|page| page.windows(needle.len()).any(|w| w == needle))
728    }
729
730    #[test]
731    fn no_copy_of_a_purged_wrapped_key_is_left_in_the_catalog() {
732        let f = fixture();
733        let (uuid, version) = stored(&f, "first");
734        let wrapped = wrapped_key(&f, version);
735        f.store
736            .delete(&f.caller, uuid, Retention::Years(7))
737            .expect("deletes");
738        let path = f.dir.path().join("catalog.sqlite");
739        let key = envelope::catalog_key(&f.store.tenant_key).expect("catalog key");
740        let page_size = crate::catalog::tests::cipher_setting(&f.store.conn(), "cipher_page_size");
741        let page_size: usize = page_size.parse().expect("a page size");
742        // The scan must see the key before the purge, or finding nothing
743        // afterwards would prove nothing.
744        assert!(holds(&plain_pages(&path, &key, page_size), &wrapped));
745        later(&f, Duration::days(2));
746
747        assert_eq!(f.store.purge_due(DAY), Ok(PurgeReport { purged: 1 }));
748
749        assert!(!holds(&plain_pages(&path, &key, page_size), &wrapped));
750        let mut wal = path.as_os_str().to_owned();
751        wal.push("-wal");
752        assert_eq!(
753            std::fs::metadata(&wal).expect("WAL").len(),
754            0,
755            "WAL truncated"
756        );
757    }
758
759    /// Lets the test's reader go when dropped.
760    struct LetGo(mpsc::Sender<()>);
761
762    impl Drop for LetGo {
763        fn drop(&mut self) {
764            let _ = self.0.send(());
765        }
766    }
767
768    #[test]
769    fn the_checkpoint_waits_for_a_reader_without_holding_the_catalog() {
770        let f = fixture();
771        let (uuid, _) = stored(&f, "first");
772        f.store
773            .delete(&f.caller, uuid, Retention::Years(7))
774            .expect("deletes");
775        later(&f, Duration::days(2));
776        let path = f.dir.path().join("catalog.sqlite");
777        let key = envelope::catalog_key(&f.store.tenant_key).expect("catalog key");
778        let mut reader = catalog::open(&path, &key, "").expect("a second connection");
779        // The reader holds its snapshot until this thread lets it go,
780        // after the checks below, so no timing decides what they see.
781        let (reading, started) = mpsc::channel();
782        let (release, released) = mpsc::channel::<()>();
783        let held = std::thread::spawn(move || {
784            let tx = reader.transaction().expect("begin");
785            let _: i64 = tx
786                .query_row("SELECT count(*) FROM version", [], |r| r.get(0))
787                .expect("reads");
788            reading.send(()).expect("signal");
789            released
790                .recv_timeout(std::time::Duration::from_secs(30))
791                .expect("let go");
792            drop(tx);
793        });
794        started
795            .recv_timeout(std::time::Duration::from_secs(30))
796            .expect("the reader started");
797        let (busy, waiting) = mpsc::channel();
798        f.store.catalog.on_checkpoint_wait(busy);
799
800        std::thread::scope(|s| {
801            let purging = s.spawn(|| f.store.purge_due(DAY));
802            // Dropped on the way out of this block, also when a check below
803            // fails, so the purge never waits for the reader forever and the
804            // failure is reported instead of hanging the test.
805            let let_go = LetGo(release);
806            waiting
807                .recv_timeout(Wait::from_secs(20))
808                .expect("the purge reaches its checkpoint and waits for the reader");
809            // In a thread of its own, so a catalog held by the checkpoint
810            // fails here instead of hanging the test.
811            let (answer, answered) = mpsc::channel();
812            let store = &f.store;
813            let counting = s.spawn(move || answer.send(store.counts().is_ok()));
814            assert_eq!(
815                answered.recv_timeout(Wait::from_secs(20)),
816                Ok(true),
817                "the catalog answers another call while the checkpoint waits"
818            );
819            counting.join().expect("the count finished").expect("sent");
820            drop(let_go);
821            assert_eq!(
822                purging.join().expect("the purge finished"),
823                Ok(PurgeReport { purged: 1 }),
824                "the purge completes once the reader is gone"
825            );
826        });
827        held.join().expect("the reader finished");
828        let timeout: i64 = f
829            .store
830            .conn()
831            .pragma_query_value(None, "busy_timeout", |r| r.get(0))
832            .expect("busy timeout");
833        assert_eq!(timeout, 5000, "the catalog's busy timeout is restored");
834        let mut wal = path.as_os_str().to_owned();
835        wal.push("-wal");
836        assert_eq!(
837            std::fs::metadata(&wal).expect("WAL").len(),
838            0,
839            "WAL truncated"
840        );
841    }
842}