1use 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
43pub const PARTITION_RECORD_FILE: &str = "partition.json";
46
47pub const LOCAL_BINDINGS_FILE: &str = "partitions.local.json";
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum RetentionClass {
61 Ephemeral,
63 Standard,
65 Durable,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "kebab-case")]
84pub enum EncryptionMode {
85 Plaintext,
88 SealedRequired,
92}
93
94impl Default for RetentionClass {
95 fn default() -> Self {
101 RetentionClass::Standard
102 }
103}
104
105#[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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct Subject {
149 pub kind: SubjectKind,
150 pub id: String,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct PartitionKey {
161 pub current_epoch: u32,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub kek_ref: Option<String>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub kek_scheme: Option<String>,
172}
173
174impl PartitionKey {
175 fn reserved() -> Self {
179 PartitionKey {
180 current_epoch: 0,
181 kek_ref: None,
182 kek_scheme: None,
183 }
184 }
185
186 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct PartitionRecord {
214 pub format_version: u32,
215 pub partition_id: String,
218 pub encryption_mode: EncryptionMode,
224 pub retention_class: RetentionClass,
226 pub key: PartitionKey,
227 pub created_at: String,
230}
231
232#[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#[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
274pub(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
302pub(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
342pub(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
363pub(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
384pub(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
414pub 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 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 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 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 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}