Skip to main content

vcon_server/store/
legal.rs

1//! Legal access: reading a deleted or replaced vCon, and listing what is
2//! kept of a uuid, for a legal key. Access decides who holds a legal key;
3//! these calls trust their caller and record each answer.
4
5use time::OffsetDateTime;
6use uuid::Uuid;
7
8use super::{Caller, Store, StoreError, Stored, Tx, commit, version_row};
9use crate::audit::{Action, Actor, Entry};
10use crate::clock::from_nanos;
11use crate::ids::VersionId;
12use crate::reveal::Part;
13
14/// A version as a legal read returns it, and whether its uuid is deleted.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Legal {
17    pub stored: Stored,
18    /// The uuid is deleted; otherwise it is live.
19    pub deleted: bool,
20}
21
22/// One kept version of a uuid, as the legal version list shows it.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct VersionInfo {
25    pub version: VersionId,
26    pub stored_at: OffsetDateTime,
27    /// When it was replaced, or its uuid deleted; None while current.
28    pub hidden_at: Option<OffsetDateTime>,
29    /// The uuid's current version.
30    pub current: bool,
31}
32
33/// What a legal call finds of a uuid.
34enum Standing {
35    Purged,
36    Absent,
37    Live(VersionId),
38    Deleted,
39}
40
41fn standing(tx: &mut Tx, uuid: Uuid) -> Result<Standing, StoreError> {
42    if tx.tombstoned(uuid)? {
43        return Ok(Standing::Purged);
44    }
45    match tx.vcon_row(uuid)? {
46        None => Ok(Standing::Absent),
47        Some(row) if row.deleted_at.is_some() => Ok(Standing::Deleted),
48        Some(row) => row.current.map(Standing::Live).ok_or(StoreError::Damaged),
49    }
50}
51
52/// The status a legal call records for `answer`, `ok` when it succeeded.
53fn status<T>(answer: &Result<T, StoreError>, ok: u16) -> u16 {
54    match answer {
55        Ok(_) => ok,
56        Err(StoreError::Gone) => 410,
57        Err(StoreError::NotFound) => 404,
58        Err(StoreError::NotDeleted) => 409,
59        Err(_) => 500,
60    }
61}
62
63/// The latest kept version of a deleted uuid. A deleted uuid left with no
64/// version is purged, with a tombstone, so a deleted row always keeps one.
65fn latest(tx: &mut Tx, uuid: Uuid) -> Result<VersionId, StoreError> {
66    tx.latest(uuid)?.ok_or(StoreError::Damaged)
67}
68
69impl Store {
70    /// Reads `version` of `uuid`, or with None its current version, or its
71    /// latest kept one when the uuid is deleted. A version purged, never
72    /// stored or of another uuid is NotFound; a purged uuid is Gone. The
73    /// whole read, object included, is one immediate transaction, so a
74    /// purge cannot remove what is being read. Each answer is recorded.
75    pub fn legal_get(
76        &self,
77        who: &Caller,
78        uuid: Uuid,
79        version: Option<VersionId>,
80    ) -> Result<Legal, StoreError> {
81        self.legal_read_as(who, uuid, version, Action::LegalRead)
82    }
83
84    /// Reads as [`Store::legal_get`] does, for a caller about to show
85    /// `part` of the version: the same answer, recorded under the legal
86    /// reveal action of that part.
87    pub fn legal_reveal(
88        &self,
89        who: &Caller,
90        uuid: Uuid,
91        version: Option<VersionId>,
92        part: Part,
93    ) -> Result<Legal, StoreError> {
94        self.legal_read_as(who, uuid, version, Action::LegalReveal(part))
95    }
96
97    /// The read behind `legal_get` and `legal_reveal`: the answer is
98    /// recorded as `action`.
99    fn legal_read_as(
100        &self,
101        who: &Caller,
102        uuid: Uuid,
103        version: Option<VersionId>,
104        action: Action,
105    ) -> Result<Legal, StoreError> {
106        let mut tx = self.catalog.immediate()?;
107        let answer = self.legal_read(&mut tx, uuid, version);
108        let entry = Entry {
109            actor: Actor::Key(who.key),
110            action,
111            target: Some(uuid.to_string()),
112            version: answer.as_ref().ok().map(|read| read.stored.version),
113            status: status(&answer, 200),
114        };
115        self.record(&mut tx, &entry)?;
116        commit(tx)?;
117        answer
118    }
119
120    fn legal_read(
121        &self,
122        tx: &mut Tx,
123        uuid: Uuid,
124        asked: Option<VersionId>,
125    ) -> Result<Legal, StoreError> {
126        let (current, deleted) = match standing(tx, uuid)? {
127            Standing::Purged => return Err(StoreError::Gone),
128            Standing::Absent => return Err(StoreError::NotFound),
129            Standing::Live(current) => (Some(current), false),
130            Standing::Deleted => (None, true),
131        };
132        let version = match (asked, current) {
133            (Some(asked), _) if tx.has_version(asked, uuid)? => asked,
134            (Some(_), _) => return Err(StoreError::NotFound),
135            (None, Some(current)) => current,
136            (None, None) => latest(tx, uuid)?,
137        };
138        let row = version_row(tx, version)?;
139        let body = self.open_version(uuid, version, &row)?;
140        Ok(Legal {
141            stored: Stored {
142                version,
143                form: row.form,
144                gzip: row.gzip,
145                body,
146            },
147            deleted,
148        })
149    }
150
151    /// Every kept version of `uuid`, oldest first, with its times. A purged
152    /// uuid is Gone and one never stored NotFound. Each answer is recorded.
153    pub fn legal_versions(&self, who: &Caller, uuid: Uuid) -> Result<Vec<VersionInfo>, StoreError> {
154        let mut tx = self.catalog.immediate()?;
155        let answer = versions(&mut tx, uuid);
156        let entry = Entry {
157            actor: Actor::Key(who.key),
158            action: Action::LegalVersions,
159            target: Some(uuid.to_string()),
160            version: None,
161            status: status(&answer, 200),
162        };
163        self.record(&mut tx, &entry)?;
164        commit(tx)?;
165        answer
166    }
167
168    /// Makes the latest kept version of a deleted `uuid` current again: its
169    /// hidden time and the uuid's deleted time are cleared, so no sweep
170    /// purges it. Older hidden versions stay hidden. A live uuid is
171    /// NotDeleted, a purged one Gone, one never stored NotFound. Recorded.
172    pub fn restore(&self, who: &Caller, uuid: Uuid) -> Result<VersionId, StoreError> {
173        let mut tx = self.catalog.immediate()?;
174        // The writes go in a part of their own, so a failure undoes them
175        // and still leaves the record.
176        let answer = in_part(&mut tx, |tx| restored(tx, uuid))?;
177        let entry = Entry {
178            actor: Actor::Key(who.key),
179            action: Action::Restore,
180            target: Some(uuid.to_string()),
181            version: answer.as_ref().ok().copied(),
182            status: status(&answer, 200),
183        };
184        self.record(&mut tx, &entry)?;
185        commit(tx)?;
186        answer
187    }
188
189    /// Turns the legal hold on `uuid` on or off. A held uuid is never
190    /// purged; a delete still hides it. A purged uuid is Gone, one never
191    /// stored NotFound. Recorded.
192    pub fn set_hold(&self, who: &Caller, uuid: Uuid, on: bool) -> Result<(), StoreError> {
193        let mut tx = self.catalog.immediate()?;
194        let answer = in_part(&mut tx, |tx| held(tx, uuid, on))?;
195        let entry = Entry {
196            actor: Actor::Key(who.key),
197            action: if on { Action::Hold } else { Action::Release },
198            target: Some(uuid.to_string()),
199            version: None,
200            status: status(&answer, 204),
201        };
202        self.record(&mut tx, &entry)?;
203        commit(tx)?;
204        answer
205    }
206}
207
208/// Runs `writes` in a part of `tx` of its own: kept if they succeed, undone
209/// if they fail. The outer error is the part's own failure; the inner one
210/// is `writes`'s answer.
211fn in_part<T>(
212    tx: &mut Tx,
213    writes: impl FnOnce(&mut Tx) -> Result<T, StoreError>,
214) -> Result<Result<T, StoreError>, StoreError> {
215    tx.begin_part()?;
216    let answer = writes(tx);
217    if answer.is_ok() {
218        tx.release_part()?;
219    } else {
220        tx.rollback_part()?;
221    }
222    Ok(answer)
223}
224
225fn restored(tx: &mut Tx, uuid: Uuid) -> Result<VersionId, StoreError> {
226    match standing(tx, uuid)? {
227        Standing::Purged => return Err(StoreError::Gone),
228        Standing::Absent => return Err(StoreError::NotFound),
229        Standing::Live(_) => return Err(StoreError::NotDeleted),
230        Standing::Deleted => {}
231    }
232    let version = latest(tx, uuid)?;
233    tx.unhide(version)?;
234    tx.undelete(uuid, version)?;
235    Ok(version)
236}
237
238fn held(tx: &mut Tx, uuid: Uuid, on: bool) -> Result<(), StoreError> {
239    match standing(tx, uuid)? {
240        Standing::Purged => Err(StoreError::Gone),
241        Standing::Absent => Err(StoreError::NotFound),
242        Standing::Live(_) | Standing::Deleted => tx.set_hold(uuid, on),
243    }
244}
245
246fn versions(tx: &mut Tx, uuid: Uuid) -> Result<Vec<VersionInfo>, StoreError> {
247    let current = match standing(tx, uuid)? {
248        Standing::Purged => return Err(StoreError::Gone),
249        Standing::Absent => return Err(StoreError::NotFound),
250        Standing::Live(current) => Some(current),
251        Standing::Deleted => None,
252    };
253    let time = |nanos: i64| from_nanos(nanos).ok_or(StoreError::Damaged);
254    tx.kept(uuid)?
255        .into_iter()
256        .map(|row| {
257            Ok(VersionInfo {
258                version: row.version,
259                stored_at: time(row.stored_at)?,
260                hidden_at: row.hidden_at.map(time).transpose()?,
261                current: Some(row.version) == current,
262            })
263        })
264        .collect()
265}
266
267#[cfg(test)]
268mod legal_tests {
269    use serde_json::Value;
270    use time::Duration;
271    use time::macros::datetime;
272    use uuid::Uuid;
273
274    use super::super::testing::vcon;
275    use super::super::tests::{Fixture, fixture};
276    use super::*;
277    use crate::clock::Clock;
278    use crate::fs::Fs;
279    use crate::ids::VersionId;
280    use crate::retention::Retention;
281    use crate::reveal::Part;
282    use crate::store::{Created, StoreError, Stored};
283
284    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
285    const OTHER: &str = "0199e5c6-0d7a-7c11-8000-000000000001";
286
287    /// Stores a vCon of `uuid` and returns its version and body.
288    fn stored(f: &Fixture, uuid: &str, subject: &str) -> (VersionId, Vec<u8>) {
289        let (found, body) = vcon(uuid, subject);
290        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
291            panic!("a new vCon")
292        };
293        (version, body)
294    }
295
296    /// Replaces the current version of `UUID` and returns the new one.
297    fn replaced(f: &Fixture, current: VersionId, subject: &str) -> (VersionId, Vec<u8>) {
298        let (found, body) = vcon(UUID, subject);
299        let version = f
300            .store
301            .replace(&f.caller, current, &found, &body)
302            .expect("replaced");
303        (version, body)
304    }
305
306    fn uuid() -> Uuid {
307        UUID.parse().expect("uuid")
308    }
309
310    fn later(f: &Fixture, by: Duration) {
311        f.clock.set(f.clock.now() + by);
312    }
313
314    /// The last record of `action`.
315    fn last(f: &Fixture, action: &str) -> Value {
316        f.store
317            .records()
318            .into_iter()
319            .rfind(|r| r["action"] == action)
320            .expect("a record")
321    }
322
323    #[test]
324    fn a_deleted_vcon_reads_back_byte_for_byte_and_says_it_is_deleted() {
325        let f = fixture();
326        let (version, body) = stored(&f, UUID, "first");
327        f.store
328            .delete(&f.caller, uuid(), Retention::Years(7))
329            .expect("deleted");
330
331        let read = f.store.legal_get(&f.caller, uuid(), None).expect("read");
332
333        assert_eq!(
334            read,
335            Legal {
336                stored: Stored {
337                    version,
338                    form: vcon::Form::Unsigned,
339                    gzip: false,
340                    body,
341                },
342                deleted: true,
343            }
344        );
345        let record = last(&f, "legal_read");
346        assert_eq!(record["status"], 200);
347        assert_eq!(record["target"], UUID);
348        assert_eq!(record["version"], version.to_string());
349    }
350
351    #[test]
352    fn a_deleted_vcon_reads_its_latest_kept_version() {
353        let f = fixture();
354        let (first, _) = stored(&f, UUID, "first");
355        later(&f, Duration::hours(1));
356        let (second, body) = replaced(&f, first, "second");
357        f.store
358            .delete(&f.caller, uuid(), Retention::Years(7))
359            .expect("deleted");
360
361        let read = f.store.legal_get(&f.caller, uuid(), None).expect("read");
362
363        assert_eq!((read.stored.version, read.stored.body), (second, body));
364    }
365
366    #[test]
367    fn a_live_vcon_reads_its_current_version() {
368        let f = fixture();
369        let (first, _) = stored(&f, UUID, "first");
370        let (second, body) = replaced(&f, first, "second");
371
372        let read = f.store.legal_get(&f.caller, uuid(), None).expect("read");
373
374        assert_eq!((read.stored.version, read.stored.body), (second, body));
375        assert!(!read.deleted);
376    }
377
378    #[test]
379    fn a_named_kept_version_reads_back_until_it_is_purged() {
380        let f = fixture();
381        let (first, body) = stored(&f, UUID, "first");
382        replaced(&f, first, "second");
383
384        let read = f
385            .store
386            .legal_get(&f.caller, uuid(), Some(first))
387            .expect("read");
388        assert_eq!((read.stored.version, read.stored.body), (first, body));
389        assert!(!read.deleted, "the uuid is live");
390
391        f.store.purge_due(Retention::Days(0)).expect("purged");
392        assert_eq!(
393            f.store.legal_get(&f.caller, uuid(), Some(first)),
394            Err(StoreError::NotFound)
395        );
396        assert_eq!(last(&f, "legal_read")["status"], 404);
397    }
398
399    #[test]
400    fn a_version_of_another_uuid_is_not_found() {
401        let f = fixture();
402        stored(&f, UUID, "first");
403        let (theirs, _) = stored(&f, OTHER, "other");
404
405        assert_eq!(
406            f.store.legal_get(&f.caller, uuid(), Some(theirs)),
407            Err(StoreError::NotFound)
408        );
409    }
410
411    #[test]
412    fn a_purged_uuid_is_gone_and_one_never_stored_is_not_found() {
413        let f = fixture();
414        stored(&f, UUID, "first");
415        f.store
416            .delete(&f.caller, uuid(), Retention::Days(0))
417            .expect("deleted and purged");
418
419        assert_eq!(
420            f.store.legal_get(&f.caller, uuid(), None),
421            Err(StoreError::Gone)
422        );
423        assert_eq!(last(&f, "legal_read")["status"], 410);
424        assert_eq!(
425            f.store.legal_versions(&f.caller, uuid()),
426            Err(StoreError::Gone)
427        );
428        assert_eq!(last(&f, "legal_versions")["status"], 410);
429
430        let never: Uuid = OTHER.parse().expect("uuid");
431        assert_eq!(
432            f.store.legal_get(&f.caller, never, None),
433            Err(StoreError::NotFound)
434        );
435        assert_eq!(
436            f.store.legal_versions(&f.caller, never),
437            Err(StoreError::NotFound)
438        );
439        assert_eq!(last(&f, "legal_versions")["status"], 404);
440    }
441
442    #[test]
443    fn the_version_list_gives_every_kept_version_with_its_times() {
444        let f = fixture();
445        let (first, _) = stored(&f, UUID, "first");
446        f.clock.set(datetime!(2026-10-23 13:00 UTC));
447        let (second, _) = replaced(&f, first, "second");
448
449        let live = f.store.legal_versions(&f.caller, uuid()).expect("list");
450        assert_eq!(
451            live,
452            [
453                VersionInfo {
454                    version: first,
455                    stored_at: datetime!(2026-10-23 12:00 UTC),
456                    hidden_at: Some(datetime!(2026-10-23 13:00 UTC)),
457                    current: false,
458                },
459                VersionInfo {
460                    version: second,
461                    stored_at: datetime!(2026-10-23 13:00 UTC),
462                    hidden_at: None,
463                    current: true,
464                },
465            ]
466        );
467        let record = last(&f, "legal_versions");
468        assert_eq!(
469            (record["status"].clone(), record["target"].clone()),
470            (200.into(), UUID.into())
471        );
472
473        f.clock.set(datetime!(2026-10-23 14:00 UTC));
474        f.store
475            .delete(&f.caller, uuid(), Retention::Years(7))
476            .expect("deleted");
477        let deleted = f.store.legal_versions(&f.caller, uuid()).expect("list");
478        assert_eq!(deleted.len(), 2);
479        assert_eq!(deleted[1].hidden_at, Some(datetime!(2026-10-23 14:00 UTC)));
480        assert!(deleted.iter().all(|v| !v.current), "nothing is current");
481    }
482
483    #[test]
484    fn a_damaged_kept_version_is_a_500_never_a_body() {
485        let f = fixture();
486        let (version, _) = stored(&f, UUID, "first");
487        f.store
488            .delete(&f.caller, uuid(), Retention::Years(7))
489            .expect("deleted");
490        let file = f.store.objects_dir.join(version.to_string());
491        let mut blob = f.fs.read(&file).expect("file");
492        let last_byte = blob.len() - 1;
493        blob[last_byte] ^= 1;
494        f.fs.remove(&file).expect("remove");
495        f.fs.write_new(&file, &blob).expect("write");
496
497        assert_eq!(
498            f.store.legal_get(&f.caller, uuid(), None),
499            Err(StoreError::Damaged)
500        );
501        assert_eq!(last(&f, "legal_read")["status"], 500);
502    }
503
504    #[test]
505    fn a_restored_vcon_is_current_again_and_a_sweep_leaves_it() {
506        let f = fixture();
507        let (first, _) = stored(&f, UUID, "first");
508        later(&f, Duration::hours(1));
509        let (second, body) = replaced(&f, first, "second");
510        f.store
511            .delete(&f.caller, uuid(), Retention::Years(7))
512            .expect("deleted");
513        later(&f, Duration::days(2));
514
515        assert_eq!(f.store.restore(&f.caller, uuid()), Ok(second));
516        let record = last(&f, "restore");
517        assert_eq!(record["status"], 200);
518        assert_eq!(record["version"], second.to_string());
519
520        let read = f.store.get(&f.caller, uuid()).expect("live again");
521        assert_eq!((read.version, read.body), (second, body));
522        f.store.purge_due(Retention::Days(1)).expect("swept");
523        assert_eq!(
524            f.store.get(&f.caller, uuid()).map(|s| s.version),
525            Ok(second),
526            "the sweep leaves it current"
527        );
528        let kept = f.store.legal_versions(&f.caller, uuid()).expect("list");
529        assert_eq!(
530            kept.iter().map(|v| v.version).collect::<Vec<_>>(),
531            [second],
532            "the older hidden version was due and is gone"
533        );
534    }
535
536    #[test]
537    fn restore_refuses_a_live_a_purged_and_a_never_stored_uuid() {
538        let f = fixture();
539        stored(&f, UUID, "first");
540        assert_eq!(
541            f.store.restore(&f.caller, uuid()),
542            Err(StoreError::NotDeleted)
543        );
544        assert_eq!(last(&f, "restore")["status"], 409);
545
546        f.store
547            .delete(&f.caller, uuid(), Retention::Days(0))
548            .expect("deleted and purged");
549        assert_eq!(f.store.restore(&f.caller, uuid()), Err(StoreError::Gone));
550        assert_eq!(last(&f, "restore")["status"], 410);
551
552        let never: Uuid = OTHER.parse().expect("uuid");
553        assert_eq!(f.store.restore(&f.caller, never), Err(StoreError::NotFound));
554        assert_eq!(last(&f, "restore")["status"], 404);
555    }
556
557    #[test]
558    fn a_hold_blocks_the_purge_until_it_is_released() {
559        let f = fixture();
560        stored(&f, UUID, "first");
561        assert_eq!(f.store.set_hold(&f.caller, uuid(), true), Ok(()));
562        assert_eq!(last(&f, "hold")["status"], 204);
563        f.store
564            .delete(&f.caller, uuid(), Retention::Days(0))
565            .expect("deleted, but held");
566        f.store.purge_due(Retention::Days(0)).expect("swept");
567        assert!(
568            f.store.legal_get(&f.caller, uuid(), None).is_ok(),
569            "held, so kept"
570        );
571
572        assert_eq!(f.store.set_hold(&f.caller, uuid(), false), Ok(()));
573        f.store.purge_due(Retention::Days(0)).expect("swept");
574        assert_eq!(
575            f.store.legal_get(&f.caller, uuid(), None),
576            Err(StoreError::Gone),
577            "released, so purged"
578        );
579    }
580
581    /// A release is recorded as a release, so the log tells it from a hold.
582    #[test]
583    fn a_release_is_recorded_as_release_not_as_hold() {
584        let f = fixture();
585        stored(&f, UUID, "first");
586        assert_eq!(f.store.set_hold(&f.caller, uuid(), true), Ok(()));
587        assert_eq!(f.store.set_hold(&f.caller, uuid(), false), Ok(()));
588        let actions: Vec<_> = f
589            .store
590            .records()
591            .into_iter()
592            .filter(|r| r["target"] == UUID)
593            .map(|r| r["action"].as_str().expect("an action").to_owned())
594            .collect();
595        assert_eq!(actions, ["create", "hold", "release"]);
596        assert_eq!(last(&f, "release")["status"], 204);
597        let never: Uuid = OTHER.parse().expect("uuid");
598        assert_eq!(
599            f.store.set_hold(&f.caller, never, false),
600            Err(StoreError::NotFound)
601        );
602        assert_eq!(last(&f, "release")["status"], 404, "a refused release too");
603    }
604
605    #[test]
606    fn a_hold_refuses_a_purged_and_a_never_stored_uuid() {
607        let f = fixture();
608        stored(&f, UUID, "first");
609        f.store
610            .delete(&f.caller, uuid(), Retention::Days(0))
611            .expect("deleted and purged");
612        assert_eq!(
613            f.store.set_hold(&f.caller, uuid(), true),
614            Err(StoreError::Gone)
615        );
616        assert_eq!(last(&f, "hold")["status"], 410);
617        let never: Uuid = OTHER.parse().expect("uuid");
618        assert_eq!(
619            f.store.set_hold(&f.caller, never, true),
620            Err(StoreError::NotFound)
621        );
622        assert_eq!(last(&f, "hold")["status"], 404);
623    }
624
625    #[test]
626    fn a_restore_that_fails_partway_changes_nothing_and_is_recorded() {
627        let f = fixture();
628        stored(&f, UUID, "first");
629        f.store
630            .delete(&f.caller, uuid(), Retention::Years(7))
631            .expect("deleted");
632        f.store
633            .conn()
634            .execute_batch(
635                "CREATE TEMP TRIGGER no_restore BEFORE UPDATE OF current ON vcon
636                 BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
637            )
638            .expect("trigger");
639
640        assert!(f.store.restore(&f.caller, uuid()).is_err());
641
642        assert_eq!(last(&f, "restore")["status"], 500);
643        let kept = f.store.legal_versions(&f.caller, uuid()).expect("list");
644        assert!(
645            kept.iter().all(|v| v.hidden_at.is_some()),
646            "the version written first is hidden again"
647        );
648    }
649
650    /// The last record: its action, status and version.
651    fn last_of_all(f: &Fixture) -> (String, Value, Value) {
652        let records = f.store.records();
653        let last = records.last().expect("a record");
654        (
655            last["action"].as_str().expect("an action").to_owned(),
656            last["status"].clone(),
657            last["version"].clone(),
658        )
659    }
660
661    #[test]
662    fn a_legal_reveal_reads_what_a_legal_read_does_and_is_recorded_under_its_part() {
663        let f = fixture();
664        let (version, _) = stored(&f, UUID, "first");
665        let read = f.store.legal_get(&f.caller, uuid(), None).expect("read");
666        for part in Part::ALL {
667            let revealed = f
668                .store
669                .legal_reveal(&f.caller, uuid(), None, part)
670                .expect("read");
671            assert_eq!(revealed, read, "{part:?}");
672            assert_eq!(
673                last_of_all(&f),
674                (
675                    format!("legal_reveal_{}", part.name()),
676                    200.into(),
677                    version.to_string().into()
678                ),
679                "{part:?}"
680            );
681        }
682    }
683
684    #[test]
685    fn a_legal_reveal_of_a_named_version_records_that_version() {
686        let f = fixture();
687        let (first, body) = stored(&f, UUID, "first");
688        replaced(&f, first, "second");
689        let revealed = f
690            .store
691            .legal_reveal(&f.caller, uuid(), Some(first), Part::Dialog)
692            .expect("read");
693        assert_eq!(
694            (revealed.stored.version, revealed.stored.body),
695            (first, body),
696            "the body"
697        );
698        assert_eq!(
699            last_of_all(&f),
700            (
701                "legal_reveal_dialog".to_owned(),
702                200.into(),
703                first.to_string().into()
704            ),
705            "the record"
706        );
707    }
708
709    #[test]
710    fn a_legal_reveal_of_a_deleted_vcon_reads_its_latest_kept_version() {
711        let f = fixture();
712        let (version, body) = stored(&f, UUID, "first");
713        f.store
714            .delete(&f.caller, uuid(), Retention::Years(7))
715            .expect("deleted");
716        let revealed = f
717            .store
718            .legal_reveal(&f.caller, uuid(), None, Part::Parties)
719            .expect("read");
720        assert!(revealed.deleted, "its state");
721        assert_eq!(revealed.stored.body, body, "the body");
722        assert_eq!(
723            last_of_all(&f),
724            (
725                "legal_reveal_parties".to_owned(),
726                200.into(),
727                version.to_string().into()
728            ),
729            "the record"
730        );
731    }
732
733    #[test]
734    fn a_legal_reveal_of_a_purged_uuid_is_gone_and_recorded_as_the_reveal() {
735        let f = fixture();
736        stored(&f, UUID, "first");
737        f.store
738            .delete(&f.caller, uuid(), Retention::Days(0))
739            .expect("deleted and purged");
740        assert_eq!(
741            f.store.legal_reveal(&f.caller, uuid(), None, Part::All),
742            Err(StoreError::Gone),
743            "the answer"
744        );
745        assert_eq!(
746            last_of_all(&f),
747            ("legal_reveal_all".to_owned(), 410.into(), Value::Null),
748            "the record"
749        );
750    }
751
752    #[test]
753    fn a_legal_reveal_of_a_version_of_another_uuid_is_not_found_and_recorded() {
754        let f = fixture();
755        stored(&f, UUID, "first");
756        let (theirs, _) = stored(&f, OTHER, "other");
757        assert_eq!(
758            f.store
759                .legal_reveal(&f.caller, uuid(), Some(theirs), Part::Links),
760            Err(StoreError::NotFound),
761            "the answer"
762        );
763        assert_eq!(
764            last_of_all(&f),
765            ("legal_reveal_links".to_owned(), 404.into(), Value::Null),
766            "the record"
767        );
768    }
769
770    #[test]
771    fn a_legal_reveal_of_a_uuid_never_stored_is_not_found_and_recorded() {
772        let f = fixture();
773        assert_eq!(
774            f.store
775                .legal_reveal(&f.caller, uuid(), None, Part::Analysis),
776            Err(StoreError::NotFound),
777            "the answer"
778        );
779        assert_eq!(
780            last_of_all(&f),
781            ("legal_reveal_analysis".to_owned(), 404.into(), Value::Null),
782            "the record"
783        );
784    }
785}