Skip to main content

storage_kit/
partition.rs

1//! The partition metadata record and provisioning API — format v3.
2//!
3//! Implements the "partition record and provisioning" sections of
4//! the design spec (the format-reservations spec,
5//! §3, §4). Deliberately scoped to **exactly** that: this module does not
6//! touch the pack/idx entry layout (§1, §2) and does not add `context` or
7//! `key_epoch` fields to any packed byte — those stay gated on the open
8//! `(hash, context)` ruling and land in a later change.
9//!
10//! Two files, at two different levels, because two different things are
11//! recorded and only one of them should ever leave the machine:
12//!
13//! ```text
14//! <store_root>/
15//!   partitions.local.json          — LOCAL subject bindings, store-level.
16//!                                    NEVER replicated. NEVER inside any
17//!                                    partition directory.
18//!   <partition_id_hex>/
19//!     partition.json               — the PORTABLE partition record.
20//!     active/ packs/ manifests/
21//! ```
22//!
23//! **The guarantee this schema exists to make structural, not aspirational:**
24//! retention must reach a person partition identically to a household
25//! partition. [`PartitionStore`](crate::store::PartitionStore) loads
26//! [`PartitionRecord`] (portable: retention class, key epoch, timestamps)
27//! but never loads or holds a [`Subject`] — `subject` is read only inside
28//! [`crate::store::PartitionStore::create`], to verify the derivation, and
29//! is then written straight to the store-level local-binding file. No
30//! accessor on `PartitionStore` returns a `Subject`. Any future code that
31//! wants retention (or anything else) to behave differently for a person
32//! than a household would have to *change a function signature* to reach
33//! the subject at all — a visible act with an owner, not a quiet
34//! conditional.
35
36use crate::addressing::PartitionId;
37use crate::error::{Result, StorageError};
38use serde::{Deserialize, Serialize};
39use std::collections::BTreeMap;
40use std::fs;
41use std::path::{Path, PathBuf};
42
43/// File name of the portable, replicated partition record inside a
44/// partition directory.
45pub const PARTITION_RECORD_FILE: &str = "partition.json";
46
47/// File name of the store-level, never-replicated local binding record.
48/// Lives at the store root, **not** inside any partition directory — see
49/// the module docs and spec §R.4/Q2.
50pub const LOCAL_BINDINGS_FILE: &str = "partitions.local.json";
51
52/// The closed retention-class vocabulary (spec §3.4). Each class changes
53/// GC behaviour; a class that only labels is a taxonomy and does not
54/// belong here. Deliberately excludes: any retention *period*
55/// (`retain_days`, `expires_at`), a `legal_hold`/`hold` class, an
56/// `audit`/`compliance` class, and any access-time or access-count field —
57/// each refusal is load-bearing and is spelled out in the spec.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum RetentionClass {
61    /// GC may drop unreferenced content aggressively, unprompted by policy.
62    Ephemeral,
63    /// GC drops unreferenced content when GC is asked to run. The default.
64    Standard,
65    /// GC never drops content, referenced or not; it repacks for
66    /// utilization only. Destruction happens by destroying the whole
67    /// partition, never incidentally.
68    Durable,
69}
70
71/// The closed encryption-mode vocabulary (spec §3.2, added per §R.2 /
72/// the security review's D-1). **Set at creation, never changeable in
73/// place** — there is no `set_encryption_mode`, exactly as there is no
74/// `set_retention_class`; no transition is legal in either direction.
75///
76/// This crate implements **no encryption** — the key design is
77/// the security review's separate, concurrent workstream. This is the mode
78/// flag only: the field that lets sealing fail closed later instead of
79/// depending on every caller remembering, so it is cheap to add now and
80/// expensive to backfill onto partitions already written. `plaintext` is
81/// the only value any current caller can produce.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "kebab-case")]
84pub enum EncryptionMode {
85    /// No encryption. The only value any current caller can produce —
86    /// `storage-kit` has no key-wrapping concept yet.
87    Plaintext,
88    /// Every write into this partition must be sealed (AEAD-wrapped).
89    /// Reserved for when the key hierarchy lands; not enforced by this
90    /// crate today.
91    SealedRequired,
92}
93
94impl Default for RetentionClass {
95    /// The documented default (spec §3.4, §4.4) — **not** applied silently
96    /// by [`crate::store::PartitionStore::create`]. `PartitionSpec::retention_class`
97    /// is a required field; a caller that wants `standard` must say so.
98    /// This impl exists so `standard` has one canonical spelling for
99    /// callers that choose to use it, not to let `create` retrofit it.
100    fn default() -> Self {
101        RetentionClass::Standard
102    }
103}
104
105/// The subject-kind vocabulary for a local partition binding (spec §3.6,
106/// amended by §R.5). **Closed, forever, at exactly three values**: `person`,
107/// `household`, and `service`. Each is a derivation prefix for a principal
108/// that gets its own partition — recording a derivation input is not adding
109/// a taxonomy, and this enum being closed is what makes that true.
110///
111/// `service` is a **principal kind**, not a loosening of the closed-vocabulary
112/// guardrail: the security review ruled that a headless service principal
113/// needs its own partition because its key cannot be a second wrap of a
114/// person's — e.g. division CI must not run under a person's principal. It
115/// describes a *principal without a human*, not a *kind of customer*.
116///
117/// **Permanently banned, and this is the guardrail that still holds without
118/// exception:** a *segment* value — `business`, `org`, `team`, `project`,
119/// `client`, `division` — is the banned segment field wearing a
120/// storage-layer costume and requires an explicit maintainer decision before
121/// it could ever exist. A division household is a `household`, identical in
122/// every recorded byte to a family household except the free-text `label`.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "snake_case")]
125pub enum SubjectKind {
126    Person,
127    Household,
128    Service,
129}
130
131impl SubjectKind {
132    /// The domain-separator prefix hashed to derive a [`PartitionId`] for
133    /// this kind of subject — mirrors [`PartitionId::for_person`] /
134    /// [`PartitionId::for_household`] / [`PartitionId::for_service`].
135    fn derivation_prefix(self) -> &'static str {
136        match self {
137            SubjectKind::Person => "person",
138            SubjectKind::Household => "household",
139            SubjectKind::Service => "service",
140        }
141    }
142}
143
144/// A partition's subject: which principal it was provisioned for. Recorded
145/// only in the store-level [`LOCAL_BINDINGS_FILE`], never inside a
146/// partition directory.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct Subject {
149    pub kind: SubjectKind,
150    pub id: String,
151}
152
153/// The reserved key-material slot inside [`PartitionRecord`]. `kek_ref` and
154/// `kek_scheme` are opaque and unresolved today — storage-kit never parses,
155/// resolves, or logs either field. Both are `null` until the key hierarchy
156/// lands (the security review, concurrent, out of scope here); a non-null
157/// value is rejected on read, fail-closed, the same discipline as the
158/// pack/idx reserved fields.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct PartitionKey {
161    /// The epoch new writes are stamped with. `0` until wrapping lands.
162    pub current_epoch: u32,
163    /// Reserved. Must be `null` today. Never a path, a URL, or key
164    /// material — an opaque reference only, resolved by a custody layer
165    /// above this crate.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub kek_ref: Option<String>,
168    /// Reserved. Must be `null` today. The tag for *how* `kek_ref` is to
169    /// be interpreted, once it means something.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub kek_scheme: Option<String>,
172}
173
174impl PartitionKey {
175    /// The only value this crate ever writes: epoch 0, both reserved
176    /// fields null. There is no API to supply a non-default value —
177    /// `PartitionSpec` carries no key fields at all.
178    fn reserved() -> Self {
179        PartitionKey {
180            current_epoch: 0,
181            kek_ref: None,
182            kek_scheme: None,
183        }
184    }
185
186    /// Fail-closed check: reject a record whose reserved fields are
187    /// non-null. Never includes the offending value in the error — only
188    /// that one was present — because `kek_ref`/`kek_scheme` must never be
189    /// logged.
190    fn reject_if_non_null(&self) -> Result<()> {
191        if self.kek_ref.is_some() {
192            return Err(StorageError::CorruptManifest(
193                "partition.json: key.kek_ref is reserved and must be null".into(),
194            ));
195        }
196        if self.kek_scheme.is_some() {
197            return Err(StorageError::CorruptManifest(
198                "partition.json: key.kek_scheme is reserved and must be null".into(),
199            ));
200        }
201        Ok(())
202    }
203}
204
205/// `partition.json` — the portable partition record. Replicated verbatim
206/// with the data (spec §3.2): retention class and key state are properties
207/// of the bytes, not of the store root they happen to sit in today.
208///
209/// Contains no principal id, household id, member list, wrap, salt, KDF
210/// parameter, or factor — see the module docs and [`Subject`], which is
211/// recorded only in the separate, never-replicated local bindings file.
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct PartitionRecord {
214    pub format_version: u32,
215    /// 32 lowercase hex chars. Must equal the containing directory name;
216    /// checked on load.
217    pub partition_id: String,
218    /// Set at creation, never changeable in place. There is no
219    /// `set_encryption_mode` — see [`EncryptionMode`]. Replicated with the
220    /// data and subject to the same anti-laundering rule as
221    /// `retention_class` (spec §3.8): [`copy_partition_record`] fails if a
222    /// push would change a destination's `encryption_mode`.
223    pub encryption_mode: EncryptionMode,
224    /// Set at creation, immutable forever. There is no setter.
225    pub retention_class: RetentionClass,
226    pub key: PartitionKey,
227    /// RFC 3339, UTC. Provisioning time of the *partition*, not of a copy —
228    /// carried verbatim by [`copy_partition_record`].
229    pub created_at: String,
230}
231
232/// Input to [`crate::store::PartitionStore::create`]. Deliberately carries
233/// no default retention class and no default encryption mode: both fields
234/// are required, so a caller must choose. "Retention decided before ingest,
235/// not retrofitted" cannot be enforced by a constructor that silently fills
236/// one in — the same discipline applies to `encryption_mode`, which is the
237/// field that makes sealed-by-default fail closed rather than depending on
238/// every caller remembering.
239#[derive(Debug, Clone)]
240pub struct PartitionSpec {
241    pub subject: Subject,
242    pub retention_class: RetentionClass,
243    pub encryption_mode: EncryptionMode,
244    pub label: Option<String>,
245}
246
247/// One entry in the store-level [`LOCAL_BINDINGS_FILE`]: the subject a
248/// partition was provisioned for, plus a free-text label. Never parsed for
249/// semantics beyond `subject`.
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251pub struct LocalBinding {
252    pub subject: Subject,
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub label: Option<String>,
255}
256
257#[derive(Debug, Clone, Serialize, Deserialize)]
258struct LocalBindingsFile {
259    format_version: u32,
260    #[serde(default)]
261    bindings: BTreeMap<String, LocalBinding>,
262}
263
264fn record_path(store_root: &Path, partition_id: PartitionId) -> PathBuf {
265    store_root
266        .join(partition_id.to_hex())
267        .join(PARTITION_RECORD_FILE)
268}
269
270fn local_bindings_path(store_root: &Path) -> PathBuf {
271    store_root.join(LOCAL_BINDINGS_FILE)
272}
273
274/// Load and validate `partition.json` for `partition_id` under
275/// `store_root`. Fail-closed: rejects a `format_version` this build cannot
276/// read, a `partition_id` that disagrees with the containing directory
277/// name, and any non-null value in the reserved `key` fields.
278pub(crate) fn load_record(store_root: &Path, partition_id: PartitionId) -> Result<PartitionRecord> {
279    let path = record_path(store_root, partition_id);
280    let bytes = fs::read(&path)?;
281    let record: PartitionRecord = serde_json::from_slice(&bytes)?;
282
283    if record.format_version != crate::FORMAT_VERSION {
284        return Err(StorageError::CorruptManifest(format!(
285            "partition.json format_version {} unreadable by this build (reads {})",
286            record.format_version,
287            crate::FORMAT_VERSION
288        )));
289    }
290    if record.partition_id != partition_id.to_hex() {
291        return Err(StorageError::PartitionBoundary(format!(
292            "partition.json partition_id {} does not match containing directory {}",
293            record.partition_id,
294            partition_id.to_hex()
295        )));
296    }
297    record.key.reject_if_non_null()?;
298
299    Ok(record)
300}
301
302/// `true` if `partition_id` has a `partition.json` under `store_root` —
303/// the sole authoritative provisioning marker.
304pub(crate) fn is_provisioned(store_root: &Path, partition_id: PartitionId) -> bool {
305    record_path(store_root, partition_id).is_file()
306}
307
308fn write_record(
309    store_root: &Path,
310    partition_id: PartitionId,
311    record: &PartitionRecord,
312) -> Result<()> {
313    let path = record_path(store_root, partition_id);
314    if let Some(parent) = path.parent() {
315        fs::create_dir_all(parent)?;
316    }
317    let json = serde_json::to_string_pretty(record)?;
318    fs::write(&path, json)?;
319    Ok(())
320}
321
322fn load_local_bindings(store_root: &Path) -> Result<LocalBindingsFile> {
323    let path = local_bindings_path(store_root);
324    if !path.is_file() {
325        return Ok(LocalBindingsFile {
326            format_version: crate::FORMAT_VERSION,
327            bindings: BTreeMap::new(),
328        });
329    }
330    let bytes = fs::read(&path)?;
331    let file: LocalBindingsFile = serde_json::from_slice(&bytes)?;
332    Ok(file)
333}
334
335fn save_local_bindings(store_root: &Path, file: &LocalBindingsFile) -> Result<()> {
336    fs::create_dir_all(store_root)?;
337    let json = serde_json::to_string_pretty(file)?;
338    fs::write(local_bindings_path(store_root), json)?;
339    Ok(())
340}
341
342/// Write the local `subject`/`label` binding for `partition_id` into the
343/// store-level [`LOCAL_BINDINGS_FILE`]. Called by
344/// [`crate::store::PartitionStore::create`] only — never by `open`, and
345/// never with the partition directory as the target.
346pub(crate) fn bind_local(
347    store_root: &Path,
348    partition_id: PartitionId,
349    subject: &Subject,
350    label: &Option<String>,
351) -> Result<()> {
352    let mut file = load_local_bindings(store_root)?;
353    file.bindings.insert(
354        partition_id.to_hex(),
355        LocalBinding {
356            subject: subject.clone(),
357            label: label.clone(),
358        },
359    );
360    save_local_bindings(store_root, &file)
361}
362
363/// Verify `PartitionId::derive("{kind}:{id}")` reproduces `partition_id`,
364/// mirroring [`PartitionId::for_person`]/[`PartitionId::for_household`].
365/// A partition cannot be provisioned under a subject it was not derived
366/// from.
367pub(crate) fn verify_derivation(partition_id: PartitionId, subject: &Subject) -> Result<()> {
368    let expected = PartitionId::derive(&format!(
369        "{}:{}",
370        subject.kind.derivation_prefix(),
371        subject.id
372    ));
373    if expected != partition_id {
374        return Err(StorageError::PartitionBoundary(format!(
375            "partition {} was not derived from subject {{kind: {:?}, id: {}}}",
376            partition_id.to_hex(),
377            subject.kind,
378            subject.id
379        )));
380    }
381    Ok(())
382}
383
384/// Build the portable record `create()` writes: the reserved key block,
385/// the provided retention class and encryption mode, and the current
386/// timestamp.
387pub(crate) fn new_record(
388    partition_id: PartitionId,
389    retention_class: RetentionClass,
390    encryption_mode: EncryptionMode,
391) -> PartitionRecord {
392    PartitionRecord {
393        format_version: crate::FORMAT_VERSION,
394        partition_id: partition_id.to_hex(),
395        encryption_mode,
396        retention_class,
397        key: PartitionKey::reserved(),
398        created_at: now_rfc3339(),
399    }
400}
401
402pub(crate) fn write_new_record(
403    store_root: &Path,
404    partition_id: PartitionId,
405    record: &PartitionRecord,
406) -> Result<()> {
407    write_record(store_root, partition_id, record)
408}
409
410fn now_rfc3339() -> String {
411    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
412}
413
414/// Copy `partition.json` from `source_store_root` to `dest_store_root` for
415/// `partition_id` (spec §3.8). Copies the portable record only — never
416/// [`LOCAL_BINDINGS_FILE`], which is not inside any partition directory and
417/// so is out of reach of a per-partition copy by construction.
418///
419/// **Fails if the destination already holds a record whose
420/// `retention_class` or `encryption_mode` differs from the source's.**
421/// Replication may not change either — that is the laundering hole this
422/// closes (spec §3.8 rule 2). A replica that lost `sealed-required` would
423/// accept plaintext writes into a partition that must never hold any, which
424/// is the same hole as retention laundering wearing a different hat.
425pub fn copy_partition_record(
426    source_store_root: &Path,
427    dest_store_root: &Path,
428    partition_id: PartitionId,
429) -> Result<()> {
430    let source_path = record_path(source_store_root, partition_id);
431    if !source_path.is_file() {
432        return Err(StorageError::PartitionNotProvisioned(partition_id.to_hex()));
433    }
434    let source_record = load_record(source_store_root, partition_id)?;
435
436    let dest_path = record_path(dest_store_root, partition_id);
437    if dest_path.is_file() {
438        let dest_record = load_record(dest_store_root, partition_id)?;
439        if dest_record.retention_class != source_record.retention_class {
440            return Err(StorageError::PartitionBoundary(format!(
441                "copy_partition_record: destination retention_class for {} would change ({:?} -> {:?}); replication may not change a retention class",
442                partition_id.to_hex(),
443                dest_record.retention_class,
444                source_record.retention_class,
445            )));
446        }
447        if dest_record.encryption_mode != source_record.encryption_mode {
448            return Err(StorageError::PartitionBoundary(format!(
449                "copy_partition_record: destination encryption_mode for {} would change ({:?} -> {:?}); replication may not change an encryption mode",
450                partition_id.to_hex(),
451                dest_record.encryption_mode,
452                source_record.encryption_mode,
453            )));
454        }
455    }
456
457    if let Some(parent) = dest_path.parent() {
458        fs::create_dir_all(parent)?;
459    }
460    // Copy verbatim (byte-for-byte) so `created_at` and every other field
461    // carry over exactly as written at provisioning time.
462    fs::copy(&source_path, &dest_path)?;
463    Ok(())
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use tempfile::tempdir;
470
471    #[test]
472    fn subject_kind_rejects_a_fourth_value() {
473        // `service` is now legal (§R.5) — the closed vocabulary is exactly
474        // three values. What must stay permanently rejected is a *segment*
475        // value wearing a storage-layer costume, per §3.6's guardrail.
476        let json = r#"{"kind":"business","id":"biz-1"}"#;
477        let result: std::result::Result<Subject, _> = serde_json::from_str(json);
478        assert!(
479            result.is_err(),
480            "subject.kind must be a closed three-value vocabulary (person, household, service) \
481             — a segment value like `business` must never deserialize"
482        );
483    }
484
485    #[test]
486    fn subject_kind_accepts_person_household_and_service() {
487        for json in [
488            r#"{"kind":"person","id":"a"}"#,
489            r#"{"kind":"household","id":"h"}"#,
490            r#"{"kind":"service","id":"svc-1"}"#,
491        ] {
492            let result: std::result::Result<Subject, _> = serde_json::from_str(json);
493            assert!(result.is_ok(), "expected {json} to deserialize");
494        }
495    }
496
497    #[test]
498    fn encryption_mode_rejects_a_third_value() {
499        let json = r#""sealed""#;
500        let result: std::result::Result<EncryptionMode, _> = serde_json::from_str(json);
501        assert!(
502            result.is_err(),
503            "encryption_mode must be a closed two-value vocabulary (plaintext, sealed-required)"
504        );
505    }
506
507    #[test]
508    fn encryption_mode_accepts_plaintext_and_sealed_required() {
509        for (json, expected) in [
510            (r#""plaintext""#, EncryptionMode::Plaintext),
511            (r#""sealed-required""#, EncryptionMode::SealedRequired),
512        ] {
513            let result: EncryptionMode = serde_json::from_str(json).unwrap();
514            assert_eq!(result, expected);
515        }
516    }
517
518    #[test]
519    fn retention_class_default_is_standard() {
520        assert_eq!(RetentionClass::default(), RetentionClass::Standard);
521    }
522
523    #[test]
524    fn partition_key_reserved_fields_are_null() {
525        let key = PartitionKey::reserved();
526        assert!(key.kek_ref.is_none());
527        assert!(key.kek_scheme.is_none());
528        assert_eq!(key.current_epoch, 0);
529    }
530
531    #[test]
532    fn partition_key_rejects_non_null_kek_ref() {
533        let key = PartitionKey {
534            current_epoch: 0,
535            kek_ref: Some("anything".into()),
536            kek_scheme: None,
537        };
538        assert!(key.reject_if_non_null().is_err());
539    }
540
541    #[test]
542    fn partition_key_rejects_non_null_kek_scheme() {
543        let key = PartitionKey {
544            current_epoch: 0,
545            kek_ref: None,
546            kek_scheme: Some("anything".into()),
547        };
548        assert!(key.reject_if_non_null().is_err());
549    }
550
551    #[test]
552    fn null_and_empty_string_kek_ref_are_distinct() {
553        let null_key = PartitionKey::reserved();
554        let empty_key = PartitionKey {
555            current_epoch: 0,
556            kek_ref: Some(String::new()),
557            kek_scheme: None,
558        };
559        assert_ne!(null_key.kek_ref, empty_key.kek_ref);
560        // Both must round-trip through JSON without collapsing into one another.
561        let null_json = serde_json::to_string(&null_key).unwrap();
562        let empty_json = serde_json::to_string(&empty_key).unwrap();
563        assert_ne!(null_json, empty_json);
564        let round_tripped: PartitionKey = serde_json::from_str(&empty_json).unwrap();
565        assert_eq!(round_tripped.kek_ref, Some(String::new()));
566    }
567
568    #[test]
569    fn verify_derivation_accepts_matching_subject() {
570        let subject = Subject {
571            kind: SubjectKind::Person,
572            id: "acct-1".into(),
573        };
574        let partition_id = PartitionId::for_person("acct-1");
575        assert!(verify_derivation(partition_id, &subject).is_ok());
576    }
577
578    #[test]
579    fn verify_derivation_rejects_mismatched_subject() {
580        let subject = Subject {
581            kind: SubjectKind::Person,
582            id: "acct-1".into(),
583        };
584        let wrong_id = PartitionId::for_person("acct-2");
585        assert!(verify_derivation(wrong_id, &subject).is_err());
586
587        let household_id = PartitionId::for_household("acct-1");
588        assert!(verify_derivation(household_id, &subject).is_err());
589    }
590
591    #[test]
592    fn verify_derivation_accepts_matching_service_subject() {
593        let subject = Subject {
594            kind: SubjectKind::Service,
595            id: "svc-ci-1".into(),
596        };
597        let partition_id = PartitionId::for_service("svc-ci-1");
598        assert!(verify_derivation(partition_id, &subject).is_ok());
599
600        // A service subject must not verify against a person/household
601        // partition derived from the same raw id — the domain prefix keeps
602        // the three kinds from colliding.
603        let person_id = PartitionId::for_person("svc-ci-1");
604        assert!(verify_derivation(person_id, &subject).is_err());
605    }
606
607    #[test]
608    fn copy_partition_record_refuses_retention_class_change() {
609        let source_root = tempdir().unwrap();
610        let dest_root = tempdir().unwrap();
611        let partition_id = PartitionId::for_person("copy-test");
612
613        let source_record = new_record(
614            partition_id,
615            RetentionClass::Durable,
616            EncryptionMode::Plaintext,
617        );
618        write_new_record(source_root.path(), partition_id, &source_record).unwrap();
619
620        let dest_record = new_record(
621            partition_id,
622            RetentionClass::Ephemeral,
623            EncryptionMode::Plaintext,
624        );
625        write_new_record(dest_root.path(), partition_id, &dest_record).unwrap();
626
627        let err = copy_partition_record(source_root.path(), dest_root.path(), partition_id)
628            .expect_err("retention class laundering must be refused");
629        let msg = format!("{err}");
630        assert!(msg.contains("retention"), "unexpected error: {msg}");
631    }
632
633    #[test]
634    fn copy_partition_record_refuses_encryption_mode_change() {
635        let source_root = tempdir().unwrap();
636        let dest_root = tempdir().unwrap();
637        let partition_id = PartitionId::for_person("copy-test-encryption");
638
639        let source_record = new_record(
640            partition_id,
641            RetentionClass::Standard,
642            EncryptionMode::SealedRequired,
643        );
644        write_new_record(source_root.path(), partition_id, &source_record).unwrap();
645
646        let dest_record = new_record(
647            partition_id,
648            RetentionClass::Standard,
649            EncryptionMode::Plaintext,
650        );
651        write_new_record(dest_root.path(), partition_id, &dest_record).unwrap();
652
653        let err = copy_partition_record(source_root.path(), dest_root.path(), partition_id)
654            .expect_err(
655                "encryption mode laundering must be refused — a replica must not be able to lose \
656             sealed-required",
657            );
658        let msg = format!("{err}");
659        assert!(msg.contains("encryption_mode"), "unexpected error: {msg}");
660    }
661
662    #[test]
663    fn copy_partition_record_succeeds_when_retention_class_matches() {
664        let source_root = tempdir().unwrap();
665        let dest_root = tempdir().unwrap();
666        let partition_id = PartitionId::for_person("copy-test-ok");
667
668        let source_record = new_record(
669            partition_id,
670            RetentionClass::Standard,
671            EncryptionMode::Plaintext,
672        );
673        write_new_record(source_root.path(), partition_id, &source_record).unwrap();
674
675        copy_partition_record(source_root.path(), dest_root.path(), partition_id).unwrap();
676
677        let copied = load_record(dest_root.path(), partition_id).unwrap();
678        assert_eq!(copied, source_record);
679    }
680
681    #[test]
682    fn copy_partition_record_succeeds_on_a_fresh_destination() {
683        let source_root = tempdir().unwrap();
684        let dest_root = tempdir().unwrap();
685        let partition_id = PartitionId::for_household("copy-test-fresh");
686
687        let source_record = new_record(
688            partition_id,
689            RetentionClass::Ephemeral,
690            EncryptionMode::Plaintext,
691        );
692        write_new_record(source_root.path(), partition_id, &source_record).unwrap();
693
694        copy_partition_record(source_root.path(), dest_root.path(), partition_id).unwrap();
695        let copied = load_record(dest_root.path(), partition_id).unwrap();
696        assert_eq!(copied, source_record);
697    }
698
699    #[test]
700    fn copy_partition_record_never_touches_local_bindings() {
701        let source_root = tempdir().unwrap();
702        let dest_root = tempdir().unwrap();
703        let partition_id = PartitionId::for_person("copy-test-no-local");
704
705        let subject = Subject {
706            kind: SubjectKind::Person,
707            id: "copy-test-no-local".into(),
708        };
709        bind_local(source_root.path(), partition_id, &subject, &None).unwrap();
710        let source_record = new_record(
711            partition_id,
712            RetentionClass::Standard,
713            EncryptionMode::Plaintext,
714        );
715        write_new_record(source_root.path(), partition_id, &source_record).unwrap();
716
717        copy_partition_record(source_root.path(), dest_root.path(), partition_id).unwrap();
718
719        assert!(
720            !local_bindings_path(dest_root.path()).exists(),
721            "copy_partition_record must never write partitions.local.json"
722        );
723    }
724}