use crate::addressing::PartitionId;
use crate::error::{Result, StorageError};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
pub const PARTITION_RECORD_FILE: &str = "partition.json";
pub const LOCAL_BINDINGS_FILE: &str = "partitions.local.json";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RetentionClass {
Ephemeral,
Standard,
Durable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EncryptionMode {
Plaintext,
SealedRequired,
}
impl Default for RetentionClass {
fn default() -> Self {
RetentionClass::Standard
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubjectKind {
Person,
Household,
Service,
}
impl SubjectKind {
fn derivation_prefix(self) -> &'static str {
match self {
SubjectKind::Person => "person",
SubjectKind::Household => "household",
SubjectKind::Service => "service",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Subject {
pub kind: SubjectKind,
pub id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartitionKey {
pub current_epoch: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kek_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kek_scheme: Option<String>,
}
impl PartitionKey {
fn reserved() -> Self {
PartitionKey {
current_epoch: 0,
kek_ref: None,
kek_scheme: None,
}
}
fn reject_if_non_null(&self) -> Result<()> {
if self.kek_ref.is_some() {
return Err(StorageError::CorruptManifest(
"partition.json: key.kek_ref is reserved and must be null".into(),
));
}
if self.kek_scheme.is_some() {
return Err(StorageError::CorruptManifest(
"partition.json: key.kek_scheme is reserved and must be null".into(),
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartitionRecord {
pub format_version: u32,
pub partition_id: String,
pub encryption_mode: EncryptionMode,
pub retention_class: RetentionClass,
pub key: PartitionKey,
pub created_at: String,
}
#[derive(Debug, Clone)]
pub struct PartitionSpec {
pub subject: Subject,
pub retention_class: RetentionClass,
pub encryption_mode: EncryptionMode,
pub label: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LocalBinding {
pub subject: Subject,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct LocalBindingsFile {
format_version: u32,
#[serde(default)]
bindings: BTreeMap<String, LocalBinding>,
}
fn record_path(store_root: &Path, partition_id: PartitionId) -> PathBuf {
store_root
.join(partition_id.to_hex())
.join(PARTITION_RECORD_FILE)
}
fn local_bindings_path(store_root: &Path) -> PathBuf {
store_root.join(LOCAL_BINDINGS_FILE)
}
pub(crate) fn load_record(store_root: &Path, partition_id: PartitionId) -> Result<PartitionRecord> {
let path = record_path(store_root, partition_id);
let bytes = fs::read(&path)?;
let record: PartitionRecord = serde_json::from_slice(&bytes)?;
if record.format_version != crate::FORMAT_VERSION {
return Err(StorageError::CorruptManifest(format!(
"partition.json format_version {} unreadable by this build (reads {})",
record.format_version,
crate::FORMAT_VERSION
)));
}
if record.partition_id != partition_id.to_hex() {
return Err(StorageError::PartitionBoundary(format!(
"partition.json partition_id {} does not match containing directory {}",
record.partition_id,
partition_id.to_hex()
)));
}
record.key.reject_if_non_null()?;
Ok(record)
}
pub(crate) fn is_provisioned(store_root: &Path, partition_id: PartitionId) -> bool {
record_path(store_root, partition_id).is_file()
}
fn write_record(
store_root: &Path,
partition_id: PartitionId,
record: &PartitionRecord,
) -> Result<()> {
let path = record_path(store_root, partition_id);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let json = serde_json::to_string_pretty(record)?;
fs::write(&path, json)?;
Ok(())
}
fn load_local_bindings(store_root: &Path) -> Result<LocalBindingsFile> {
let path = local_bindings_path(store_root);
if !path.is_file() {
return Ok(LocalBindingsFile {
format_version: crate::FORMAT_VERSION,
bindings: BTreeMap::new(),
});
}
let bytes = fs::read(&path)?;
let file: LocalBindingsFile = serde_json::from_slice(&bytes)?;
Ok(file)
}
fn save_local_bindings(store_root: &Path, file: &LocalBindingsFile) -> Result<()> {
fs::create_dir_all(store_root)?;
let json = serde_json::to_string_pretty(file)?;
fs::write(local_bindings_path(store_root), json)?;
Ok(())
}
pub(crate) fn bind_local(
store_root: &Path,
partition_id: PartitionId,
subject: &Subject,
label: &Option<String>,
) -> Result<()> {
let mut file = load_local_bindings(store_root)?;
file.bindings.insert(
partition_id.to_hex(),
LocalBinding {
subject: subject.clone(),
label: label.clone(),
},
);
save_local_bindings(store_root, &file)
}
pub(crate) fn verify_derivation(partition_id: PartitionId, subject: &Subject) -> Result<()> {
let expected = PartitionId::derive(&format!(
"{}:{}",
subject.kind.derivation_prefix(),
subject.id
));
if expected != partition_id {
return Err(StorageError::PartitionBoundary(format!(
"partition {} was not derived from subject {{kind: {:?}, id: {}}}",
partition_id.to_hex(),
subject.kind,
subject.id
)));
}
Ok(())
}
pub(crate) fn new_record(
partition_id: PartitionId,
retention_class: RetentionClass,
encryption_mode: EncryptionMode,
) -> PartitionRecord {
PartitionRecord {
format_version: crate::FORMAT_VERSION,
partition_id: partition_id.to_hex(),
encryption_mode,
retention_class,
key: PartitionKey::reserved(),
created_at: now_rfc3339(),
}
}
pub(crate) fn write_new_record(
store_root: &Path,
partition_id: PartitionId,
record: &PartitionRecord,
) -> Result<()> {
write_record(store_root, partition_id, record)
}
fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
pub fn copy_partition_record(
source_store_root: &Path,
dest_store_root: &Path,
partition_id: PartitionId,
) -> Result<()> {
let source_path = record_path(source_store_root, partition_id);
if !source_path.is_file() {
return Err(StorageError::PartitionNotProvisioned(partition_id.to_hex()));
}
let source_record = load_record(source_store_root, partition_id)?;
let dest_path = record_path(dest_store_root, partition_id);
if dest_path.is_file() {
let dest_record = load_record(dest_store_root, partition_id)?;
if dest_record.retention_class != source_record.retention_class {
return Err(StorageError::PartitionBoundary(format!(
"copy_partition_record: destination retention_class for {} would change ({:?} -> {:?}); replication may not change a retention class",
partition_id.to_hex(),
dest_record.retention_class,
source_record.retention_class,
)));
}
if dest_record.encryption_mode != source_record.encryption_mode {
return Err(StorageError::PartitionBoundary(format!(
"copy_partition_record: destination encryption_mode for {} would change ({:?} -> {:?}); replication may not change an encryption mode",
partition_id.to_hex(),
dest_record.encryption_mode,
source_record.encryption_mode,
)));
}
}
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
fs::copy(&source_path, &dest_path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn subject_kind_rejects_a_fourth_value() {
let json = r#"{"kind":"business","id":"biz-1"}"#;
let result: std::result::Result<Subject, _> = serde_json::from_str(json);
assert!(
result.is_err(),
"subject.kind must be a closed three-value vocabulary (person, household, service) \
— a segment value like `business` must never deserialize"
);
}
#[test]
fn subject_kind_accepts_person_household_and_service() {
for json in [
r#"{"kind":"person","id":"a"}"#,
r#"{"kind":"household","id":"h"}"#,
r#"{"kind":"service","id":"svc-1"}"#,
] {
let result: std::result::Result<Subject, _> = serde_json::from_str(json);
assert!(result.is_ok(), "expected {json} to deserialize");
}
}
#[test]
fn encryption_mode_rejects_a_third_value() {
let json = r#""sealed""#;
let result: std::result::Result<EncryptionMode, _> = serde_json::from_str(json);
assert!(
result.is_err(),
"encryption_mode must be a closed two-value vocabulary (plaintext, sealed-required)"
);
}
#[test]
fn encryption_mode_accepts_plaintext_and_sealed_required() {
for (json, expected) in [
(r#""plaintext""#, EncryptionMode::Plaintext),
(r#""sealed-required""#, EncryptionMode::SealedRequired),
] {
let result: EncryptionMode = serde_json::from_str(json).unwrap();
assert_eq!(result, expected);
}
}
#[test]
fn retention_class_default_is_standard() {
assert_eq!(RetentionClass::default(), RetentionClass::Standard);
}
#[test]
fn partition_key_reserved_fields_are_null() {
let key = PartitionKey::reserved();
assert!(key.kek_ref.is_none());
assert!(key.kek_scheme.is_none());
assert_eq!(key.current_epoch, 0);
}
#[test]
fn partition_key_rejects_non_null_kek_ref() {
let key = PartitionKey {
current_epoch: 0,
kek_ref: Some("anything".into()),
kek_scheme: None,
};
assert!(key.reject_if_non_null().is_err());
}
#[test]
fn partition_key_rejects_non_null_kek_scheme() {
let key = PartitionKey {
current_epoch: 0,
kek_ref: None,
kek_scheme: Some("anything".into()),
};
assert!(key.reject_if_non_null().is_err());
}
#[test]
fn null_and_empty_string_kek_ref_are_distinct() {
let null_key = PartitionKey::reserved();
let empty_key = PartitionKey {
current_epoch: 0,
kek_ref: Some(String::new()),
kek_scheme: None,
};
assert_ne!(null_key.kek_ref, empty_key.kek_ref);
let null_json = serde_json::to_string(&null_key).unwrap();
let empty_json = serde_json::to_string(&empty_key).unwrap();
assert_ne!(null_json, empty_json);
let round_tripped: PartitionKey = serde_json::from_str(&empty_json).unwrap();
assert_eq!(round_tripped.kek_ref, Some(String::new()));
}
#[test]
fn verify_derivation_accepts_matching_subject() {
let subject = Subject {
kind: SubjectKind::Person,
id: "acct-1".into(),
};
let partition_id = PartitionId::for_person("acct-1");
assert!(verify_derivation(partition_id, &subject).is_ok());
}
#[test]
fn verify_derivation_rejects_mismatched_subject() {
let subject = Subject {
kind: SubjectKind::Person,
id: "acct-1".into(),
};
let wrong_id = PartitionId::for_person("acct-2");
assert!(verify_derivation(wrong_id, &subject).is_err());
let household_id = PartitionId::for_household("acct-1");
assert!(verify_derivation(household_id, &subject).is_err());
}
#[test]
fn verify_derivation_accepts_matching_service_subject() {
let subject = Subject {
kind: SubjectKind::Service,
id: "svc-ci-1".into(),
};
let partition_id = PartitionId::for_service("svc-ci-1");
assert!(verify_derivation(partition_id, &subject).is_ok());
let person_id = PartitionId::for_person("svc-ci-1");
assert!(verify_derivation(person_id, &subject).is_err());
}
#[test]
fn copy_partition_record_refuses_retention_class_change() {
let source_root = tempdir().unwrap();
let dest_root = tempdir().unwrap();
let partition_id = PartitionId::for_person("copy-test");
let source_record = new_record(
partition_id,
RetentionClass::Durable,
EncryptionMode::Plaintext,
);
write_new_record(source_root.path(), partition_id, &source_record).unwrap();
let dest_record = new_record(
partition_id,
RetentionClass::Ephemeral,
EncryptionMode::Plaintext,
);
write_new_record(dest_root.path(), partition_id, &dest_record).unwrap();
let err = copy_partition_record(source_root.path(), dest_root.path(), partition_id)
.expect_err("retention class laundering must be refused");
let msg = format!("{err}");
assert!(msg.contains("retention"), "unexpected error: {msg}");
}
#[test]
fn copy_partition_record_refuses_encryption_mode_change() {
let source_root = tempdir().unwrap();
let dest_root = tempdir().unwrap();
let partition_id = PartitionId::for_person("copy-test-encryption");
let source_record = new_record(
partition_id,
RetentionClass::Standard,
EncryptionMode::SealedRequired,
);
write_new_record(source_root.path(), partition_id, &source_record).unwrap();
let dest_record = new_record(
partition_id,
RetentionClass::Standard,
EncryptionMode::Plaintext,
);
write_new_record(dest_root.path(), partition_id, &dest_record).unwrap();
let err = copy_partition_record(source_root.path(), dest_root.path(), partition_id)
.expect_err(
"encryption mode laundering must be refused — a replica must not be able to lose \
sealed-required",
);
let msg = format!("{err}");
assert!(msg.contains("encryption_mode"), "unexpected error: {msg}");
}
#[test]
fn copy_partition_record_succeeds_when_retention_class_matches() {
let source_root = tempdir().unwrap();
let dest_root = tempdir().unwrap();
let partition_id = PartitionId::for_person("copy-test-ok");
let source_record = new_record(
partition_id,
RetentionClass::Standard,
EncryptionMode::Plaintext,
);
write_new_record(source_root.path(), partition_id, &source_record).unwrap();
copy_partition_record(source_root.path(), dest_root.path(), partition_id).unwrap();
let copied = load_record(dest_root.path(), partition_id).unwrap();
assert_eq!(copied, source_record);
}
#[test]
fn copy_partition_record_succeeds_on_a_fresh_destination() {
let source_root = tempdir().unwrap();
let dest_root = tempdir().unwrap();
let partition_id = PartitionId::for_household("copy-test-fresh");
let source_record = new_record(
partition_id,
RetentionClass::Ephemeral,
EncryptionMode::Plaintext,
);
write_new_record(source_root.path(), partition_id, &source_record).unwrap();
copy_partition_record(source_root.path(), dest_root.path(), partition_id).unwrap();
let copied = load_record(dest_root.path(), partition_id).unwrap();
assert_eq!(copied, source_record);
}
#[test]
fn copy_partition_record_never_touches_local_bindings() {
let source_root = tempdir().unwrap();
let dest_root = tempdir().unwrap();
let partition_id = PartitionId::for_person("copy-test-no-local");
let subject = Subject {
kind: SubjectKind::Person,
id: "copy-test-no-local".into(),
};
bind_local(source_root.path(), partition_id, &subject, &None).unwrap();
let source_record = new_record(
partition_id,
RetentionClass::Standard,
EncryptionMode::Plaintext,
);
write_new_record(source_root.path(), partition_id, &source_record).unwrap();
copy_partition_record(source_root.path(), dest_root.path(), partition_id).unwrap();
assert!(
!local_bindings_path(dest_root.path()).exists(),
"copy_partition_record must never write partitions.local.json"
);
}
}