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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Shared application-key hiding and value-protection composition.
use crate::internal_core::key::validate_canonical_key;
use crate::internal_core::value::{
Compression, Encryption, ItemValue, JsonValue, Value, ValueCodec, ValueKeyring,
};
use crate::internal_core::{
ClientRootKey, DataProtectionKey, ItemId, KeyFormat, KeyType, Result, TypedKey,
transport::RequestBudget,
};
use crate::internal_value::Value as StructuredValue;
/// Reusable keyed transformation shared by language-specific client layers.
pub struct DataProtection {
key: ClientRootKey,
key_spec: KeyType,
key_format: KeyFormat,
codec: ValueCodec,
}
impl DataProtection {
/// Creates mandatory application-key hiding and value encryption.
///
/// # Arguments
///
/// * `key` - Application-managed master secret.
/// * `compression` - Optional compression applied before encryption.
///
/// # Returns
///
/// A reusable transformation with domain-separated key and value subkeys.
///
/// # Errors
///
/// Returns an error when the compression settings are invalid.
pub fn new(key: DataProtectionKey, compression: Compression) -> Result<Self> {
Self::with_key_spec(key, KeyType::Bytes, compression)
}
/// Creates mandatory protection with an explicit formatted key spec.
pub fn with_key_spec(
key: ClientRootKey,
key_spec: KeyType,
compression: Compression,
) -> Result<Self> {
if key.is_zero() {
return Err(crate::internal_core::Error::configuration(
"client_root_key",
"must not be all zero when value protection is enabled",
));
}
let codec =
ValueCodec::protected(&key, compression)?.allow_read_profile(Encryption::Compact);
Ok(Self {
key,
key_spec,
key_format: KeyFormat::NamespaceHash,
codec,
})
}
/// Creates protection with a separate Item ID root and value-key keyring.
///
/// The root key remains solely responsible for deterministic application
/// key/Item ID derivation. The supplied keyring owns value-key rotation:
/// readers accept every inserted ID while writes use its active ID.
pub fn with_keyring(
key: ClientRootKey,
keyring: ValueKeyring,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
Self::with_keyring_and_key_spec_and_format(
key,
keyring,
KeyType::Bytes,
KeyFormat::NamespaceHash,
compression,
encryption,
)
}
/// Creates protected values with an independent Item-ID root and value
/// keyring.
///
/// An all-zero [`ClientRootKey`] is valid here and deliberately produces
/// publicly derivable Item IDs. The value keyring remains the sole source
/// of value-protection keys; it is never derived from the Item-ID root.
pub fn with_item_id_root_and_keyring(
item_id_root: ClientRootKey,
keyring: ValueKeyring,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
Self::with_keyring(item_id_root, keyring, compression, encryption)
}
/// Creates rotating value protection with an explicit formatted key spec.
pub fn with_keyring_and_key_spec(
key: ClientRootKey,
keyring: ValueKeyring,
key_spec: KeyType,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
Self::with_keyring_and_key_spec_and_format(
key,
keyring,
key_spec,
KeyFormat::NamespaceHash,
compression,
encryption,
)
}
/// Creates rotating value protection with an explicit key type and
/// Item ID mapping profile.
pub fn with_keyring_and_key_spec_and_format(
key: ClientRootKey,
keyring: ValueKeyring,
key_spec: KeyType,
key_format: KeyFormat,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
crate::internal_core::KeySpace::with_format(key_spec, key_format)
.validate()
.map_err(crate::internal_core::Error::from)?;
let codec = match encryption {
Encryption::Unprotected => ValueCodec::compressed(compression)?,
Encryption::Compact | Encryption::Robust => {
let alternate = match encryption {
Encryption::Compact => Encryption::Robust,
Encryption::Robust => Encryption::Compact,
Encryption::Unprotected => unreachable!(),
};
ValueCodec::with_keyring(keyring, compression, encryption)?
.allow_read_profile(alternate)
}
};
Ok(Self {
key,
key_spec,
key_format,
codec,
})
}
/// Applies one aggregate byte budget to value protection work.
///
/// The budget is retained by this transformation and shared by envelope,
/// decrypted, decompressed, and structured-codec allocations. Protected
/// network clients install their own connection budget automatically;
/// standalone callers can use this method to apply the same bound.
pub fn with_budget(mut self, budget: RequestBudget) -> Self {
self.codec = self.codec.with_budget(budget);
self
}
/// Creates the default unprotected formatted client.
///
/// The all-zero root still participates in namespace-bound Item ID
/// derivation. Only value protection is disabled.
pub fn unprotected(key_spec: KeyType, compression: Compression) -> Result<Self> {
let codec = ValueCodec::compressed(compression)?;
Ok(Self {
key: ClientRootKey::zero(),
key_spec,
key_format: KeyFormat::NamespaceHash,
codec,
})
}
/// Creates protection with an explicit authenticated-encryption profile.
///
/// # Arguments
///
/// * `key` - Application-managed data protection key.
/// * `compression` - Compression policy applied before encryption.
/// * `encryption` - Unprotected, Compact, or Robust profile.
///
/// # Returns
///
/// A reusable application-key and value transformation.
///
/// # Errors
///
/// Returns an error for an invalid compression setting or protected profile
/// configuration.
pub fn with_profile(
key: DataProtectionKey,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
Self::with_profile_and_key_spec(key, KeyType::Bytes, compression, encryption)
}
/// Creates protection with an explicit key spec and encryption profile.
pub fn with_profile_and_key_spec(
key: ClientRootKey,
key_spec: KeyType,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
if key.is_zero() && encryption != Encryption::Unprotected {
return Err(crate::internal_core::Error::configuration(
"client_root_key",
"must not be all zero when value protection is enabled",
));
}
let codec = match encryption {
Encryption::Unprotected => ValueCodec::compressed(compression)?,
Encryption::Compact | Encryption::Robust => {
let alternate = match encryption {
Encryption::Compact => Encryption::Robust,
Encryption::Robust => Encryption::Compact,
Encryption::Unprotected => unreachable!(),
};
ValueCodec::protected_with_profile(&key, compression, encryption)?
.allow_read_profile(alternate)
}
};
Ok(Self {
key,
key_spec,
key_format: KeyFormat::NamespaceHash,
codec,
})
}
/// Creates a protection facade with an explicit key type and mapping
/// profile. Mapping and value protection remain independent.
pub fn with_profile_and_key_type_and_format(
key: ClientRootKey,
key_type: crate::internal_core::KeyType,
key_format: KeyFormat,
compression: Compression,
encryption: Encryption,
) -> Result<Self> {
crate::internal_core::KeySpace::with_format(key_type, key_format)
.validate()
.map_err(crate::internal_core::Error::from)?;
if key.is_zero() && encryption != Encryption::Unprotected {
return Err(crate::internal_core::Error::configuration(
"client_root_key",
"must not be all zero when value protection is enabled",
));
}
let codec = match encryption {
Encryption::Unprotected => ValueCodec::compressed(compression)?,
Encryption::Compact | Encryption::Robust => {
ValueCodec::protected_with_profile(&key, compression, encryption)?
}
};
Ok(Self {
key,
key_spec: key_type,
key_format,
codec,
})
}
/// Returns the compatibility key-type selector.
///
/// `TypedKey` operations infer their type per call under the v1 contract;
/// this accessor remains for callers migrating from the pre-contract
/// `key_spec` setting.
pub const fn key_spec(&self) -> KeyType {
self.key_spec
}
/// Returns the configured compatibility key-type selector.
///
/// The v1 contract infers `TypedKey` from each operation. This accessor is
/// retained for callers migrating from the pre-contract `key_spec` name;
/// it does not change the canonical-key ABI boundary.
pub const fn key_type(&self) -> KeyType {
self.key_spec
}
/// Returns the configured Item ID mapping profile.
pub const fn key_format(&self) -> KeyFormat {
self.key_format
}
/// Derives a namespace-bound Item ID for one typed key.
///
/// The `TypedKey` variant is inferred by the operation. The compatibility
/// `key_spec` setting is not a namespace policy and is not applied here.
/// Returns the configured value resource limits.
pub fn value_limits(&self) -> crate::internal_core::value::ValueLimits {
self.codec.limits()
}
/// Returns the aggregate byte budget shared by transport and value work.
pub fn request_budget(&self) -> RequestBudget {
self.codec.budget().clone()
}
/// Derives a namespace-bound Item ID for a typed portable key.
pub fn item_id_in_namespace(
&self,
namespace_id: u64,
key: impl Into<TypedKey>,
) -> Result<ItemId> {
let key = key.into();
self.key
.derive_item_id_in_namespace_with_format(namespace_id, self.key_format, key)
.map_err(Into::into)
}
/// Derives an Item ID from canonical key bytes after validating one item.
pub fn item_id_from_canonical_key(
&self,
namespace_id: u64,
canonical_key: &[u8],
) -> Result<ItemId> {
let canonical_key = validate_canonical_key(canonical_key)?;
self.key
.derive_item_id_from_validated_canonical_key(
namespace_id,
self.key_format,
canonical_key,
)
.map_err(Into::into)
}
/// Derives an Item ID from canonical key bytes without applying a configured
/// [`KeyType`].
///
/// This is the boundary for the low-level native ABI. The canonical CBOR
/// item carries its own `Integer`, `Text`, or `Bytes` discriminator; typed
/// high-level clients should use [`Self::item_id_from_canonical_key`]
/// instead so one keyspace cannot accidentally mix types.
#[cfg(feature = "ffi")]
pub(crate) fn item_id_from_canonical_key_unchecked(
&self,
namespace_id: u64,
canonical_key: &[u8],
) -> Result<ItemId> {
let canonical_key = validate_canonical_key(canonical_key)?;
self.key
.derive_item_id_from_validated_canonical_key(
namespace_id,
self.key_format,
canonical_key,
)
.map_err(Into::into)
}
/// Explicit compatibility path for the pre-contract byte-key mapping.
pub fn legacy_item_id(&self, application_key: impl AsRef<[u8]>) -> ItemId {
self.key.derive_item_id(application_key)
}
/// Legacy byte-key convenience retained for source compatibility.
///
/// New mapped operations should use [`Self::item_id_in_namespace`].
#[deprecated(note = "use item_id_in_namespace or legacy_item_id explicitly")]
pub fn item_id(&self, application_key: impl AsRef<[u8]>) -> ItemId {
self.legacy_item_id(application_key)
}
/// Resolves a typed key through the explicit public preserve-or-hash
/// profile. The method name keeps this escape hatch distinct from mapped
/// NamespaceHash operations.
pub fn public_key_or_hash_in_namespace(
&self,
namespace_id: u64,
key: impl Into<TypedKey>,
) -> Result<ItemId> {
let key = key.into();
self.key
.derive_item_id_in_namespace_with_format(namespace_id, KeyFormat::PublicKeyOrHash, key)
.map_err(Into::into)
}
/// Serializes and protects one core logical value.
///
/// # Arguments
///
/// * `item_id` - Exact item ID bound into authenticated encryption.
/// * `value` - Raw or logical JSON value to encode.
///
/// # Returns
///
/// A complete value-format container for opaque storage.
///
/// # Errors
///
/// Returns an error for invalid logical values, size-limit violations, compression failures,
/// entropy failures, or encryption failures.
pub fn encode(&self, item_id: ItemId, value: Value) -> Result<ItemValue> {
self.encode_in_namespace(1, item_id, value)
}
/// Serializes and protects a value while binding its namespace into AAD.
pub fn encode_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
value: Value,
) -> Result<ItemValue> {
self.codec
.encode_in_namespace(namespace_id, item_id, value)
.map_err(Into::into)
}
/// Serializes one canonical JSON helper value as selector-0
/// `OpaqueBytes`.
pub fn encode_json_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
value: JsonValue,
) -> Result<ItemValue> {
self.codec
.seal_json_in_namespace(namespace_id, item_id, value)
.map_err(Into::into)
}
/// Serializes and protects one canonical StructuredValue-CBOR-v1 value.
///
/// The structured ABI accepts the value-model algebra directly; opaque
/// bytes and JSON convenience views are intentionally separate APIs.
pub fn encode_structured_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
value: &StructuredValue,
) -> Result<ItemValue> {
self.codec
.seal_structured_in_namespace(namespace_id, item_id, value)
.map_err(Into::into)
}
/// Serializes and protects a StructuredValue-CBOR-v1 value while binding its namespace.
pub fn seal_structured_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
value: &StructuredValue,
) -> Result<ItemValue> {
self.encode_structured_in_namespace(namespace_id, item_id, value)
}
/// Encodes one StructuredValue-CBOR-v1 payload with the configured
/// resource limits.
pub fn encode_structured_cbor(&self, value: &StructuredValue) -> Result<Vec<u8>> {
self.codec.encode_structured_cbor(value).map_err(Into::into)
}
/// Decodes and protects one complete StructuredValue-CBOR-v1 payload
/// while retaining parser permits through envelope encoding.
pub fn seal_structured_cbor_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
payload: &[u8],
) -> Result<ItemValue> {
self.codec
.seal_structured_cbor_in_namespace(namespace_id, item_id, payload)
.map_err(Into::into)
}
/// Authenticates and decodes one stored value into the core logical model.
///
/// # Arguments
///
/// * `item_id` - Exact item ID expected by authenticated encryption.
/// * `encoded` - Complete value-format container returned by the raw client.
///
/// # Returns
///
/// The decoded Raw or logical JSON value.
///
/// # Errors
///
/// Returns an error when the value is malformed, unsupported, oversized, unauthenticated, or
/// cannot be decompressed or deserialized.
pub fn decode(&self, item_id: ItemId, encoded: ItemValue) -> Result<Value> {
self.decode_in_namespace(1, item_id, encoded)
}
/// Authenticates and decodes a value while binding its namespace into AAD.
pub fn decode_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
encoded: ItemValue,
) -> Result<Value> {
self.codec
.decode_in_namespace(namespace_id, item_id, encoded)
.map_err(Into::into)
}
/// Authenticates and decodes a canonical JSON helper value stored as
/// selector-0 `OpaqueBytes`.
pub fn decode_json_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
encoded: ItemValue,
) -> Result<JsonValue> {
self.codec
.open_json_in_namespace(namespace_id, item_id, encoded)
.map_err(Into::into)
}
/// Authenticates and decodes one canonical StructuredValue-CBOR-v1 value.
pub fn decode_structured_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
encoded: ItemValue,
) -> Result<StructuredValue> {
self.codec
.open_structured_in_namespace(namespace_id, item_id, encoded)
.map_err(Into::into)
}
/// Authenticates and decodes one StructuredValue-CBOR-v1 value.
pub fn open_structured_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
encoded: ItemValue,
) -> Result<StructuredValue> {
self.decode_structured_in_namespace(namespace_id, item_id, encoded)
}
/// Encrypts a borrowed plaintext value and binds it to its item ID.
///
/// # Arguments
///
/// * `item_id` - Item ID derived for the value's application key.
/// * `plaintext` - Exact application value bytes.
///
/// # Returns
///
/// Opaque encrypted bytes containing the client-owned transformation envelope.
///
/// # Errors
///
/// Returns an error for oversized values, entropy failures, compression failures, or
/// encryption failures.
pub fn seal(&self, item_id: ItemId, plaintext: &[u8]) -> Result<ItemValue> {
self.seal_in_namespace(1, item_id, plaintext)
}
/// Encrypts bytes while binding their namespace and Item ID into AAD.
pub fn seal_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
plaintext: &[u8],
) -> Result<ItemValue> {
self.encode_in_namespace(namespace_id, item_id, Value::Raw(plaintext.to_vec()))
}
/// Encrypts an owned plaintext value while reusing its allocation when practical.
///
/// # Arguments
///
/// * `item_id` - Item ID derived for the value's application key.
/// * `plaintext` - Owned application value bytes.
///
/// # Returns
///
/// Opaque encrypted bytes containing the client-owned transformation envelope.
///
/// # Errors
///
/// Returns an error for oversized values, entropy failures, compression failures, or
/// encryption failures.
pub fn seal_owned(&self, item_id: ItemId, plaintext: Vec<u8>) -> Result<ItemValue> {
self.seal_owned_in_namespace(1, item_id, plaintext)
}
/// Encrypts owned bytes while binding their namespace and Item ID into AAD.
pub fn seal_owned_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
plaintext: Vec<u8>,
) -> Result<ItemValue> {
self.encode_in_namespace(namespace_id, item_id, Value::Raw(plaintext))
}
/// Authenticates, decrypts, and optionally decompresses a stored value.
///
/// # Arguments
///
/// * `item_id` - Item ID used as authenticated data.
/// * `encoded` - Exact encrypted value returned by the raw client.
///
/// # Returns
///
/// The original plaintext application value.
///
/// # Errors
///
/// Returns an error when the value is malformed, oversized, cannot be authenticated, or
/// cannot be decompressed.
pub fn open(&self, item_id: ItemId, encoded: ItemValue) -> Result<Vec<u8>> {
self.open_in_namespace(1, item_id, encoded)
}
/// Authenticates and opens bytes while binding their namespace and Item ID into AAD.
pub fn open_in_namespace(
&self,
namespace_id: u64,
item_id: ItemId,
encoded: ItemValue,
) -> Result<Vec<u8>> {
match self.decode_in_namespace(namespace_id, item_id, encoded)? {
Value::Raw(bytes) => Ok(bytes),
Value::Json(_) => Err(crate::internal_core::value::Error::ExpectedRawValue.into()),
}
}
/// Validates and passes through a caller-owned version-0 envelope.
pub fn pass_through_v0(&self, bytes: Vec<u8>) -> Result<ItemValue> {
self.codec.pass_through_v0(bytes).map_err(Into::into)
}
/// Opens a caller-owned version-0 envelope without interpreting its body.
pub fn open_v0(&self, encoded: ItemValue) -> Result<Vec<u8>> {
self.codec.open_v0(encoded).map_err(Into::into)
}
}