tandem-memory 0.6.8

Memory storage and embedding utilities for Tandem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use crate::types::{MemoryError, MemoryResult, MemoryTenantScope};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use tandem_enterprise_contract::DataClass;

pub const MEMORY_ENVELOPE_METADATA_KEY: &str = "memory_envelope";
const HOSTED_ENCRYPTION_REQUIRED_ENV: &str = "TANDEM_MEMORY_ENCRYPTION_REQUIRED";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryKeyScope {
    pub org_id: String,
    pub workspace_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deployment_id: Option<String>,
    /// Department (`owner_org_unit_id`) that owns the wrapped DEK (TAN-662).
    /// Makes department a **cryptographic** key dimension, not just an
    /// access-control one: each `(tenant × department × data_class × source)`
    /// gets a distinct DEK, so a leaked department key cannot decrypt another
    /// department's ciphertext in the same tenant + data class. `None` =
    /// tenant-wide (no department), mirroring the `owner_org_unit_id` row column.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub org_unit: Option<String>,
    pub data_class: DataClass,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_binding_id: Option<String>,
}

impl MemoryKeyScope {
    pub fn new(
        tenant_scope: &MemoryTenantScope,
        data_class: DataClass,
        source_binding_id: Option<String>,
    ) -> Self {
        Self {
            org_id: tenant_scope.org_id.clone(),
            workspace_id: tenant_scope.workspace_id.clone(),
            deployment_id: tenant_scope.deployment_id.clone(),
            org_unit: None,
            data_class,
            source_binding_id,
        }
    }

    /// Bind this key scope to a department (TAN-662). A trimmed-empty value is
    /// treated as no department.
    pub fn with_org_unit(mut self, org_unit: Option<String>) -> Self {
        self.org_unit = org_unit
            .map(|unit| unit.trim().to_string())
            .filter(|unit| !unit.is_empty());
        self
    }

    pub fn canonical_id(&self) -> String {
        let deployment = self.deployment_id.as_deref().unwrap_or("default");
        let class = serde_json::to_value(self.data_class)
            .ok()
            .and_then(|value| value.as_str().map(ToOwned::to_owned))
            .unwrap_or_else(|| "unknown".to_string());
        // The department segment must be structurally distinct from the
        // tenant-wide form so `dept/x` can never collide with a data-class or
        // source segment, keeping per-department DEKs unambiguous. The org-unit
        // value is caller-derived (`{taxonomy_id}/{unit_id}`) and legitimately
        // contains `/`, so it is percent-encoded to prevent delimiter injection:
        // without it, `org_unit="a/source/b"` (no source) would collide with
        // `org_unit="a", source="b"` and share a DEK across departments.
        let dept = match self.org_unit.as_deref() {
            Some(org_unit) if !org_unit.trim().is_empty() => {
                format!("/dept/{}", encode_scope_segment(org_unit))
            }
            _ => String::new(),
        };
        match self.source_binding_id.as_deref() {
            Some(source_binding_id) if !source_binding_id.trim().is_empty() => format!(
                "tandem/memory/{}/{}/{}/{}{}/source/{}",
                self.org_id, self.workspace_id, deployment, class, dept, source_binding_id
            ),
            _ => format!(
                "tandem/memory/{}/{}/{}/{}{}",
                self.org_id, self.workspace_id, deployment, class, dept
            ),
        }
    }

    fn validates_against_tenant(&self, tenant_scope: &MemoryTenantScope) -> bool {
        self.org_id == tenant_scope.org_id
            && self.workspace_id == tenant_scope.workspace_id
            && self.deployment_id.as_deref().unwrap_or("")
                == tenant_scope.deployment_id.as_deref().unwrap_or("")
    }

    /// Validate that this scope is safe to seal a DEK under: no wildcard tenant,
    /// deployment, or department segment (any of which would collapse per-scope
    /// DEKs into a shared key). Called on the write path before wrapping.
    pub fn validate_for_envelope(&self) -> MemoryResult<()> {
        self.validate_partitioned()
    }

