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    /// Sets how many tenant keys [`Tenants::key_order`] unwraps at once
87    /// (`key_wrap.start_parallel`); 0 is taken as 1.
88    pub fn set_start_parallel(&self, n: usize) {
89        self.start_parallel
90            .store(n.max(1), std::sync::atomic::Ordering::Relaxed);
91    }
92
93    /// How many tenant keys [`Tenants::key_order`] unwraps at once.
94    #[must_use]
95    pub fn start_parallel(&self) -> usize {
96        self.start_parallel
97            .load(std::sync::atomic::Ordering::Relaxed)
98    }
99
100    /// Counts the tenants whose data is not all under their current key.
101    pub fn key_order(&self) -> Result<KeyOrder, TenantError> {
102        let rows = self.registry.snapshot()?.tenants()?;
103        let opens = self.unwrap_all(&rows);
104        let mut order = KeyOrder::default();
105        for (row, opens) in rows.into_iter().zip(opens) {
106            let (id, pending) = (row.id, row.pending.is_some());
107            if !opens {
108                order.wrapped_elsewhere += 1;
109                continue;
110            }
111            if pending {
112                order.rotations_stopped += 1;
113            }
114            let elsewhere = match self.store_or_why(id) {
115                Ok(store) => store.rows_under_other_keys().map_err(io)? > 0,
116                Err(OpenFailure::WrongKey) => true,
117                Err(failure) => {
118                    order.catalogs_unopened += 1;
119                    if let OpenFailure::Access { error, .. } = failure {
120                        order.unopened_error.get_or_insert(error.to_string());
121                    }
122                    false
123                }
124            };
125            if elsewhere {
126                order.data_under_other_keys += 1;
127            }
128        }
129        Ok(order)
130    }
131
132    /// Whether each row's tenant key unwraps, in the rows' order, with at
133    /// most `start_parallel` unwraps in flight: each worker takes the next
134    /// row until none is left.
135    fn unwrap_all(&self, rows: &[crate::backend::TenantRow]) -> Vec<bool> {
136        let next = std::sync::atomic::AtomicUsize::new(0);
137        let opens: Vec<std::sync::atomic::AtomicBool> = rows
138            .iter()
139            .map(|_| std::sync::atomic::AtomicBool::new(false))
140            .collect();
141        let workers = self.start_parallel().min(rows.len());
142        let wrap = &*self.wrap;
143        std::thread::scope(|scope| {
144            for _ in 0..workers {
145                scope.spawn(|| {
146                    loop {
147                        let at = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
148                        let Some(row) = rows.get(at) else { break };
149                        let ok = wrap.unwrap(row.id, &row.wrapped, row.kek.as_ref()).is_ok();
150                        opens[at].store(ok, std::sync::atomic::Ordering::Relaxed);
151                    }
152                });
153            }
154        });
155        opens
156            .into_iter()
157            .map(std::sync::atomic::AtomicBool::into_inner)
158            .collect()
159    }
160
161    /// How many tenants have a version packed into a pack file: with any,
162    /// `serve` needs `[storage.parquet]`.
163    pub fn tenants_with_packed_versions(&self) -> Result<u64, TenantError> {
164        let rows = self.registry.snapshot()?.tenants()?;
165        let mut count = 0;
166        for row in rows {
167            if self.store(row.id)?.packed_versions().map_err(io)? > 0 {
168                count += 1;
169            }
170        }
171        Ok(count)
172    }
173
174    /// The rotation backlog: purges per tenant since its key's rotation,
175    /// and removals since the master key's.
176    pub fn rotation_backlog(&self) -> Result<RotationBacklog, TenantError> {
177        let rows = self.registry.snapshot()?.tenants()?;
178        let mut backlog = RotationBacklog::default();
179        for row in rows {
180            let key_since = from_nanos(row.key_since).ok_or(TenantError::Io)?;
181            let (purges, oldest) = self.store(row.id)?.purges_since(key_since).map_err(io)?;
182            if purges > 0 {
183                backlog.tenants_with_purges += 1;
184                backlog.purges += purges;
185                backlog.oldest_purge = earliest(backlog.oldest_purge, oldest);
186            }
187        }
188        (backlog.removals, backlog.oldest_removal) = self.removals_since_master()?;
189        Ok(backlog)
190    }
191
192    /// Tenant removals since the master key's rotation, and the oldest.
193    fn removals_since_master(&self) -> Result<(u64, Option<OffsetDateTime>), TenantError> {
194        let (since, removals) = {
195            let mut tx = self.registry.snapshot()?;
196            let since = tx.master_since(self.wrap.key_id())?;
197            let removals = tx.record_times(Action::TenantRemove, 204)?;
198            (since, removals)
199        };
200        let since = since
201            .map(|s| from_nanos(s).ok_or(TenantError::Io))
202            .transpose()?;
203        let (mut count, mut oldest) = (0, None);
204        for at in removals {
205            let at = OffsetDateTime::parse(&at, &Rfc3339).map_err(io)?;
206            if since.is_none_or(|since| at >= since) {
207                count += 1;
208                oldest = earliest(oldest, Some(at));
209            }
210        }
211        Ok((count, oldest))
212    }
213
214    /// Examines every tenant at `now`, under its own retention period or
215    /// `default`.
216    pub fn examine(
217        &self,
218        default: Retention,
219        now: OffsetDateTime,
220    ) -> Result<RegistryExamination, TenantError> {
221        let rows = self.registry.snapshot()?.tenants()?;
222        let time = |nanos| from_nanos(nanos).ok_or(TenantError::Io);
223        let mut tenants = Vec::new();
224        for row in rows {
225            let (id, name, retention, key_since) = (row.id, row.name, row.retention, row.key_since);
226            let rotation_stopped = row.pending.is_some();
227            let retention = super::kept_for(stored_retention(retention)?, default);
228            let key_since = time(key_since)?;
229            let store = self
230                .store_or_why(id)
231                .map_err(Unexamined::Open)
232                .and_then(|store| {
233                    store
234                        .examine(retention, key_since, now)
235                        .map_err(Unexamined::Examine)
236                });
237            tenants.push(TenantExamination {
238                id,
239                name,
240                rotation_stopped,
241                store,
242            });
243        }
244        let (removed_since_master, oldest_removed_since_master) = self.removals_since_master()?;
245        let found = RegistryExamination {
246            tenants,
247            removed_since_master,
248            oldest_removed_since_master,
249        };
250        Ok(found)
251    }
252}
253
254/// The earlier of two times, either of which may be absent.
255fn earliest(a: Option<OffsetDateTime>, b: Option<OffsetDateTime>) -> Option<OffsetDateTime> {
256    match (a, b) {
257        (Some(a), Some(b)) => Some(a.min(b)),
258        (a, b) => a.or(b),
259    }
260}
261
262#[cfg(test)]
263mod examine_tests {
264    use time::macros::datetime;
265
266    use super::super::tests::fixture;
267    use super::*;
268    use crate::audit::Actor;
269    use crate::store::Caller;
270    use crate::store::testing::vcon;
271
272    const CALLER: Caller = Caller {
273        key: crate::ids::KeyId([7; 8]),
274    };
275
276    #[test]
277    fn each_tenant_is_examined_under_its_own_period_or_the_default() {
278        let f = fixture();
279        let own = f
280            .tenants
281            .create(Actor::Cli, "own", Some(Retention::Days(1)))
282            .expect("made");
283        let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
284        for id in [own, default] {
285            let store = f.tenants.store(id).expect("store");
286            let (found, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc46", "kept");
287            store.create(&CALLER, &found, &body).expect("stored");
288            store
289                .delete(&CALLER, found.uuid, Retention::Years(7))
290                .expect("deleted");
291        }
292        let found = f
293            .tenants
294            .examine(Retention::Years(7), datetime!(2026-10-30 12:00 UTC))
295            .expect("examined");
296        let by_name = |name: &str| found.tenants.iter().find(|t| t.name == name).expect(name);
297        let own = by_name("own");
298        assert_eq!(
299            own.store.as_ref().expect("opens").due,
300            1,
301            "a day has passed"
302        );
303        assert!(!own.rotation_stopped);
304        assert_eq!(by_name("default").store.as_ref().expect("opens").due, 0);
305        assert_eq!(found.tenants.len(), 2);
306    }
307
308    #[test]
309    fn a_rotation_stopped_part_way_is_reported_and_a_catalog_that_does_not_open_too() {
310        let f = fixture();
311        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
312        *f.tenants.hooks.rekey_stop.lock().expect("hook") =
313            Some(super::super::rekey::RekeyStep::Reencrypted);
314        assert_eq!(f.tenants.rekey_tenant(Actor::Cli, id), Err(TenantError::Io));
315        let found = f
316            .tenants
317            .examine(Retention::Years(7), datetime!(2026-10-23 12:00 UTC))
318            .expect("examined");
319        let acme = &found.tenants[0];
320        assert!(acme.rotation_stopped);
321        assert!(
322            matches!(acme.store, Err(Unexamined::Open(OpenFailure::WrongKey))),
323            "its catalog is under the pending key: {:?}",
324            acme.store
325        );
326    }
327
328    /// A tenant's files this process may not write, such as ones a command
329    /// run as root left, are reported as that, with the path and the
330    /// system's error; only a key that does not open the catalog is a key
331    /// problem.
332    #[test]
333    fn a_catalog_the_process_may_not_open_is_an_access_failure_not_a_key_one() {
334        use std::os::unix::fs::PermissionsExt;
335        let f = fixture();
336        // Made, but not yet opened through the registry, as at start-up.
337        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
338        let dir = f.dir.path().join("tenants").join(id.to_string());
339        let mode =
340            |m| std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(m)).expect("chmod");
341        mode(0o500);
342        let order = f.tenants.key_order();
343        let found = f
344            .tenants
345            .examine(Retention::Years(7), datetime!(2026-10-23 12:00 UTC));
346        mode(0o700);
347        let order = order.expect("read");
348        assert_eq!(order.data_under_other_keys, 0, "{order:?}");
349        assert_eq!(order.catalogs_unopened, 1, "{order:?}");
350        assert_eq!(
351            order.unopened_error.as_deref(),
352            Some("Permission denied (os error 13)")
353        );
354        assert!(!order.is_sound());
355        match &found.expect("examined").tenants[0].store {
356            Err(Unexamined::Open(OpenFailure::Access { path, error })) => {
357                assert_eq!(path, &dir);
358                assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
359            }
360            other => panic!("{other:?}"),
361        }
362        assert!(
363            f.tenants.key_order().expect("read").is_sound(),
364            "once allowed"
365        );
366    }
367
368    /// The tenants with a version whose catalog row names a pack file, as
369    /// a pack run leaves them: counted per tenant, not per version, and
370    /// none while every version is in its object.
371    #[test]
372    fn tenants_with_packed_versions_are_counted() {
373        let f = fixture();
374        let mut ids = Vec::new();
375        for name in ["acme", "beta", "gamma"] {
376            let id = f.tenants.create(Actor::Cli, name, None).expect("made");
377            let store = f.tenants.store(id).expect("store");
378            for n in 0..2 {
379                let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc4{n}"), "k");
380                store.create(&CALLER, &found, &body).expect("stored");
381            }
382            ids.push(id);
383        }
384        assert_eq!(
385            f.tenants.tenants_with_packed_versions(),
386            Ok(0),
387            "every version in its object"
388        );
389        // Both versions of the first tenant, and one of the second.
390        for (id, limit) in [(ids[0], 2_i64), (ids[1], 1)] {
391            let store = f.tenants.store(id).expect("store");
392            let changed = store
393                .conn_for_test()
394                .execute(
395                    "UPDATE version SET place_file = randomblob(16), place_group = 0, place_row = 0
396                     WHERE version IN (SELECT version FROM version ORDER BY version LIMIT ?1)",
397                    [limit],
398                )
399                .expect("placed in a pack file");
400            assert_eq!(i64::try_from(changed), Ok(limit), "placed");
401        }
402        assert_eq!(
403            f.tenants.tenants_with_packed_versions(),
404            Ok(2),
405            "two tenants, one with a single packed version"
406        );
407    }
408
409    mod key_order {
410        use super::*;
411        use crate::envelope::{self, Context, Key};
412        use crate::tenants::rekey::RekeyStep;
413
414        fn with_vcons(f: &super::super::super::tests::Fixture) -> TenantId {
415            let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
416            let store = f.tenants.store(id).expect("store");
417            for n in 0..3 {
418                let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc4{n}"), "k");
419                store.create(&CALLER, &found, &body).expect("stored");
420            }
421            id
422        }
423
424        #[test]
425        fn a_sound_registry_is_in_order() {
426            let f = fixture();
427            with_vcons(&f);
428            assert!(f.tenants.key_order().expect("read").is_sound());
429        }
430
431        #[test]
432        fn a_rotation_stopped_at_any_step_is_out_of_order() {
433            for (step, data) in [
434                (RekeyStep::Pending, 0),
435                (RekeyStep::Batch, 1),
436                (RekeyStep::Rewrapped, 1),
437                (RekeyStep::Reencrypted, 1),
438            ] {
439                let f = fixture();
440                let id = with_vcons(&f);
441                *f.tenants.hooks.rekey_stop.lock().expect("hook") = Some(step);
442                assert!(f.tenants.rekey_in_batches(Actor::Cli, id, 2).is_err());
443                assert_eq!(
444                    f.tenants.key_order().expect("read"),
445                    KeyOrder {
446                        wrapped_elsewhere: 0,
447                        rotations_stopped: 1,
448                        data_under_other_keys: data,
449                        ..KeyOrder::default()
450                    },
451                    "{step:?}"
452                );
453                f.tenants.rekey_tenant(Actor::Cli, id).expect("finished");
454                assert!(f.tenants.key_order().expect("read").is_sound(), "{step:?}");
455            }
456        }
457
458        #[test]
459        fn a_tenant_key_wrapped_under_another_key_is_out_of_order() {
460            let f = fixture();
461            let id = with_vcons(&f);
462            let other = Key::generate().expect("key");
463            let foreign =
464                envelope::wrap(&other, &Context::Tenant { tenant: id }, &f.tenant_key(id));
465            f.conn()
466                .execute(
467                    "UPDATE tenant SET wrapped_tenant_key = ?1 WHERE id = ?2",
468                    rusqlite::params![foreign, id.0],
469                )
470                .expect("rewritten");
471            f.tenants.close(id);
472            assert_eq!(f.tenants.key_order().expect("read").wrapped_elsewhere, 1);
473        }
474    }
475
476    #[test]
477    fn the_rotation_backlog_counts_purges_and_removals_from_the_logs() {
478        let f = fixture();
479        let purging = f
480            .tenants
481            .create(Actor::Cli, "purging", Some(Retention::Days(0)))
482            .expect("made");
483        f.tenants.create(Actor::Cli, "quiet", None).expect("made");
484        let gone = f.tenants.create(Actor::Cli, "gone", None).expect("made");
485        let store = f.tenants.store(purging).expect("store");
486        for (n, at) in [
487            (0, datetime!(2026-10-24 10:00 UTC)),
488            (1, datetime!(2026-10-24 11:00 UTC)),
489        ] {
490            f.clock.set(at);
491            let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc4{n}"), "k");
492            store.create(&CALLER, &found, &body).expect("stored");
493            store
494                .delete(&CALLER, found.uuid, Retention::Days(0))
495                .expect("deleted and purged");
496        }
497        drop(store);
498        f.clock.set(datetime!(2026-10-24 12:00 UTC));
499        f.tenants
500            .remove(Actor::Cli, gone, crate::tenants::Removal::Empty)
501            .expect("removed");
502        assert_eq!(
503            f.tenants.rotation_backlog().expect("read"),
504            RotationBacklog {
505                tenants_with_purges: 1,
506                purges: 2,
507                oldest_purge: Some(datetime!(2026-10-24 10:00 UTC)),
508                removals: 1,
509                oldest_removal: Some(datetime!(2026-10-24 12:00 UTC)),
510            }
511        );
512    }
513
514    #[test]
515    fn removals_since_the_master_key_was_rotated_are_counted() {
516        let f = fixture();
517        let gone = f.tenants.create(Actor::Cli, "gone", None).expect("made");
518        f.tenants.create(Actor::Cli, "kept", None).expect("made");
519        f.clock.set(datetime!(2026-10-24 08:00 UTC));
520        f.tenants
521            .remove(Actor::Cli, gone, crate::tenants::Removal::Empty)
522            .expect("removed");
523        // A removal from before the master key's rotation, and a refused one.
524        f.conn()
525            .execute_batch(
526                "INSERT INTO audit (at, actor, action, target, version, status, count)
527                 VALUES ('2026-10-01T00:00:00Z', 'cli', 'tenant_remove', NULL, NULL, 204, 1),
528                        ('2026-10-24T09:00:00Z', 'cli', 'tenant_remove', NULL, NULL, 409, 1);",
529            )
530            .expect("older records");
531        let found = f
532            .tenants
533            .examine(Retention::Years(7), datetime!(2026-10-25 12:00 UTC))
534            .expect("examined");
535        assert_eq!(found.removed_since_master, 1);
536        assert_eq!(
537            found.oldest_removed_since_master,
538            Some(datetime!(2026-10-24 08:00 UTC))
539        );
540        assert_eq!(found.tenants.len(), 1);
541    }
542}