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