Skip to main content

runar_serializer/
traits.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::fmt::Debug;
5use std::sync::Arc;
6
7// ---------------------------------------------------------------------------
8// Re-exports from runar-keys for envelope encryption integration
9// ---------------------------------------------------------------------------
10pub use runar_keys::mobile::EnvelopeEncryptedData;
11pub use runar_keys::EnvelopeCrypto;
12
13// Trait-object alias so existing code that expects `&dyn KeyStore` continues to
14// compile while delegating to the real `EnvelopeCrypto` implementation.
15// This avoids another custom abstraction layer.
16pub type KeyStore = dyn EnvelopeCrypto;
17
18// ---------------------------------------------------------------------------
19// Key-scope modelling
20// ---------------------------------------------------------------------------
21
22/// Determines how an envelope key should be encrypted for a given label.
23// #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24// pub enum KeyScope {
25//     /// Encrypt with the network key so all nodes in the network can decrypt.
26//     Network,
27//     /// Encrypt with one or more user-profile keys so only specific profiles can decrypt.
28//     Profile,
29// }
30/// Information required to perform envelope encryption for a label.
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct LabelKeyInfo {
33    pub profile_public_keys: Vec<Vec<u8>>,
34    pub network_id: Option<String>,
35}
36
37// ---------------------------------------------------------------------------
38// Label-to-PublicKey mapping utilities
39// ---------------------------------------------------------------------------
40
41/// Label-to-PublicKey mapping configuration
42#[derive(Serialize, Deserialize, Debug, Clone)]
43pub struct KeyMappingConfig {
44    /// Maps labels to public-key information.
45    pub label_mappings: HashMap<String, LabelKeyInfo>,
46}
47
48/// Label resolver interface for mapping labels to public keys
49pub trait LabelResolver: Send + Sync {
50    /// Resolve a label to key-info (public key + scope).
51    fn resolve_label_info(&self, label: &str) -> Result<Option<LabelKeyInfo>>;
52
53    /// Get available labels in current context
54    fn available_labels(&self) -> Vec<String>;
55
56    /// Check if a label can be resolved
57    fn can_resolve(&self, label: &str) -> bool;
58
59    /// Clone this trait object
60    fn clone_box(&self) -> Box<dyn LabelResolver>;
61}
62
63// Implement LabelResolver for Box<dyn LabelResolver> to allow cloning
64impl LabelResolver for Box<dyn LabelResolver> {
65    fn resolve_label_info(&self, label: &str) -> Result<Option<LabelKeyInfo>> {
66        self.as_ref().resolve_label_info(label)
67    }
68
69    fn available_labels(&self) -> Vec<String> {
70        self.as_ref().available_labels()
71    }
72
73    fn can_resolve(&self, label: &str) -> bool {
74        self.as_ref().can_resolve(label)
75    }
76
77    fn clone_box(&self) -> Box<dyn LabelResolver> {
78        self.as_ref().clone_box()
79    }
80}
81
82/// Configurable label resolver implementation
83pub struct ConfigurableLabelResolver {
84    /// The mapping configuration
85    config: KeyMappingConfig,
86}
87
88impl ConfigurableLabelResolver {
89    pub fn new(config: KeyMappingConfig) -> Self {
90        Self { config }
91    }
92}
93
94impl LabelResolver for ConfigurableLabelResolver {
95    fn resolve_label_info(&self, label: &str) -> Result<Option<LabelKeyInfo>> {
96        Ok(self.config.label_mappings.get(label).cloned())
97    }
98
99    fn available_labels(&self) -> Vec<String> {
100        self.config.label_mappings.keys().cloned().collect()
101    }
102
103    fn can_resolve(&self, label: &str) -> bool {
104        self.config.label_mappings.contains_key(label)
105    }
106
107    fn clone_box(&self) -> Box<dyn LabelResolver> {
108        Box::new(ConfigurableLabelResolver {
109            config: self.config.clone(),
110        })
111    }
112}
113
114/// Marker trait for detecting encryption capability at runtime
115pub trait RunarEncryptable {}
116
117/// Trait for encrypting structs with selective field encryption
118pub trait RunarEncrypt: RunarEncryptable {
119    type Encrypted: RunarDecrypt<Decrypted = Self> + Serialize;
120
121    fn encrypt_with_keystore(
122        &self,
123        keystore: &Arc<KeyStore>,
124        resolver: &dyn LabelResolver,
125    ) -> Result<Self::Encrypted>;
126}
127
128/// Trait for decrypting encrypted structs
129pub trait RunarDecrypt {
130    type Decrypted: RunarEncrypt<Encrypted = Self>;
131
132    fn decrypt_with_keystore(&self, keystore: &Arc<KeyStore>) -> Result<Self::Decrypted>;
133}
134
135// (identity RunarEncrypt/RunarDecrypt impls for primitives are no longer
136// required – primitives never hit the decrypt registry path because they
137// succeed in the direct `serde_cbor` deserialisation fast-path.)
138// ---------------------------------------------------------------------------
139// Serialization Context for consolidated parameters
140// ---------------------------------------------------------------------------
141
142/// Consolidated context for serialization operations containing all encryption-related parameters
143#[derive(Clone)]
144pub struct SerializationContext {
145    pub keystore: Arc<KeyStore>,
146    pub resolver: Arc<dyn LabelResolver>,
147    pub network_id: String,
148    pub profile_public_key: Option<Vec<u8>>,
149}