Skip to main content

incokit_e2ee/
entity.rs

1//! Entity-scoped encryption helpers.
2//!
3//! Most persisted rows follow the same shape: one numeric id, a few
4//! sensitive fields that need encryption under a per-entity key. This
5//! module wires the three pieces together — [`SessionKey`] for the
6//! master key, [`KeyNamespace`] for scoping, [`crate::sealed`] for the wire
7//! format — so that adding a new encrypted entity only requires implementing
8//! [`EncryptedEntity`] and calling the `*_entity_*` helpers.
9//!
10//! Example:
11//!
12//! ```
13//! use incokit_e2ee::entity::{EncryptedEntity, seal_entity_json, try_unseal_entity_json};
14//! use incokit_e2ee::namespace::KeyNamespace;
15//! use incokit_e2ee::session::SessionKey;
16//! use serde_json::json;
17//!
18//! struct ProxyRow { id: i64 }
19//!
20//! impl EncryptedEntity for ProxyRow {
21//!     const NAMESPACE: KeyNamespace = KeyNamespace::Proxy;
22//!     fn entity_id(&self) -> i64 { self.id }
23//! }
24//!
25//! let session = SessionKey::new([42u8; 32]); // sourced from PIN unlock / keychain
26//! let row = ProxyRow { id: 7 };
27//! let payload = json!({ "host": "1.2.3.4", "port": 1080 });
28//!
29//! let blob = seal_entity_json(&session, &row, &payload).unwrap();
30//! let back: serde_json::Value = try_unseal_entity_json(&session, &row, &blob).unwrap();
31//! assert_eq!(back, payload);
32//! ```
33
34use crate::error::CryptoResult;
35use crate::namespace::KeyNamespace;
36use crate::sealed::{
37    seal_json, seal_string, try_unseal_json, try_unseal_string, unseal_json, unseal_string,
38};
39use crate::session::SessionKey;
40use serde::{de::DeserializeOwned, Serialize};
41
42/// A type whose sensitive fields are encrypted under a per-entity key
43/// derived from the session master key.
44///
45/// Implementors declare which [`KeyNamespace`] scopes their key and how
46/// to pull the id used in derivation. The trait is intentionally small
47/// — everything else lives in free functions keyed on the trait, so
48/// there's no blanket-impl magic to debug.
49pub trait EncryptedEntity {
50    /// HKDF namespace — one per entity type.
51    const NAMESPACE: KeyNamespace;
52
53    /// Numeric id fed into the key-derivation info string. Must be
54    /// stable for the lifetime of the row; if you renumber ids, you
55    /// must rewrap every blob.
56    fn entity_id(&self) -> i64;
57}
58
59impl SessionKey {
60    /// Convenience: derive the per-entity key for a specific row.
61    pub fn entity_key<E: EncryptedEntity>(&self, entity: &E) -> CryptoResult<[u8; 32]> {
62        self.derive(E::NAMESPACE, entity.entity_id())
63    }
64}
65
66// ─── string helpers ───────────────────────────────────────────────────────
67
68pub fn seal_entity_string<E: EncryptedEntity>(
69    session: &SessionKey,
70    entity: &E,
71    plaintext: &str,
72) -> CryptoResult<String> {
73    let key = session.entity_key(entity)?;
74    seal_string(&key, plaintext)
75}
76
77/// Strict: reject plaintext (missing `e2ee:` prefix).
78pub fn unseal_entity_string<E: EncryptedEntity>(
79    session: &SessionKey,
80    entity: &E,
81    stored: &str,
82) -> CryptoResult<String> {
83    let key = session.entity_key(entity)?;
84    unseal_string(&key, stored)
85}
86
87/// Lenient: accept legacy plaintext rows.
88pub fn try_unseal_entity_string<E: EncryptedEntity>(
89    session: &SessionKey,
90    entity: &E,
91    stored: &str,
92) -> CryptoResult<String> {
93    let key = session.entity_key(entity)?;
94    try_unseal_string(&key, stored)
95}
96
97// ─── JSON helpers ─────────────────────────────────────────────────────────
98
99pub fn seal_entity_json<E: EncryptedEntity, T: Serialize>(
100    session: &SessionKey,
101    entity: &E,
102    value: &T,
103) -> CryptoResult<String> {
104    let key = session.entity_key(entity)?;
105    seal_json(&key, value)
106}
107
108/// Strict: reject plaintext JSON.
109pub fn unseal_entity_json<E: EncryptedEntity, T: DeserializeOwned>(
110    session: &SessionKey,
111    entity: &E,
112    stored: &str,
113) -> CryptoResult<T> {
114    let key = session.entity_key(entity)?;
115    unseal_json(&key, stored)
116}
117
118/// Lenient: accept legacy plaintext JSON rows.
119pub fn try_unseal_entity_json<E: EncryptedEntity, T: DeserializeOwned>(
120    session: &SessionKey,
121    entity: &E,
122    stored: &str,
123) -> CryptoResult<T> {
124    let key = session.entity_key(entity)?;
125    try_unseal_json(&key, stored)
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    struct Dummy {
133        id: i64,
134    }
135
136    impl EncryptedEntity for Dummy {
137        const NAMESPACE: KeyNamespace = KeyNamespace::Profile;
138        fn entity_id(&self) -> i64 {
139            self.id
140        }
141    }
142
143    fn session() -> SessionKey {
144        SessionKey::new([42u8; 32])
145    }
146
147    #[test]
148    fn roundtrip_string() {
149        let s = session();
150        let e = Dummy { id: 7 };
151        let sealed = seal_entity_string(&s, &e, "hello").unwrap();
152        assert_eq!(try_unseal_entity_string(&s, &e, &sealed).unwrap(), "hello");
153    }
154
155    #[test]
156    fn different_ids_cannot_cross_decrypt() {
157        let s = session();
158        let a = Dummy { id: 1 };
159        let b = Dummy { id: 2 };
160        let sealed = seal_entity_string(&s, &a, "secret").unwrap();
161        assert!(try_unseal_entity_string(&s, &b, &sealed).is_err());
162    }
163
164    #[test]
165    fn plaintext_passes_through_try_variant() {
166        let s = session();
167        let e = Dummy { id: 1 };
168        assert_eq!(
169            try_unseal_entity_string(&s, &e, "legacy-plaintext").unwrap(),
170            "legacy-plaintext"
171        );
172    }
173
174    #[test]
175    fn plaintext_rejected_by_strict_variant() {
176        let s = session();
177        let e = Dummy { id: 1 };
178        assert!(unseal_entity_string(&s, &e, "legacy-plaintext").is_err());
179    }
180
181    // A second entity type sharing the SAME id space but a DIFFERENT
182    // namespace. This is the realistic cross-entity collision: a proxy and a
183    // profile can both have id=1.
184    struct OtherEntity {
185        id: i64,
186    }
187    impl EncryptedEntity for OtherEntity {
188        const NAMESPACE: KeyNamespace = KeyNamespace::Proxy;
189        fn entity_id(&self) -> i64 {
190            self.id
191        }
192    }
193
194    /// Same id, different namespace ⇒ different derived key ⇒ no cross-decrypt.
195    /// Guards against a refactor that drops the namespace from key derivation,
196    /// which would let one entity type read another's sealed fields.
197    #[test]
198    fn same_id_different_namespace_cannot_cross_decrypt() {
199        let s = session();
200        let profile = Dummy { id: 1 };
201        let proxy = OtherEntity { id: 1 };
202
203        let sealed = seal_entity_string(&s, &profile, "profile-secret").unwrap();
204        assert!(
205            try_unseal_entity_string(&s, &proxy, &sealed).is_err(),
206            "a proxy key must not decrypt a profile blob sharing the same id"
207        );
208    }
209
210    /// A different session master key derives different entity keys, so a
211    /// blob sealed under one session can't be opened under another.
212    #[test]
213    fn different_session_key_cannot_decrypt() {
214        let e = Dummy { id: 7 };
215        let sealed = seal_entity_string(&session(), &e, "secret").unwrap();
216
217        let other_session = SessionKey::new([99u8; 32]);
218        assert!(unseal_entity_string(&other_session, &e, &sealed).is_err());
219    }
220
221    #[test]
222    fn roundtrip_json() {
223        use serde_json::json;
224        let s = session();
225        let e = Dummy { id: 3 };
226        let value = json!({ "host": "1.2.3.4", "port": 1080 });
227
228        let sealed = seal_entity_json(&s, &e, &value).unwrap();
229        let back: serde_json::Value = try_unseal_entity_json(&s, &e, &sealed).unwrap();
230        assert_eq!(back, value);
231    }
232}