Repository navigation
Expand file tree
/
Copy pathcipher.rs
More file actions
1908 lines (1806 loc) · 85.4 KB
/
Copy pathcipher.rs
File metadata and controls
1908 lines (1806 loc) · 85.4 KB
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Implementation of [`StackCipher`]. For usage, start at the crate docs; this
//! module documents the internals.
//!
//! `StackCipher` is scoped to one ZeroKMS client; a [`KeysetCipher`] — the
//! cipher bound to one of that client's keysets — seals values whose
//! per-leaf keys are ZeroKMS data keys, minted under that keyset, rather
//! than one fixed key. The value side is vitaminc's: a value describes
//! itself once ([`Encrypt`]), vitaminc plans it into a tree of pending
//! leaves, each with its tagged plaintext and the AAD its place derives,
//! and a bytes-only [`Cipher`] seals and opens one leaf at a time. The
//! result is a ciphertext tree ([`StackCipherText`], the analog of
//! `AesCipherText`) whose leaves ([`SealedValue`]) each carry the ZeroKMS
//! metadata for their own data key — the keyset it was minted under
//! included, which is why decrypting needs no keyset named and lives on the
//! client-scoped `StackCipher`.
//!
//! ## Batching the key fetch
//!
//! Data-key generation/retrieval is an async ZeroKMS round-trip, and each
//! leaf needs its own key, so the keys are fetched for the whole tree
//! before any leaf is sealed or opened. The AES work stays in vitaminc's
//! synchronous walk:
//!
//! * **Encrypt** — [`PendingStackCipherText::plan`] walks the value into
//! vitaminc's pending tree and does no I/O. A single
//! [`PendingStackCipherText::seal`] (or the [`KeysetCipher::encrypt_tree`]
//! convenience) then batches **one** `generate_keys` call for the whole
//! tree, under the handle's keyset, and seals every leaf through
//! `MintedKeys`, the sealing half of this crate's [`Cipher`], one key per
//! leaf in walk order.
//! * **Decrypt** — [`StackCipher::decrypt`] batches **one** `retrieve_keys`
//! call per keyset the leaves were sealed under and zips each key onto
//! its leaf. vitaminc's [`decrypt`](vitaminc_aead::decrypt) then opens
//! every leaf through `BoundKeys`, the opening half, and walks the opened
//! tree into the value's [`Decrypt`] sink.
//!
//! Neither half is vitaminc's `AsyncCipher`. Its `seal_many` batches the
//! leaves of one document, but a ZeroKMS request names the descriptor of
//! the context the whole tree is sealed under, which a leaf's derived AAD
//! does not carry, and the target layer merges the key requests of many
//! documents (the fields of a record, the rows of a column) into one call
//! (RFC 0002). So the fetch is the target layer's
//! [`Pending`](crate::target::Pending), and the cipher vitaminc drives is
//! the synchronous one.
//!
//! ## AAD derivation
//!
//! vitaminc derives each leaf's AAD from the caller's, on both sides, with
//! the same domain-separated derivations every vitaminc cipher gets, so the
//! container *shape* is authenticated:
//!
//! * sequence elements are sealed under [`Context::for_sequence_element`];
//! * map values under [`Context::for_map_entry`] of their cleartext key (so
//! swapping or renaming keys fails decryption);
//! * empty sequences/maps under [`Context::for_empty_sequence`] /
//! [`Context::for_empty_map`], each sealing an *empty* plaintext,
//! verified as empty on open. An absent value (`None`) is a null leaf like
//! any other scalar.
//!
//! This crate binds its own envelope on top of that, per leaf (below).
//!
//! ## Leaf crypto and wire format
//!
//! Each leaf ([`SealedValue`]) stores the ZeroKMS keyset id, `iv` and key
//! `tag` — enough to retrieve the data key — plus a vitaminc
//! [`LocalCipherText`] sealed under that key by
//! [`vitaminc_encrypt::Aes256Cipher`] (AES-256-GCM via vitaminc's backend:
//! `aws-lc-rs` on native, RustCrypto on wasm32; vitaminc's own random nonce
//! and versioned leaf layout). The leaf AAD is the labelled derivation
//! `leaf_aad` (private):
//! `PAE("stack-encrypt/leaf", version, keyset_id, derived_aad, tag)`, with
//! [`SealedValue::FORMAT_VERSION`] — the version byte that prefixes the
//! leaf's frozen byte encoding ([`SealedValue::to_bytes`]) — and the keyset
//! id bound under the tag, so a stored leaf relabelled with a different
//! version byte fails verification instead of selecting different parsing
//! rules, and one re-pointed at another keyset fails instead of asking that
//! keyset for a key it never minted. The `tag` is always bound, so the
//! ciphertext is cryptographically tied to its ZeroKMS data key (key
//! binding); a caller AAD (e.g. a [`ContextTag`](vitaminc_aead::ContextTag))
//! adds a further binding layer.
//! Every data key is requested under a ZeroKMS **descriptor**: the context
//! the tree is sealed under, rendered as a string by
//! [`Descriptor`]. ZeroKMS HMACs the descriptor into the
//! key `tag` and demands the same descriptor to re-derive the key, so the
//! binding the leaf AAD makes locally is enforced at ZeroKMS as well, and
//! the descriptor is what ZeroKMS logs per retrieval. The lock context on
//! each request is empty.
//!
//! This is a fresh framing and is intentionally **not** byte-compatible with
//! `cipherstash-client`'s `EncryptedRecord` AAD (a raw `descriptor || tag`
//! concatenation). A compatibility module can be added later to read existing
//! records as customers of `cipherstash-client` migrate.
use std::cell::RefCell;
use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use stack_kms::{DataKey, DataKeySource, DataKeyWithTag, IdentifiedBy, IndexKeySource};
#[cfg(feature = "http")]
use stack_kms::{EnvKeyProvider, StackKms, StackKmsBuilder};
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
use stack_kms::{FallbackKeyProvider, KeyProvider, KeyProviderError, ProfileStore};
use uuid::Uuid;
use vitaminc_aead::seal::seal_all;
use vitaminc_aead::{
Cipher, CipherText, Context, DecodeError, Decrypt, DecryptError, Encrypt, IntoAad, IntoContext,
LocalCipherText, Node, Pending, Unspecified,
};
use vitaminc_encrypt::{Aes256Cipher, Key as AesKey};
use vitaminc_protected::Protected;
use crate::keyset::{KeysetCache, KeysetCipher, KeysetState, Lookup, DEFAULT_NAME_TTL};
use crate::Descriptor;
/// The recursive ciphertext container produced by [`StackCipher`]: vitaminc's
/// ciphertext tree ([`Node`]) over [`SealedValue`] leaves. Its shape
/// mirrors the encrypted plaintext: a scalar, `None` included, yields
/// `Single`, a `Vec` yields `Sequence` (or `EmptySequence`), a `HashMap` or
/// struct yields `Map` (or `EmptyMap`). Map keys are stored in the clear but
/// bound into their value's AAD. A passthrough subtree travels in the clear
/// as a [`PassthroughFrame`](vitaminc_aead::PassthroughFrame): the subtree's
/// frame bytes.
pub type StackCipherText = Node<SealedValue>;
/// Errors from sealing or opening a [`StackCipherText`].
///
/// Every variant has a `stack_encrypt::` miette code, or forwards the code
/// of the error it carries ([`Kms`](Self::Kms), [`Term`](Self::Term),
/// [`Plan`](Self::Plan)); its structured fields are its
/// [`ErrorPayload`](crate::ErrorPayload). No message carries a context's
/// descriptor or another library's text (see the rule on
/// [`ErrorPayload`](crate::ErrorPayload)).
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[non_exhaustive]
pub enum Error {
/// A ZeroKMS data-key or keyset operation failed. Transparent: the
/// message, code and help are the [`stack_kms::Error`]'s, so a caller
/// across a binding sees `stack_kms::keyset_not_found` itself.
#[error(transparent)]
#[diagnostic(transparent)]
Kms(#[from] stack_kms::Error),
/// AEAD sealing/opening failed, or the ciphertext tree is malformed. On
/// decrypt this is the expected outcome for a wrong key, wrong AAD, or
/// tampered ciphertext. A ciphertext that opens but holds a value of
/// another type is [`OpenedType`](Self::OpenedType), not this.
#[error("AEAD operation failed (wrong key, AAD mismatch, or malformed ciphertext)")]
#[diagnostic(
code(stack_encrypt::aead),
help("Open the value under the context it was sealed with. If the context is right, the ciphertext is damaged or was altered.")
)]
Aead,
/// A ciphertext opened, so every leaf in it is authentic and unaltered,
/// but it holds a value of another type or shape than the one it was
/// opened as: text opened as an integer, an integer too wide for the
/// target, a map without a field the target needs. The value was sealed
/// as another type or shape, or arrived as part of one, and is not
/// tampered with.
///
/// A container's membership and order are not authenticated, by design:
/// a stored sequence is a set of rows and a stored map a row's columns,
/// and a database returns rows in any order and a query selects some
/// columns, not all. So a map missing a field, or a sequence of another
/// length, is a shape the target refuses, not a failed authentication.
///
/// `expected` names what the target reads (a vitaminc kind such as
/// `i32`, or the Rust type). The message never names what the value
/// held, and never a map key.
#[error("the ciphertext opened, but it does not hold a value of the type {expected}")]
#[diagnostic(
code(stack_encrypt::opened_type),
help("Open the value as the type it was sealed as. The ciphertext is authentic: it was sealed as another type, not altered.")
)]
OpenedType { expected: &'static str },
/// The database answered a JSON index read with an entry other than
/// the one the read asked for: `->` returned the entry of another path,
/// or the sealed root in place of a node, or a subtree walk returned a
/// row that is not where the walk's key says its rows are (a node of
/// another path, a row out of its place in the document, a row whose
/// parent is not among the rows, rows that stop before a node's
/// subtree is complete, one entry returned twice, or rows of two
/// documents). Refused by the client, which
/// derived the path's selector itself; see
/// [`JsonSelector::open`](crate::json::JsonSelector::open) and
/// [`JsonSubtreeKey::open`](crate::json::JsonSubtreeKey::open).
///
/// Not [`Aead`](Self::Aead): every entry may be genuine, sealed in
/// this column and this row. Not [`OpenedType`](Self::OpenedType)
/// either: the entry is not of an unexpected shape, it is the answer to
/// another question. A database that answers the query it was sent
/// never returns one, so this says the rows were tampered with or the
/// query that produced them was not the one the key or selector keyed.
///
/// Which row a value belongs to is not checked: an entry from another
/// row of the same column at the same path, returned with that row's
/// header, opens. A value is bound to its row only when its context
/// names the row. A row binding protects the ciphertext; selectors and
/// terms still derive under the query scopes alone.
///
/// `expected` names what the read expected, never what the entry held.
#[error("the database returned a JSON index entry other than {expected}")]
#[diagnostic(
code(stack_encrypt::json_wrong_entry),
help("The entry opened, but it is not the one the query asked for. A database that answers the query it was sent never returns one: check that the rows came from the query the selector or subtree key was derived for, and treat them as tampered with if they did.")
)]
JsonWrongEntry { expected: &'static str },
/// A JSON subtree read with a wildcard found an array longer than the
/// bound the wildcard was expanded to: the probe the read sent for the
/// element at `bound` named a node. The read fails rather than return
/// part of the answer; see
/// [`KeysetCipher::json_subtree_key_with_bound`](crate::KeysetCipher::json_subtree_key_with_bound).
///
/// Names the bound and nothing of the path, whose key names can be
/// customer data.
#[error("a JSON array at the wildcard is longer than the read's bound of {bound}")]
#[diagnostic(
code(stack_encrypt::json_wildcard_truncated),
help("A wildcard read expands to the positions below its bound and fails when an array is longer, so it never returns part of the answer. Derive the key with a larger bound (`json_subtree_key_with_bound`), or read the array itself.")
)]
JsonWildcardTruncated { bound: u32 },
/// The JSON index entry `->` returned did not open on its own. An entry
/// opens alone only if it is a scalar, an empty container or the sealed
/// root: a container with children is sealed over its children's
/// ciphertexts, which `->` does not return. So the path named a container
/// with children, which is read with a subtree read
/// ([`KeysetCipher::json_subtree_key`](crate::KeysetCipher::json_subtree_key)),
/// or the entry was altered, or sealed under another key or column. The
/// client cannot tell which before the entry opens, so this names both
/// and claims neither.
#[error("the JSON index entry at the path did not open on its own")]
#[diagnostic(
code(stack_encrypt::json_not_a_leaf),
help("If the path names an object or an array with members, read it with a subtree read (`json_subtree_key`): `->` returns one entry, and a container's entry is sealed over its children. If the path names a scalar, the entry was altered, or sealed under another key or column.")
)]
JsonNotALeaf,
/// ZeroKMS returned a different number of keys than were requested.
#[error("expected {expected} data keys from ZeroKMS but received {received}")]
#[diagnostic(code(stack_encrypt::key_count_mismatch))]
KeyCountMismatch { expected: usize, received: usize },
/// A context rendered to a descriptor longer than ZeroKMS can bind
/// ([`Descriptor::MAX_LEN`]). Raised before any request is sent, so no
/// key is minted or retrieved for the batch.
#[error(
"context renders to a {len}-byte ZeroKMS descriptor; the limit is {} bytes",
Descriptor::MAX_LEN
)]
#[diagnostic(
code(stack_encrypt::descriptor_too_long),
help(
"ZeroKMS binds a descriptor of at most {} bytes. Shorten the context: fewer parts, shorter labels, or an id in place of a long name.",
Descriptor::MAX_LEN
)
)]
DescriptorTooLong { len: usize },
/// Building a ZeroKMS client from the environment failed: credentials or
/// client key missing or malformed.
///
/// Boxed rather than naming `stack_encrypt::kms::StackKmsBuilderError` directly:
/// that type only exists with `http`, and a variant whose presence tracks
/// a feature is not additive — feature unification elsewhere in the graph
/// would then change this enum's shape under a downstream match.
///
/// The box holds whatever built it: this crate fills it with
/// `StackKmsBuilderError`, whose message obeys the rule on
/// [`ErrorPayload`](crate::ErrorPayload), and so may be shown here.
///
/// Its payload is the builder error's (the variable at fault, say). Its
/// code stays this one; the builder error's own is on the source.
#[error("could not build a ZeroKMS client from the environment: {0}")]
#[diagnostic(
code(stack_encrypt::config),
help("The message says which setting failed. Check `CS_WORKSPACE_CRN`, `CS_CLIENT_ID`, `CS_CLIENT_KEY`, `CS_CLIENT_ACCESS_KEY` and `CS_ZEROKMS_HOST`, or log in with `stash auth login`.")
)]
Config(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
/// An index term failed to derive.
#[error(transparent)]
#[diagnostic(transparent)]
Term(#[from] crate::sem::TermError),
/// A third-party [`EncryptFrom`](crate::target::EncryptFrom) /
/// [`DecryptInto`](crate::target::DecryptInto) implementation failed
/// for a reason of its own.
///
/// Its message is the implementation's, shown as given: an
/// implementation that fills this slot writes its message under the
/// rule on [`ErrorPayload`](crate::ErrorPayload), naming what it refused
/// and never a byte of the value or the ciphertext.
#[error(transparent)]
#[diagnostic(code(stack_encrypt::other))]
Other(Box<dyn std::error::Error + Send + Sync + 'static>),
/// A [`transcode::Visitor`](crate::target::transcode::Visitor) was handed
/// an encrypted output shape its destination does not accept: a scalar
/// destination offered a sequence, say. Raised by the visitor's default
/// methods, so a destination only has to describe the shapes it stores.
/// Never a data error: the output was produced correctly, the
/// destination just has nowhere to put it.
#[error("destination does not support this encrypted output shape")]
#[diagnostic(code(stack_encrypt::unsupported_shape))]
UnsupportedShape,
/// A record carrying its context in storage (`#[stash(context_field)]`)
/// was opened with an expected context that differs from the stored
/// one. Refused before any key is retrieved.
///
/// `stored` is the stored context's descriptor, rendered as ZeroKMS
/// would log it, for a caller in this process. The message gives only
/// its length and number of parts: a stored context can be built from
/// a record field, so its descriptor can be customer data.
#[error(
"stored context ({} bytes in {} parts) does not match the expected context",
stored.len(),
descriptor_parts(stored)
)]
#[diagnostic(
code(stack_encrypt::context_mismatch),
help("The record was stored under another context than the one it is opened with. Open it with the context it was stored under.")
)]
ContextMismatch { stored: Descriptor },
/// A [`Pending`](crate::target::Pending) fulfilment's requests and
/// responses did not line up: it drew more responses — or a different
/// kind — than its requests asked for, or left some of them unconsumed.
/// Always a composition bug in an `EncryptFrom`/`DecryptInto`
/// implementation, never a data error.
#[error("a pending fulfilment's responses did not match its requests")]
#[diagnostic(code(stack_encrypt::response_shape))]
ResponseShape,
/// [`Pending`](crate::target::Pending)s scoped to different keysets were
/// merged (`zip` / `all`): one built through a [`KeysetCipher`] for one
/// keyset, the other for another. A row belongs to one tenant; an
/// assembly that spans two is a composition bug, caught before any
/// I/O. (Opening leaves from several keysets in one batch is allowed —
/// through the [`StackCipher`], which is scoped to none.)
///
/// The keyset is the *whole* merge rule: two pendings built through two
/// different [`StackCipher`] values merge freely as long as they agree
/// on a keyset, because a keyset id is global and a cipher only holds a
/// keyset ZeroKMS resolved for its client. (Before the multi-keyset
/// `StackCipher` there was a `CipherMismatch` variant here, raised on
/// pointer equality of the two ciphers; it tested object identity
/// rather than client identity, and so refused two ciphers over the
/// same client and the same keyset.)
#[error("merged pendings were scoped to different keysets ({left} and {right})")]
#[diagnostic(
code(stack_encrypt::keyset_mismatch),
help("Build every part of one record or batch through the same keyset.")
)]
KeysetMismatch { left: Uuid, right: Uuid },
/// A keyset a decryption needed could not be loaded. Opening a JSON
/// document whose root is open derives the root's token under the index
/// key of the keyset the document was sealed under, and the cipher could
/// not load that keyset; `source` is the load's own error. Only the
/// documents under that keyset fail: the rest of the batch they were
/// opened in settles.
#[error("keyset {keyset_id} could not be loaded")]
#[diagnostic(
code(stack_encrypt::keyset_load),
help("The source says why the load failed. Check that this client is authorised for the keyset the document was sealed under.")
)]
KeysetLoad {
keyset_id: Uuid,
#[source]
source: Arc<Error>,
},
/// A leaf sealed under one keyset was handed to a [`KeysetCipher`] for
/// another. The handle's keyset is a constraint the caller asked for —
/// a tenant-scoped request handler must not open another tenant's row
/// — so this is refused before any key is retrieved. To open leaves
/// from any keyset, decrypt through the [`StackCipher`].
#[error("leaf was sealed under keyset {found}, not the handle's keyset {expected}")]
#[diagnostic(
code(stack_encrypt::foreign_keyset),
help(
"Decrypt through the client, not a keyset-bound cipher, to open rows from any keyset."
)
)]
ForeignKeyset { expected: Uuid, found: Uuid },
/// A data key was requested through a [`StackCipher`] rather than a
/// [`KeysetCipher`]: a [`Request::generate_data_key`] needs a keyset
/// to mint under, and only a keyset-scoped pending has one. Always a
/// composition bug in a hand-written `EncryptFrom`, caught before any
/// I/O.
///
/// [`Request::generate_data_key`]: crate::target::Request::generate_data_key
#[error("a data key was requested with no keyset to mint it under")]
#[diagnostic(
code(stack_encrypt::no_keyset),
help("Encrypt through a keyset cipher: `default_keyset()` or `keyset(..)` on the client.")
)]
NoKeyset,
/// A [`DecryptField`](crate::target::DecryptField) implementation
/// declared its type [`DECRYPTABLE`](crate::target::Decryptable::DECRYPTABLE)
/// but passed the field over. Always a bug in a third-party
/// `DecryptField`, never a data error.
#[error("a field declared decryptable was not opened by its DecryptField implementation")]
#[diagnostic(code(stack_encrypt::not_opened))]
NotOpened,
/// A [plan](crate::plan) was refused: it did not validate when it was
/// built, or the value, record or query it was run with does not match
/// it. A refusal at build or when a plan runs is raised before any key
/// is requested; [`FieldValues::take`](crate::plan::FieldValues::take)
/// also returns one for a record already in hand.
#[error(transparent)]
#[diagnostic(transparent)]
Plan(#[from] crate::plan::PlanError),
/// An [`OpaqueBlob`](crate::OpaqueBlob) could not be written as a
/// storage blob, or an authenticated ciphertext did not hold one its
/// type reads. Transparent: the message, code and help are the
/// [`BlobError`](crate::BlobError)'s, one per class of refusal. On
/// decrypt it is raised only after the leaf authenticated, so it never
/// stands in for [`Aead`](Self::Aead): the ciphertext is genuine and
/// holds a blob of another version, shape or type.
#[error(transparent)]
#[diagnostic(transparent)]
Blob(#[from] crate::BlobError),
}
/// How many separator-delimited parts a descriptor has: what an error about
/// a context says of it in place of the descriptor itself.
fn descriptor_parts(descriptor: &Descriptor) -> usize {
descriptor.as_str().split(Descriptor::SEPARATOR).count()
}
impl crate::ErrorPayload for Error {
fn payload(&self) -> serde_json::Map<String, serde_json::Value> {
use crate::diagnostic::payload;
match self {
Self::Kms(error) => error.payload(),
Self::Term(error) => error.payload(),
Self::Plan(error) => error.payload(),
Self::Blob(error) => error.payload(),
Self::KeyCountMismatch { expected, received } => payload([
("expected", (*expected).into()),
("received", (*received).into()),
]),
Self::OpenedType { expected } | Self::JsonWrongEntry { expected } => {
payload([("expected", (*expected).into())])
}
Self::JsonWildcardTruncated { bound } => payload([("bound", (*bound).into())]),
Self::DescriptorTooLong { len } => payload([
("len", (*len).into()),
("limit", Descriptor::MAX_LEN.into()),
]),
Self::ContextMismatch { stored } => payload([
("stored_len", stored.len().into()),
("stored_parts", descriptor_parts(stored).into()),
]),
Self::KeysetMismatch { left, right } => payload([
("left", left.to_string().into()),
("right", right.to_string().into()),
]),
Self::KeysetLoad { keyset_id, source } => {
let mut fields = payload([("keyset_id", keyset_id.to_string().into())]);
fields.extend(source.payload());
fields
}
Self::ForeignKeyset { expected, found } => payload([
("expected", expected.to_string().into()),
("found", found.to_string().into()),
]),
#[cfg(feature = "http")]
Self::Config(error) => error
.downcast_ref::<stack_kms::StackKmsBuilderError>()
.map(crate::ErrorPayload::payload)
.unwrap_or_default(),
#[cfg(not(feature = "http"))]
Self::Config(_) => serde_json::Map::new(),
Self::Aead
| Self::JsonNotALeaf
| Self::Other(_)
| Self::UnsupportedShape
| Self::ResponseShape
| Self::NoKeyset
| Self::NotOpened => serde_json::Map::new(),
}
}
}
#[cfg(feature = "http")]
impl From<stack_kms::StackKmsBuilderError> for Error {
fn from(error: stack_kms::StackKmsBuilderError) -> Self {
Error::Config(Box::new(error))
}
}
impl From<Unspecified> for Error {
fn from(_: Unspecified) -> Self {
Error::Aead
}
}
/// A text that is not a JSON path is a term error, as it is when an
/// accessor's path is parsed: a caller building a JSON index's options
/// (`JsonOptions::ordering`) can `?` it.
impl From<crate::json::JsonPathError> for Error {
fn from(error: crate::json::JsonPathError) -> Self {
Error::Term(error.into())
}
}
/// The CipherStash cipher, scoped to one client: a ZeroKMS client (a
/// [`DataKeySource`] — production: [`kms::StackKms`](crate::kms::StackKms); tests:
/// `stack_encrypt::kms::FakeDataKeySource`) and the keysets that client uses.
///
/// Per-leaf keying is deliberate: every value access requires its own data-key
/// retrieval, so individual value accesses are visible (and auditable) as
/// ZeroKMS key-retrieval events.
///
/// # Keysets
///
/// Sealing values, sealing records and deriving index terms all happen
/// under a keyset, and a client may use many — one per tenant, say. So
/// those operations bind to a [`KeysetCipher`], the cipher scoped to one
/// keyset: [`default_keyset`](Self::default_keyset) for the client's
/// default — the keyset a ZeroKMS administrator set for this client —
/// [`keyset`](Self::keyset) for any other, by id or by name. Keysets load lazily, through a bounded
/// least-recently-used cache: the first selection of a keyset is one
/// ZeroKMS round trip (its index key, which
/// [Searchable Encrypted Metadata](crate::sem) terms are derived from),
/// and every later one is a lookup. A backend that cannot supply an index
/// key is not a Stack Encrypt backend; plain AEAD with no indexing is what
/// `vitaminc` alone provides.
///
/// Decrypting is not keyset-scoped: a sealed leaf carries the id of the
/// keyset it was sealed under, and retrieving its data key needs nothing
/// more than that and the client. So [`decrypt`](Self::decrypt) lives here
/// and opens leaves from any keyset the client is authorised for, in one
/// batch. The same method on a [`KeysetCipher`] adds a constraint: it
/// refuses a leaf from any other keyset before any key is retrieved.
///
/// # Construction
///
// `new()` builds the ZeroKMS client from the environment, so it exists only
// with `http`; the builder path below works in either shape.
#[cfg_attr(
feature = "http",
doc = r#"[`new`](Self::new) is the default path — a ZeroKMS client from the
environment, on that client's default keyset:
```no_run
# async fn example() -> Result<(), stack_encrypt::Error> {
use stack_encrypt::StackCipher;
let cipher = StackCipher::new().await?;
# Ok(())
# }
```
Override with [`builder`](Self::builder) — a different keyset, or a
different data-key source entirely:"#
)]
#[cfg_attr(
not(feature = "http"),
doc = "Build with [`builder`](Self::builder), over an explicit data-key source:"
)]
///
/// ```
/// # async fn example() -> Result<(), stack_encrypt::Error> {
/// use stack_encrypt::StackCipher;
/// use stack_encrypt::kms::FakeDataKeySource;
///
/// let cipher = StackCipher::builder()
/// .kms(FakeDataKeySource::new())
/// .init()
/// .await?;
/// # Ok(())
/// # }
/// # tokio_test_block_on(example()).unwrap();
/// # fn tokio_test_block_on<F: std::future::Future>(f: F) -> F::Output {
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(f)
/// # }
/// ```
///
/// Construction is async because it resolves the client's default keyset
/// and loads its index key — one ZeroKMS round-trip, paid once, so a
/// misconfigured client fails here rather than on first use.
pub struct StackCipher<K> {
kms: K,
/// The client's default keyset, loaded eagerly by `init` and never
/// evicted. Not the caller's to choose — see
/// [`default_keyset`](Self::default_keyset).
default: Arc<KeysetState>,
/// Every other keyset this cipher has selected, least recently used
/// first out. See [`keyset`](Self::keyset).
keysets: Mutex<KeysetCache>,
/// Where the JSON index draws its permutations from (a document's stored
/// order, the order a query's selectors are sent in): fresh entropy per
/// document or query, outside tests.
json_randomness: crate::json::Randomness,
}
#[cfg(feature = "http")]
impl StackCipher<StackKms<stack_auth::AutoStrategy>> {
/// Build a cipher over a ZeroKMS client configured from the environment,
/// on that client's default keyset.
///
/// Equivalent to `StackCipher::builder().init()`. For a different keyset
/// or a different data-key source, use [`builder`](StackCipher::builder).
pub async fn new() -> Result<Self, Error> {
StackCipher::builder().init().await
}
}
impl StackCipher<FromEnv> {
/// Start building a cipher: pick a keyset, or supply a data-key source
/// other than the environment's ZeroKMS client.
///
/// A convenience alias for [`StackCipherBuilder::new`], which is the
/// canonical entry point. This one is anchored on `StackCipher<FromEnv>`
/// purely so `StackCipher::builder()` names a single concrete `K` and
/// resolves without a type annotation; `StackCipher<FromEnv>` is never
/// constructed.
pub fn builder() -> StackCipherBuilder {
StackCipherBuilder::new()
}
}
/// Opaque: the default keyset's identity and the data-key source's type
/// name, and nothing else. A cipher reaches the whole keyset cache — every
/// loaded keyset's index-key PRF — and, through its backend, the client key
/// and access token; none of that is printable, and a `Debug` that walked
/// the cache would also take its lock.
impl<K> std::fmt::Debug for StackCipher<K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StackCipher")
.field("default_keyset_id", &self.default.id)
.field("default_keyset_name", &self.default.name)
.field("kms", &std::any::type_name::<K>())
.finish_non_exhaustive()
}
}
impl<K> StackCipher<K> {
/// The cipher bound to the client's default keyset: the one a ZeroKMS
/// administrator set for this client, which is what naming no keyset
/// resolves to. Loaded at `init`, so this never touches ZeroKMS.
///
/// Always that keyset, whatever else the cipher has selected — the
/// default is the workspace's statement about this client, not a
/// preference a caller can override. To work under another keyset,
/// select it with [`keyset`](Self::keyset).
pub fn default_keyset(&self) -> KeysetCipher<'_, K> {
KeysetCipher::new(self, Arc::clone(&self.default))
}
/// The underlying data-key source.
pub fn kms(&self) -> &K {
&self.kms
}
/// Where this cipher draws the JSON index's permutations from.
pub(crate) fn json_randomness(&self) -> &crate::json::Randomness {
&self.json_randomness
}
fn keysets(&self) -> std::sync::MutexGuard<'_, KeysetCache> {
// The cache holds no invariant a panic mid-update could break (an
// insert is two map writes, and a stale name entry only points at
// a still-valid state), so a poisoned lock is recovered, not
// propagated.
self.keysets.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl<K: IndexKeySource> StackCipher<K> {
/// The cipher bound to a keyset, by id or by name.
///
/// The one async point of keyset selection: a keyset this cipher has
/// not seen (or has evicted) is loaded from ZeroKMS here — its id
/// resolved and its index key fetched — and cached; every later
/// selection is a lookup. The returned handle keeps that keyset loaded
/// for as long as it is held, so a request handler that selects its
/// tenant's keyset once never pays again within the request.
///
/// ```
/// # async fn example() -> Result<(), stack_encrypt::Error> {
/// use stack_encrypt::{nonempty, StackCipher};
/// use stack_encrypt::kms::{FakeDataKeySource, IdentifiedBy};
///
/// let cipher = StackCipher::builder()
/// .kms(FakeDataKeySource::new())
/// .init()
/// .await?;
/// let tenant = cipher.keyset(IdentifiedBy::Name("acme".to_string().into())).await?;
/// let sealed = tenant.encrypt_tree("hello".to_string(), nonempty!("greeting")).await?;
/// # Ok(())
/// # }
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap();
/// ```
///
/// A keyset ZeroKMS does not know, or has disabled, is
/// [`Error::Kms`]. The name-to-id resolution is ZeroKMS's: a keyset
/// selected by name reports the resolved id from
/// [`KeysetCipher::keyset_id`], and a name the cipher resolved earlier
/// is trusted for a bounded window
/// ([`keyset_name_ttl`](StackCipherBuilder::keyset_name_ttl)) before it
/// is asked again — ZeroKMS allows renames, and a running process
/// notices one within that window. Selecting by id never asks twice.
pub async fn keyset(
&self,
keyset: impl Into<IdentifiedBy>,
) -> Result<KeysetCipher<'_, K>, Error> {
let keyset = keyset.into();
let resolution = match self.keysets().get(&keyset) {
Lookup::Hit(state) => return Ok(KeysetCipher::new(self, state)),
// A name past its window: the keyset is still loaded, but
// whether the name still means it is ZeroKMS's to say.
Lookup::Stale(resolution) | Lookup::Miss(resolution) => resolution,
};
// Loaded outside the lock: a round trip must not hold up every other
// selection. Two selections racing on the same miss load twice; the
// cache keeps both keysets by id, and the name follows the later
// lookup whichever answer lands first — and so does this caller,
// who is handed the answer that won, not the one that lost.
let asked_name = match &keyset {
IdentifiedBy::Name(name) => Some(name.to_string()),
IdentifiedBy::Uuid(_) => None,
};
let state = match load_keyset(&self.kms, keyset).await {
Ok(state) => state,
Err(error) => {
// ZeroKMS's own answer that no keyset has this name is an
// answer about the name, and the cache orders it like one:
// the binding an earlier lookup made goes, and an earlier
// positive answer still in flight cannot bind the name after
// it. A lookup that got no answer (transport, auth) says
// nothing about the name and leaves the cache as it was.
if let (Some(name), true) = (&asked_name, is_keyset_not_found(&error)) {
self.keysets().forget(name, resolution);
}
return Err(error);
}
};
let state = self.keysets().insert(state, resolution);
Ok(KeysetCipher::new(self, state))
}
/// The loaded state of the keyset `id`: from the cache, or loaded from
/// ZeroKMS and cached on a miss, as [`keyset`](Self::keyset) selects a
/// keyset by id. What a keyset request settles to
/// ([`Request::load_keyset`](crate::target::Request)).
pub(crate) async fn keyset_state(&self, id: Uuid) -> Result<Arc<KeysetState>, Error> {
// Bound first, so the cache's lock is released before the await.
let lookup = self.keysets().get(&IdentifiedBy::Uuid(id));
let resolution = match lookup {
Lookup::Hit(state) => return Ok(state),
Lookup::Stale(resolution) | Lookup::Miss(resolution) => resolution,
};
// Boxed: this runs after a batch's data keys have been through the
// stack, and a future is built on the stack and moved with every
// byte it does not initialise (see `dispatch`).
let state = Box::pin(load_keyset(&self.kms, IdentifiedBy::Uuid(id))).await?;
// Asked by id, ZeroKMS answers for that id. A source that answers for
// another would have the document walked under another keyset's PRF,
// and cached under an id no later lookup asks for.
if state.id != id {
return Err(Error::KeysetMismatch {
left: id,
right: state.id,
});
}
Ok(self.keysets().insert(state, resolution))
}
}
/// Resolve a keyset at ZeroKMS and build the state the cipher holds for it:
/// its resolved id, the name it was selected by (a selection by id has
/// none), and the PRF keyed by its index key. The one round trip a keyset
/// costs, shared by eager loading at
/// [`init`](StackCipherBuilder::init) and lazy loading in
/// [`StackCipher::keyset`] so both hold a keyset in exactly the same shape.
/// ZeroKMS answered a load with "no such keyset" — as opposed to not
/// answering at all.
fn is_keyset_not_found(error: &Error) -> bool {
matches!(
error,
Error::Kms(stack_kms::Error::LoadKeyset(
stack_kms::LoadKeysetError::KeysetNotFound(_)
))
)
}
async fn load_keyset<K: IndexKeySource>(
kms: &K,
keyset: IdentifiedBy,
) -> Result<Arc<KeysetState>, Error> {
let name = match &keyset {
IdentifiedBy::Name(name) => Some(name.to_string()),
IdentifiedBy::Uuid(_) => None,
};
let (id, index_key) = kms.load_index_key(Some(keyset)).await?;
Ok(keyset_state_of(id, name, &index_key))
}
/// The state the cipher holds for a loaded keyset: its id, the name it was
/// selected by, and the PRF keyed by its index key. One construction for
/// every way a keyset is loaded.
fn keyset_state_of(
id: Uuid,
name: Option<String>,
index_key: &stack_kms::IndexKey,
) -> Arc<KeysetState> {
Arc::new(KeysetState {
id,
name,
prf: hmac_prf_from_index_key(index_key),
})
}
/// The client's own default keyset — the one a ZeroKMS administrator set for
/// this client — asked for by naming nothing. Loaded once, by
/// [`init`](StackCipherBuilder::init); it is not the caller's to choose, so
/// there is no id or name to carry.
async fn load_default_keyset<K: IndexKeySource>(kms: &K) -> Result<Arc<KeysetState>, Error> {
let (id, index_key) = kms.load_index_key(None).await?;
Ok(keyset_state_of(id, None, &index_key))
}
/// The state of a [`StackCipherBuilder`] that has not been given a data-key
/// source: [`init`](StackCipherBuilder::init) will build a ZeroKMS client from
/// the environment (and, on native targets, the CLI's profile directory).
pub struct FromEnv;
/// The client key, looked up the way [`stack_auth::AutoStrategy`] looks up the
/// access token: `CS_CLIENT_ID` / `CS_CLIENT_KEY` first, then the current
/// workspace's `secretkey.json` in the profile directory. A profile directory
/// that cannot be resolved is not an error here — env-only setups (CI) have
/// none — it just leaves the environment as the only source.
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
fn client_key_provider() -> FallbackKeyProvider<EnvKeyProvider, ProfileClientKey> {
FallbackKeyProvider::new(
EnvKeyProvider,
ProfileClientKey(ProfileStore::resolve(None).ok()),
)
}
/// wasm32 has no filesystem, so no profile: the environment is the only source.
#[cfg(all(feature = "http", target_arch = "wasm32"))]
fn client_key_provider() -> EnvKeyProvider {
EnvKeyProvider
}
/// [`ProfileStore`] as a [`KeyProvider`], tolerating an unresolvable profile
/// directory so the "not configured" message can say what to do about it
/// rather than only that `CS_CLIENT_ID` is unset.
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
struct ProfileClientKey(Option<ProfileStore>);
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
impl KeyProvider for ProfileClientKey {
async fn client_key(&self) -> Result<stack_kms::ClientKey, KeyProviderError> {
match &self.0 {
Some(store) => store.client_key().await,
None => Err(KeyProviderError::NotConfigured(
"no client key: set CS_CLIENT_ID / CS_CLIENT_KEY, or run `npx stash auth login`"
.into(),
)),
}
}
}
/// Builder for a [`StackCipher`]. Start with [`StackCipherBuilder::new`] (or
/// its alias [`StackCipher::builder`]).
pub struct StackCipherBuilder<K = FromEnv> {
kms: K,
cache_size: NonZeroUsize,
name_ttl: Duration,
#[cfg(feature = "test-support")]
json_seed: Option<Protected<[u8; 32]>>,
}
impl StackCipherBuilder<FromEnv> {
/// Start building a cipher: pick a keyset, or supply a data-key source
/// other than the environment's ZeroKMS client.
///
/// The `K = FromEnv` type default makes this resolve without a type
/// annotation whether or not the `http` feature is on.
pub fn new() -> Self {
Self {
kms: FromEnv,
cache_size: KeysetCache::DEFAULT_CAPACITY,
name_ttl: DEFAULT_NAME_TTL,
#[cfg(feature = "test-support")]
json_seed: None,
}
}
}
impl Default for StackCipherBuilder<FromEnv> {
fn default() -> Self {
Self::new()
}
}
impl<K> StackCipherBuilder<K> {
/// How many keysets beyond the default the cipher keeps loaded
/// (default 1024). A process serving more tenants than this reloads a
/// keyset's index key from ZeroKMS when it comes back into use; nothing
/// stored depends on the cache, so the bound only trades memory for
/// round trips. See [`StackCipher::keyset`].
pub fn keyset_cache_size(mut self, size: NonZeroUsize) -> Self {
self.cache_size = size;
self
}
/// How long a keyset selected by name is trusted to still be the keyset
/// that name resolved to (default five minutes, [`DEFAULT_NAME_TTL`]).
/// ZeroKMS allows a keyset to be renamed; within the window a rename is
/// invisible to a running process, after it the next selection by that
/// name asks ZeroKMS again. `Duration::ZERO` makes every selection by
/// name a round trip; selection by id is never affected. See
/// [`StackCipher::keyset`].
///
/// [`DEFAULT_NAME_TTL`]: crate::keyset::DEFAULT_NAME_TTL
pub fn keyset_name_ttl(mut self, ttl: Duration) -> Self {
self.name_ttl = ttl;
self
}
/// Test support: draw every permutation the JSON index needs (the
/// stored order of each document it seals, its objects' member
/// ordinals, the order each query's selectors are sent in) from one
/// generator started at `seed`,
/// so that a run sealing the same documents in the same sequence draws
/// the same permutations and a fixture can pin them. Paired with the
/// deterministic key source (`kms::DeterministicSource`).
///
/// Never for data: the permutations are drawn from the operating
/// system's entropy so that they say nothing, and one that follows from
/// a known seed hides nothing of a document's shape.
#[cfg(feature = "test-support")]
pub fn json_seed(mut self, seed: [u8; 32]) -> Self {
self.json_seed = Some(Protected::new(seed));
self
}
}
impl StackCipherBuilder<FromEnv> {
/// Use an explicit data-key source rather than building a ZeroKMS client
/// from the environment.
///
/// This is the seam for a custom authentication strategy: build a
/// [`kms::StackKms`](crate::kms::StackKms) — with `stack_encrypt::kms::StackKmsBuilder`,
/// or over the host's own transport — and hand it over. It is also how
/// tests inject `stack_encrypt::kms::FakeDataKeySource`.
pub fn kms<K>(self, kms: K) -> StackCipherBuilder<K> {
StackCipherBuilder {
kms,
cache_size: self.cache_size,
name_ttl: self.name_ttl,
#[cfg(feature = "test-support")]
json_seed: self.json_seed,
}
}
/// Build a ZeroKMS client from the environment, then resolve the keyset
/// and load its index key.
///
/// Credentials come from the same two places for both halves of the
/// client — the access token and the client key:
///
/// 1. the environment (`CS_CLIENT_ACCESS_KEY` + `CS_WORKSPACE_CRN`;
/// `CS_CLIENT_ID` + `CS_CLIENT_KEY`), then
/// 2. the current workspace in the CLI's profile directory
/// (`auth.json`; `secretkey.json`), which `npx stash auth login`
/// writes.
///
/// So on a developer machine, logging in with the CLI is sufficient; in
/// CI, the four variables are.
#[cfg(feature = "http")]
pub async fn init(self) -> Result<StackCipher<StackKms<stack_auth::AutoStrategy>>, Error> {
let kms = StackKmsBuilder::auto()?
.with_key_provider(client_key_provider())
.build()
.await?;
self.kms(kms).init().await
}
}
impl<K> StackCipherBuilder<K> {
/// The randomness the cipher's JSON index draws from: the seeded stream
/// under `test-support` when one was given, entropy otherwise.
fn json_randomness(&self) -> crate::json::Randomness {
#[cfg(feature = "test-support")]
if let Some(seed) = &self.json_seed {
return crate::json::Randomness::seeded(seed.clone());
}
crate::json::Randomness::from_entropy()
}
}
impl<K: DataKeySource + IndexKeySource> StackCipherBuilder<K> {
/// Resolve the default keyset and load its index key, producing a
/// cipher whose [`default_keyset`](StackCipher::default_keyset) can both
/// seal values and derive index terms. The one round trip a cipher
/// always pays; every other keyset loads on first selection.
pub async fn init(self) -> Result<StackCipher<K>, Error> {
let default = load_default_keyset(&self.kms).await?;
let json_randomness = self.json_randomness();
Ok(StackCipher {
kms: self.kms,
keysets: Mutex::new(KeysetCache::new(