Skip to main content

vcon_server/tenants/
examine.rs

1//! What `check` reads of the registry: each tenant's Store examined under
2//! its own retention period, rotations left part way, and tenant removals
3//! since the master key was last rotated. Reading changes nothing.
4
5use time::OffsetDateTime;
6use time::format_description::well_known::Rfc3339;
7
8use super::{OpenFailure, TenantError, Tenants, io, stored_retention};
9use crate::audit::Action;
10use crate::clock::from_nanos;
11use crate::ids::TenantId;
12use crate::retention::Retention;
13use crate::store::{Examination, ExamineError};
14
15/// One tenant as `check` found it.
16#[derive(Debug)]
17pub struct TenantExamination {
18    pub id: TenantId,
19    pub name: String,
20    /// A key rotation of this tenant was stopped part way.
21    pub rotation_stopped: bool,
22    /// Its Store examined, or why it was not.
23    pub store: Result<Examination, Unexamined>,
24}
25
26/// Why a tenant's Store was not examined: it did not open, or it opened
27/// and the examination failed, as when the objects cannot be read.
28#[derive(Debug)]
29pub enum Unexamined {
30    /// The Store did not open.
31    Open(OpenFailure),
32    /// The Store opened, and examining it failed.
33    Examine(ExamineError),
34}
35
36/// The registry as `check` found it.
37#[derive(Debug)]
38pub struct RegistryExamination {
39    pub tenants: Vec<TenantExamination>,
40    /// Tenants removed since the master key was last rotated: their keys
41    /// are destroyed only by the next rotation.
42    pub removed_since_master: u64,
43    /// When the oldest of those removals was made.
44    pub oldest_removed_since_master: Option<OffsetDateTime>,
45}
46
47/// Whether every tenant's data is under its current key, as `serve`
48/// requires before it starts: counts of tenants only, never which, and no
49/// path, since a path names a tenant.
50#[derive(Debug, Clone, PartialEq, Eq, Default)]
51pub struct KeyOrder {
52    /// Tenants whose key does not unwrap under the master key.
53    pub wrapped_elsewhere: u64,
54    /// Tenants with a key rotation stopped part way.
55    pub rotations_stopped: u64,
56    /// Tenants whose catalog does not open under their key, or with a
57    /// version row naming another key.
58    pub data_under_other_keys: u64,
59    /// Tenants whose Store did not open for a reason other than its key,
60    /// such as files this process may not use.
61    pub catalogs_unopened: u64,
62    /// The system's error for the first of those that has one, such as
63    /// `Permission denied (os error 13)`.
64    pub unopened_error: Option<String>,
65}
66
67impl KeyOrder {
68    pub fn is_sound(&self) -> bool {
69        *self == KeyOrder::default()
70    }
71}
72
73/// Work that only a key rotation finishes: purges since each tenant key's
74/// rotation, and tenant removals since the master key's. Read from the
75/// audit logs only.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub struct RotationBacklog {
78    pub tenants_with_purges: u64,
79    pub purges: u64,
80    pub oldest_purge: Option<OffsetDateTime>,
81    pub removals: u64,
82    pub oldest_removal: Option<OffsetDateTime>,
83}
84
85impl Tenants {
86    /// Counts the tenants whose data is not all under their current key.
87    pub fn key_order(&self) -> Result<KeyOrder, TenantError> {
88        let rows = self.registry.snapshot()?.tenants()?;
89        let mut order = KeyOrder::default();
90        for row in rows {
91            let (id, wrapped, pending) = (row.id, row.wrapped, row.pending.is_some());
92            if self.wrap.unwrap(id, &wrapped).is_err() {
93                order.wrapped_elsewhere += 1;
94                continue;
95            }
96            if pending {
97                order.rotations_stopped += 1;
98            }
99            let elsewhere = match self.store_or_why(id) {
100                Ok(store) => store.rows_under_other_keys().map_err(io)? > 0,
101                Err(OpenFailure::WrongKey) => true,
102                Err(failure) => {
103                    order.catalogs_unopened += 1;
104                    if let OpenFailure::Access { error, .. } = failure {
105                        order.unopened_error.get_or_insert(error.to_string());
106                    }
107                    false
108                }
109            };
110            if elsewhere {
111                order.data_under_other_keys += 1;
112            }
113        }
114        Ok(order)
115    }
116
117    /// How many tenants have a version packed into a pack file: with any,
118    /// `serve` needs `[storage.parquet]`.
119    pub fn tenants_with_packed_versions(&self) -> Result<u64, TenantError> {
120        let rows = self.registry.snapshot()?.tenants()?;
121        let mut count = 0;
122        for row in rows {
123            if self.store(row.id)?.packed_versions().map_err(io)? > 0 {
124                count += 1;
125            }
126        }
127        Ok(count)
128    }
129
130    /// The rotation backlog: purges per tenant since its key's rotation,
131    /// and removals since the master key's.
132    pub fn rotation_backlog(&self) -> Result<RotationBacklog, TenantError> {
133        let rows = self.registry.snapshot()?.tenants()?;
134        let mut backlog = RotationBacklog::default();
135        for row in rows {
136            let key_since = from_nanos(row.key_since).ok_or(TenantError::Io)?;
137            let (purges, oldest) = self.store(row.id)?.purges_since(key_since).map_err(io)?;
138            if purges > 0 {
139                backlog.tenants_with_purges += 1;
140                backlog.purges += purges;
141                backlog.oldest_purge = earliest(backlog.oldest_purge, oldest);
142            }
143        }
144        (backlog.removals, backlog.oldest_removal) = self.removals_since_master()?;
145        Ok(backlog)
146    }
147
148    /// Tenant removals since the master key's rotation, and the oldest.
149    fn removals_since_master(&self) -> Result<(u64, Option<OffsetDateTime>), TenantError> {
150        let (since, removals) = {
151            let mut tx = self.registry.snapshot()?;
152            let since = tx.master_since(self.wrap.key_id())?;
153            let removals = tx.record_times(Action::TenantRemove, 204)?;
154            (since, removals)
155        };
156        let since = since
157            .map(|s| from_nanos(s).ok_or(TenantError::Io))
158            .transpose()?;
159        let (mut count, mut oldest) = (0, None);
160        for at in removals {
161            let at = OffsetDateTime::parse(&at, &Rfc3339).map_err(io)?;
162            if since.is_none_or(|since| at >= since) {
163                count += 1;
164                oldest = earliest(oldest, Some(at));
165            }
166        }
167        Ok((count, oldest))
168    }
169
170    /// Examines every tenant at `now`, under its own retention period or
171    /// `default`.
172    pub fn examine(
173        &self,
174        default: Retention,
175        now: OffsetDateTime,
176    ) -> Result<RegistryExamination, TenantError> {
177        let rows = self.registry.snapshot()?.tenants()?;
178        let time = |nanos| from_nanos(nanos).ok_or(TenantError::Io);
179        let mut tenants = Vec::new();
180        for row in rows {
181            let (id, name, retention, key_since) = (row.id, row.name, row.retention, row.key_since);
182            let rotation_stopped = row.pending.is_some();
183            let retention = super::kept_for(stored_retention(retention)?, default);
184            let key_since = time(key_since)?;
185            let store = self
186                .store_or_why(id)
187                .map_err(Unexamined::Open)
188                .and_then(|store| {
189                    store
190                        .examine(retention, key_since, now)
191                        .map_err(Unexamined::Examine)
192                });
193            tenants.push(TenantExamination {
194                id,
195                name,
196                rotation_stopped,
197                store,
198            });
199        }
200        let (removed_since_master, oldest_removed_since_master) = self.removals_since_master()?;
201        let found = RegistryExamination {
202            tenants,
203            removed_since_master,
204            oldest_removed_since_master,
205        };
206        Ok(found)
207    }
208}
209
210/// The earlier of two times, either of which may be absent.
211fn earliest(a: Option<OffsetDateTime>, b: Option<OffsetDateTime>) -> Option<OffsetDateTime> {
212    match (a, b) {
213        (Some(a), Some(b)) => Some(a.min(b)),
214        (a, b) => a.or(b),
215    }
216}
217
218#[cfg(test)]
219mod examine_tests {
220    use time::macros::datetime;
221
222    use super::super::tests::fixture;
223    use super::*;
224    use crate::audit::Actor;
225    use crate::store::Caller;
226    use crate::store::testing::vcon;
227
228    const CALLER: Caller = Caller {
229        key: crate::ids::KeyId([7; 8]),
230    };
231
232    #[test]
233    fn each_tenant_is_examined_under_its_own_period_or_the_default() {
234        let f = fixture();
235        let own = f
236            .tenants
237            .create(Actor::Cli, "own", Some(Retention::Days(1)))
238            .expect("made");
239        let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
240        for id in [own, default] {
241            let store = f.tenants.store(id).expect("store");
242            let (found, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc46", "kept");
243            store.create(&CALLER, &found, &body).expect("stored");
244            store
245                .delete(&CALLER, found.uuid, Retention::Years(7))
246                .expect("deleted");
247        }
248        let found = f
249            .tenants
250            .examine(Retention::Years(7), datetime!(2026-10-30 12:00 UTC))
251            .expect("examined");
252        let by_name = |name: &str| found.tenants.iter().find(|t| t.name == name).expect(name);
253        let own = by_name("own");
254        assert_eq!(
255            own.store.as_ref().expect("opens").due,
256            1,
257            "a day has passed"
258        );
259        assert!(!own.rotation_stopped);
260        assert_eq!(by_name("default").store.as_ref().expect("opens").due, 0);
261        assert_eq!(found.tenants.len(), 2);
262    }
263
264    #[test]
265    fn a_rotation_stopped_part_way_is_reported_and_a_catalog_that_does_not_open_too() {
266        let f = fixture();
267        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
268        *f.tenants.hooks.rekey_stop.lock().expect("hook") =
269            Some(super::super::rekey::RekeyStep::Reencrypted);
270        assert_eq!(f.tenants.rekey_tenant(Actor::Cli, id), Err(TenantError::Io));
271        let found = f
272            .tenants
273            .examine(Retention::Years(7), datetime!(2026-10-23 12:00 UTC))
274            .expect("examined");
275        let acme = &found.tenants[0];
276        assert!(acme.rotation_stopped);
277        assert!(
278            matches!(acme.store, Err(Unexamined::Open(OpenFailure::WrongKey))),
279            "its catalog is under the pending key: {:?}",
280            acme.store
281        );
282    }
283
284    /// A tenant's files this process may not write, such as ones a command
285    /// run as root left, are reported as that, with the path and the
286    /// system's error; only a key that does not open the catalog is a key
287    /// problem.
288    #[test]
289    fn a_catalog_the_process_may_not_open_is_an_access_failure_not_a_key_one() {
290        use std::os::unix::fs::PermissionsExt;
291        let f = fixture();
292        // Made, but not yet opened through the registry, as at start-up.
293        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
294        let dir = f.dir.path().join("tenants").join(id.to_string());
295        let mode =
296            |m| std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(m)).expect("chmod");
297        mode(0o500);
298        let order = f.tenants.key_order();
299        let found = f
300            .tenants
301            .examine(Retention::Years(7), datetime!(2026-10-23 12:00 UTC));
302        mode(0o700);
303        let order = order.expect("read");
304        assert_eq!(order.data_under_other_keys, 0, "{order:?}");
305        assert_eq!(order.catalogs_unopened, 1, "{order:?}");
306        assert_eq!(
307            order.unopened_error.as_deref(),
308            Some("Permission denied (os error 13)")
309        );
310        assert!(!order.is_sound());
311        match &found.expect("examined").tenants[0].store {
312            Err(Unexamined::Open(OpenFailure::Access { path, error })) => {
313                assert_eq!(path, &dir);
314                assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
315            }
316            other => panic!("{other:?}"),
317        }
318        assert!(
319            f.tenants.key_order().expect("read").is_sound(),
320            "once allowed"
321        );
322    }
323
324    /// The tenants with a version whose catalog row names a pack file, as
325    /// a pack run leaves them: counted per tenant, not per version, and
326    /// none while every version is in its object.
327    #[test]
328    fn tenants_with_packed_versions_are_counted() {
329        let f = fixture();
330        let mut ids = Vec::new();
331        for name in ["acme", "beta", "gamma"] {
332            let id = f.tenants.create(Actor::Cli, name, None).expect("made");
333            let store = f.tenants.store(id).expect("store");
334            for n in 0..2 {
335                let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc4{n}"), "k");
336                store.create(&CALLER, &found, &body).expect("stored");
337            }
338            ids.push(id);
339        }
340        assert_eq!(
341            f.tenants.tenants_with_packed_versions(),
342            Ok(0),
343            "every version in its object"
344        );
345        // Both versions of the first tenant, and one of the second.
346        for (id, limit) in [(ids[0], 2_i64), (ids[1], 1)] {
347            let store = f.tenants.store(id).expect("store");
348            let changed = store
349                .conn_for_test()
350                .execute(
351                    "UPDATE version SET place_file = randomblob(16), place_group = 0, place_row = 0
352                     WHERE version IN (SELECT version FROM version ORDER BY version LIMIT ?1)",
353                    [limit],
354                )
355                .expect("placed in a pack file");
356            assert_eq!(i64::try_from(changed), Ok(limit), "placed");
357        }
358        assert_eq!(
359            f.tenants.tenants_with_packed_versions(),
360            Ok(2),
361            "two tenants, one with a single packed version"
362        );
363    }
364
365    mod key_order {
366        use super::*;
367        use crate::envelope::{self, Context, Key};
368        use crate::tenants::rekey::RekeyStep;
369
370        fn with_vcons(f: &super::super::super::tests::Fixture) -> TenantId {
371            let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
372            let store = f.tenants.store(id).expect("store");
373            for n in 0..3 {
374                let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc4{n}"), "k");
375                store.create(&CALLER, &found, &body).expect("stored");
376            }
377            id
378        }
379
380        #[test]
381        fn a_sound_registry_is_in_order() {
382            let f = fixture();
383            with_vcons(&f);
384            assert!(f.tenants.key_order().expect("read").is_sound());
385        }
386
387        #[test]
388        fn a_rotation_stopped_at_any_step_is_out_of_order() {
389            for (step, data) in [
390                (RekeyStep::Pending, 0),
391                (RekeyStep::Batch, 1),
392                (RekeyStep::Rewrapped, 1),
393                (RekeyStep::Reencrypted, 1),
394            ] {
395                let f = fixture();
396                let id = with_vcons(&f);
397                *f.tenants.hooks.rekey_stop.lock().expect("hook") = Some(step);
398                assert!(f.tenants.rekey_in_batches(Actor::Cli, id, 2).is_err());
399                assert_eq!(
400                    f.tenants.key_order().expect("read"),
401                    KeyOrder {
402                        wrapped_elsewhere: 0,
403                        rotations_stopped: 1,
404                        data_under_other_keys: data,
405                        ..KeyOrder::default()
406                    },
407                    "{step:?}"
408                );
409                f.tenants.rekey_tenant(Actor::Cli, id).expect("finished");
410                assert!(f.tenants.key_order().expect("read").is_sound(), "{step:?}");
411            }
412        }
413
414        #[test]
415        fn a_tenant_key_wrapped_under_another_key_is_out_of_order() {
416            let f = fixture();
417            let id = with_vcons(&f);
418            let other = Key::generate().expect("key");
419            let foreign =
420                envelope::wrap(&other, &Context::Tenant { tenant: id }, &f.tenant_key(id));
421            f.conn()
422                .execute(
423                    "UPDATE tenant SET wrapped_tenant_key = ?1 WHERE id = ?2",
424                    rusqlite::params![foreign, id.0],
425                )
426                .expect("rewritten");
427            f.tenants.close(id);
428            assert_eq!(f.tenants.key_order().expect("read").wrapped_elsewhere, 1);
429        }
430    }
431
432    #[test]
433    fn the_rotation_backlog_counts_purges_and_removals_from_the_logs() {
434        let f = fixture();
435        let purging = f
436            .tenants
437            .create(Actor::Cli, "purging", Some(Retention::Days(0)))
438            .expect("made");
439        f.tenants.create(Actor::Cli, "quiet", None).expect("made");
440        let gone = f.tenants.create(Actor::Cli, "gone", None).expect("made");
441        let store = f.tenants.store(purging).expect("store");
442        for (n, at) in [
443            (0, datetime!(2026-10-24 10:00 UTC)),
444            (1, datetime!(2026-10-24 11:00 UTC)),
445        ] {
446            f.clock.set(at);
447            let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc4{n}"), "k");
448            store.create(&CALLER, &found, &body).expect("stored");
449            store
450                .delete(&CALLER, found.uuid, Retention::Days(0))
451                .expect("deleted and purged");
452        }
453        drop(store);
454        f.clock.set(datetime!(2026-10-24 12:00 UTC));
455        f.tenants
456            .remove(Actor::Cli, gone, crate::tenants::Removal::Empty)
457            .expect("removed");
458        assert_eq!(
459            f.tenants.rotation_backlog().expect("read"),
460            RotationBacklog {
461                tenants_with_purges: 1,
462                purges: 2,
463                oldest_purge: Some(datetime!(2026-10-24 10:00 UTC)),
464                removals: 1,
465                oldest_removal: Some(datetime!(2026-10-24 12:00 UTC)),
466            }
467        );
468    }
469
470    #[test]
471    fn removals_since_the_master_key_was_rotated_are_counted() {
472        let f = fixture();
473        let gone = f.tenants.create(Actor::Cli, "gone", None).expect("made");
474        f.tenants.create(Actor::Cli, "kept", None).expect("made");
475        f.clock.set(datetime!(2026-10-24 08:00 UTC));
476        f.tenants
477            .remove(Actor::Cli, gone, crate::tenants::Removal::Empty)
478            .expect("removed");
479        // A removal from before the master key's rotation, and a refused one.
480        f.conn()
481            .execute_batch(
482                "INSERT INTO audit (at, actor, action, target, version, status, count)
483                 VALUES ('2026-10-01T00:00:00Z', 'cli', 'tenant_remove', NULL, NULL, 204, 1),
484                        ('2026-10-24T09:00:00Z', 'cli', 'tenant_remove', NULL, NULL, 409, 1);",
485            )
486            .expect("older records");
487        let found = f
488            .tenants
489            .examine(Retention::Years(7), datetime!(2026-10-25 12:00 UTC))
490            .expect("examined");
491        assert_eq!(found.removed_since_master, 1);
492        assert_eq!(
493            found.oldest_removed_since_master,
494            Some(datetime!(2026-10-24 08:00 UTC))
495        );
496        assert_eq!(found.tenants.len(), 1);
497    }
498}