    fn validate_partitioned(&self) -> MemoryResult<()> {
        for (field, value) in [
            ("org_id", self.org_id.as_str()),
            ("workspace_id", self.workspace_id.as_str()),
        ] {
            if is_wildcard_scope(value) {
                return Err(MemoryError::InvalidConfig(format!(
                    "memory envelope key scope must not use wildcard `{field}`"
                )));
            }
        }
        if self
            .deployment_id
            .as_deref()
            .map(is_wildcard_scope)
            .unwrap_or(false)
        {
            return Err(MemoryError::InvalidConfig(
                "memory envelope key scope must not use wildcard `deployment_id`".to_string(),
            ));
        }
        // A wildcard department would collapse per-department DEKs back into one
        // shared key, defeating at-rest department separation (TAN-662).
        if self
            .org_unit
            .as_deref()
            .map(is_wildcard_scope)
            .unwrap_or(false)
        {
            return Err(MemoryError::InvalidConfig(
                "memory envelope key scope must not use wildcard `org_unit`".to_string(),
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryEnvelopeMetadata {
    pub key_scope: MemoryKeyScope,
    pub kek_id: String,
    pub kek_version: String,
    pub wrapped_dek: String,
    pub algorithm: String,
    pub encryption_context_hash: String,
    pub rotation_epoch: u64,
    pub policy_decision_id: String,
    pub audit_id: String,
}

impl MemoryEnvelopeMetadata {
    pub fn from_metadata(metadata: Option<&Value>) -> MemoryResult<Option<Self>> {
        let Some(value) = metadata.and_then(|value| value.get(MEMORY_ENVELOPE_METADATA_KEY)) else {
            return Ok(None);
        };
        serde_json::from_value(value.clone())
            .map(Some)
            .map_err(MemoryError::from)
    }

    pub fn attach_to_metadata(&self, metadata: Option<Value>) -> MemoryResult<Value> {
        let mut object = match metadata {
            Some(Value::Object(object)) => object,
            Some(_) => {
                return Err(MemoryError::InvalidConfig(
                    "memory envelope metadata requires object metadata".to_string(),
                ));
            }
            None => Map::new(),
        };
        object.insert(
            MEMORY_ENVELOPE_METADATA_KEY.to_string(),
            serde_json::to_value(self)?,
        );
        Ok(Value::Object(object))
    }

    fn validate_required_fields(&self) -> MemoryResult<()> {
        let required = [
            ("kek_id", self.kek_id.as_str()),
            ("kek_version", self.kek_version.as_str()),
            ("wrapped_dek", self.wrapped_dek.as_str()),
            ("algorithm", self.algorithm.as_str()),
            (
                "encryption_context_hash",
                self.encryption_context_hash.as_str(),
            ),
            ("policy_decision_id", self.policy_decision_id.as_str()),
            ("audit_id", self.audit_id.as_str()),
        ];
        for (field, value) in required {
            if value.trim().is_empty() {
                return Err(MemoryError::InvalidConfig(format!(
                    "hosted memory encryption metadata missing `{field}`"
                )));
            }
        }
        Ok(())
    }
}

pub fn hosted_memory_encryption_required() -> bool {
    std::env::var(HOSTED_ENCRYPTION_REQUIRED_ENV)
        .map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
        .unwrap_or(false)
}

pub fn validate_memory_envelope_for_write(
    tenant_scope: &MemoryTenantScope,
    metadata: Option<&Value>,
) -> MemoryResult<()> {
    validate_memory_envelope_for_required_write(
        tenant_scope,
        metadata,
        hosted_memory_encryption_required(),
    )
}

pub fn validate_memory_envelope_for_required_write(
    tenant_scope: &MemoryTenantScope,
    metadata: Option<&Value>,
    encryption_required: bool,
) -> MemoryResult<()> {
    let envelope = MemoryEnvelopeMetadata::from_metadata(metadata)?;
    let Some(envelope) = envelope else {
        if encryption_required {
            return Err(MemoryError::InvalidConfig(
                "hosted memory encryption requires memory_envelope metadata".to_string(),
            ));
        }
        return Ok(());
    };

    envelope.validate_required_fields()?;
    envelope.key_scope.validate_partitioned()?;
    if !envelope.key_scope.validates_against_tenant(tenant_scope) {
        return Err(MemoryError::InvalidConfig(
            "memory envelope key scope does not match tenant scope".to_string(),
        ));
    }
    // The key scope's department must match the row's owner_org_unit_id (TAN-662),
    // so a row can never be sealed under another department's DEK. Both `None`
    // (tenant-wide) is the matching case for undepartmented rows.
    let row_org_unit = crate::types::owner_org_unit_id_from_metadata(metadata);
    if envelope.key_scope.org_unit != row_org_unit {
        return Err(MemoryError::InvalidConfig(
            "memory envelope key scope org_unit does not match row owner_org_unit_id".to_string(),
        ));
    }
    validate_enterprise_source_binding(metadata, &envelope)
}

/// Percent-encode `%` and `/` so a caller-derived scope segment cannot inject a
/// structural delimiter (`/dept/`, `/source/`) into a `canonical_id` and collide
/// with a different scope (TAN-662). `%` is encoded first to keep the mapping
/// unambiguous (so a literal `%2F` cannot be confused with an encoded `/`).
fn encode_scope_segment(value: &str) -> String {
    value.replace('%', "%25").replace('/', "%2F")
}

fn is_wildcard_scope(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "" | "*" | "all" | "global" | "default"
    )
}

fn validate_enterprise_source_binding(
    metadata: Option<&Value>,
    envelope: &MemoryEnvelopeMetadata,
) -> MemoryResult<()> {
    let Some(binding) = metadata.and_then(|value| value.get("enterprise_source_binding")) else {
        return Ok(());
    };
    if let Some(binding_data_class) = binding.get("data_class").and_then(Value::as_str) {
        let expected = serde_json::to_value(envelope.key_scope.data_class)?
            .as_str()
            .unwrap_or_default()
            .to_string();
        if binding_data_class != expected {
            return Err(MemoryError::InvalidConfig(
                "memory envelope data class does not match enterprise source binding".to_string(),
            ));
        }
    }
    if let Some(binding_id) = binding.get("binding_id").and_then(Value::as_str) {
        if envelope.key_scope.source_binding_id.as_deref() != Some(binding_id) {
            return Err(MemoryError::InvalidConfig(
                "memory envelope source binding does not match enterprise source binding"
                    .to_string(),
            ));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tenant_scope() -> MemoryTenantScope {
        MemoryTenantScope {
            org_id: "acme".to_string(),
            workspace_id: "finance".to_string(),
            deployment_id: Some("prod".to_string()),
        }
    }

    fn envelope(data_class: DataClass) -> MemoryEnvelopeMetadata {
        MemoryEnvelopeMetadata {
            key_scope: MemoryKeyScope::new(
                &tenant_scope(),
                data_class,
                Some("drive-1".to_string()),
            ),
            kek_id: "projects/acme/locations/global/keyRings/memory/cryptoKeys/finance".to_string(),
            kek_version: "1".to_string(),
            wrapped_dek: "wrapped".to_string(),
            algorithm: "AES-256-GCM".to_string(),
            encryption_context_hash: "ctx-hash".to_string(),
            rotation_epoch: 0,
            policy_decision_id: "decision-1".to_string(),
            audit_id: "audit-1".to_string(),
        }
    }

    #[test]
    fn key_scope_canonical_id_includes_tenant_class_and_source() {
        let scope = MemoryKeyScope::new(
            &tenant_scope(),
            DataClass::FinancialRecord,
            Some("drive-1".to_string()),
        );
        assert_eq!(
            scope.canonical_id(),
            "tandem/memory/acme/finance/prod/financial_record/source/drive-1"
        );
    }

    #[test]
    fn key_scope_canonical_id_is_distinct_per_department() {
        // TAN-662: each department gets its own DEK scope, so canonical ids must
        // differ across departments in the same tenant + data class + source.
        let base = MemoryKeyScope::new(&tenant_scope(), DataClass::Internal, None);
        let sales = base
            .clone()
            .with_org_unit(Some("department/sales".to_string()));
        let engineering = base
            .clone()
            .with_org_unit(Some("department/engineering".to_string()));

        // The org-unit segment is percent-encoded so its internal `/` cannot be
        // confused with a structural delimiter.
        assert_eq!(
            sales.canonical_id(),
            "tandem/memory/acme/finance/prod/internal/dept/department%2Fsales"
        );
        assert_ne!(sales.canonical_id(), engineering.canonical_id());
        // The tenant-wide (no-department) scope is distinct from any department.
        assert_ne!(base.canonical_id(), sales.canonical_id());

        // With a source binding the department segment precedes the source.
        let sales_sourced = MemoryKeyScope::new(
            &tenant_scope(),
            DataClass::Internal,
            Some("drive-1".to_string()),
        )
        .with_org_unit(Some("department/sales".to_string()));
        assert_eq!(
            sales_sourced.canonical_id(),
            "tandem/memory/acme/finance/prod/internal/dept/department%2Fsales/source/drive-1"
        );
    }

    #[test]
    fn key_scope_canonical_id_resists_delimiter_injection() {
        // TAN-662 (review, P1): a department id that embeds the reserved
        // `/source/` delimiter must not collide with a distinct department+source
        // scope, and a literal `%2F` must not collide with an encoded `/`.
        let injected = MemoryKeyScope::new(&tenant_scope(), DataClass::Internal, None)
            .with_org_unit(Some("department/sales/source/drive-1".to_string()));
        let genuine = MemoryKeyScope::new(
            &tenant_scope(),
            DataClass::Internal,
            Some("drive-1".to_string()),
        )
        .with_org_unit(Some("department/sales".to_string()));
        assert_ne!(injected.canonical_id(), genuine.canonical_id());

        let literal_percent = MemoryKeyScope::new(&tenant_scope(), DataClass::Internal, None)
            .with_org_unit(Some("department%2Fsales".to_string()));
        let real_slash = MemoryKeyScope::new(&tenant_scope(), DataClass::Internal, None)
            .with_org_unit(Some("department/sales".to_string()));
        assert_ne!(literal_percent.canonical_id(), real_slash.canonical_id());
    }

    #[test]
    fn validation_accepts_matching_department_and_rejects_mismatch() {
        // Envelope key scope bound to `department/sales` and a row stamped the
        // same department validates…
        let mut envelope = envelope(DataClass::Internal);
        envelope.key_scope.source_binding_id = None;
        envelope.key_scope = envelope
            .key_scope
            .with_org_unit(Some("department/sales".to_string()));
        let metadata = envelope
            .attach_to_metadata(Some(serde_json::json!({
                "owner_org_unit_id": "department/sales"
            })))
            .expect("metadata");
        validate_memory_envelope_for_write(&tenant_scope(), Some(&metadata))
            .expect("matching department should validate");

        // …but a row owned by a different department is rejected: it must never be
        // sealed under another department's DEK.
        let mismatched = envelope
            .attach_to_metadata(Some(serde_json::json!({
                "owner_org_unit_id": "department/engineering"
            })))
            .expect("metadata");
        let err = validate_memory_envelope_for_write(&tenant_scope(), Some(&mismatched))
            .expect_err("department mismatch should fail");
        assert!(err
            .to_string()
            .contains("org_unit does not match row owner_org_unit_id"));
    }

    #[test]
    fn validation_rejects_wildcard_org_unit() {
        let mut envelope = envelope(DataClass::Internal);
        envelope.key_scope.source_binding_id = None;
        envelope.key_scope.org_unit = Some("*".to_string());
        let metadata = envelope.attach_to_metadata(None).expect("metadata");

        let err = validate_memory_envelope_for_write(&tenant_scope(), Some(&metadata))
            .expect_err("wildcard org_unit should fail");
        assert!(err.to_string().contains("wildcard `org_unit`"));
    }

    #[test]
    fn envelope_round_trips_through_metadata() {
        let envelope = envelope(DataClass::FinancialRecord);
        let metadata = envelope
            .attach_to_metadata(Some(serde_json::json!({"kind": "test"})))
            .expect("attach metadata");
        assert_eq!(
            MemoryEnvelopeMetadata::from_metadata(Some(&metadata))
                .expect("parse metadata")
                .as_ref(),
            Some(&envelope)
        );
    }

    #[test]
    fn validation_rejects_tenant_mismatch() {
        let mut envelope = envelope(DataClass::FinancialRecord);
        envelope.key_scope.workspace_id = "hr".to_string();
        let metadata = envelope.attach_to_metadata(None).expect("metadata");

        let err = validate_memory_envelope_for_write(&tenant_scope(), Some(&metadata))
            .expect_err("tenant mismatch should fail");
        assert!(err
            .to_string()
            .contains("key scope does not match tenant scope"));
    }

    #[test]
    fn validation_rejects_wildcard_key_scope() {
        let mut envelope = envelope(DataClass::FinancialRecord);
        envelope.key_scope.org_id = "*".to_string();
        let metadata = envelope.attach_to_metadata(None).expect("metadata");

        let err = validate_memory_envelope_for_write(&tenant_scope(), Some(&metadata))
            .expect_err("wildcard key scope should fail");
        assert!(err.to_string().contains("wildcard `org_id`"));
    }

    #[test]
    fn validation_rejects_source_binding_mismatch() {
        let metadata = envelope(DataClass::FinancialRecord)
            .attach_to_metadata(Some(serde_json::json!({
                "enterprise_source_binding": {
                    "binding_id": "other-drive",
                    "data_class": "financial_record"
                }
            })))
            .expect("metadata");

        let err = validate_memory_envelope_for_write(&tenant_scope(), Some(&metadata))
            .expect_err("source binding mismatch should fail");
        assert!(err.to_string().contains("source binding does not match"));
    }

    #[test]
    fn hosted_required_mode_rejects_missing_envelope() {
        let err = validate_memory_envelope_for_required_write(&tenant_scope(), None, true)
            .expect_err("hosted required mode should fail without metadata");

        assert!(err
            .to_string()
            .contains("requires memory_envelope metadata"));
    }

    #[test]
    fn local_mode_allows_missing_envelope() {
        validate_memory_envelope_for_required_write(&tenant_scope(), None, false)
            .expect("local mode should allow missing envelope metadata");
    }
}