basil-core 0.6.1

Basil daemon core, broker services, transport, and offline admin command implementations.
Documentation
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
#![allow(clippy::result_large_err)]

// SPDX-FileCopyrightText: 2026 OpenBasil Contributors
//
// SPDX-License-Identifier: Apache-2.0

use basil_proto::broker::v1 as pb;
use basil_proto::broker::v1::aead_service_server::AeadService;
use tonic::{Request, Response};

use crate::catalog::policy::Op;
use crate::core::crypto_provider::{
    Envelope as ProviderEnvelope, EnvelopeAlgorithm as ProviderEnvelopeAlgorithm,
    KemAlgorithm as ProviderKemAlgorithm,
};
use crate::manager::MlKemEnvelopeParts;
use crate::service::broker::{BrokerGrpc, GrpcResult};
use crate::service::shared::{
    SupportedKem, aead_algorithm, basil_ciphertext_envelope, ciphertext_envelope,
    ensure_supported_envelope_algorithm, ensure_supported_kem_algorithm, invalid_request,
    manager_status, payload_too_large,
};
use crate::x25519_seal::SealedEnvelope;

#[tonic::async_trait]
impl AeadService for BrokerGrpc {
    async fn encrypt(
        &self,
        request: Request<pb::EncryptRequest>,
    ) -> GrpcResult<pb::EncryptResponse> {
        let body = request.get_ref();
        self.authorize(&request, Op::Encrypt, &body.key_id)?;
        if body.plaintext.len() > self.state.limits().max_encrypt_size {
            return Err(payload_too_large(
                "encrypt",
                "encrypt payload exceeds configured cap",
            ));
        }
        let envelope = self
            .state
            .manager()
            .encrypt(
                &body.key_id,
                aead_algorithm(body.algorithm, "encrypt")?,
                &body.plaintext,
                body.aad.as_deref(),
            )
            .await
            .map_err(|e| manager_status("encrypt", &e))?;
        Ok(Response::new(pb::EncryptResponse {
            envelope: Some(ciphertext_envelope(envelope)),
        }))
    }

    async fn decrypt(
        &self,
        request: Request<pb::DecryptRequest>,
    ) -> GrpcResult<pb::DecryptResponse> {
        let body = request.get_ref();
        self.authorize(&request, Op::Decrypt, &body.key_id)?;
        let envelope = body
            .envelope
            .as_ref()
            .ok_or_else(|| invalid_request("decrypt", "missing ciphertext envelope"))
            .and_then(|envelope| basil_ciphertext_envelope(envelope, "decrypt"))?;
        if envelope.ciphertext.len() > self.state.limits().max_encrypt_size {
            return Err(payload_too_large(
                "decrypt",
                "decrypt payload exceeds configured cap",
            ));
        }
        let plaintext = self
            .state
            .manager()
            .decrypt(&body.key_id, &envelope, body.aad.as_deref())
            .await
            .map_err(|e| manager_status("decrypt", &e))?;
        Ok(Response::new(pb::DecryptResponse { plaintext }))
    }

    async fn wrap_envelope(
        &self,
        request: Request<pb::WrapEnvelopeRequest>,
    ) -> GrpcResult<pb::WrapEnvelopeResponse> {
        let body = request.get_ref();
        let actor = self.authorize(&request, Op::Encrypt, &body.key_id)?;
        let uid = Self::require_unix_uid(&actor, "encrypt")?;
        if body.plaintext.len() > self.state.limits().max_encrypt_size {
            return Err(payload_too_large(
                "wrap_envelope",
                "envelope payload exceeds configured cap",
            ));
        }
        let kem = ensure_supported_kem_algorithm(body.kem_algorithm, "wrap_envelope")?;
        ensure_supported_envelope_algorithm(body.envelope_algorithm, "wrap_envelope")?;
        // X25519 wraps through the classical sealing path (public-only); ML-KEM
        // dispatches through the software-custody crypto provider, which self-seals
        // to the custodied seed's encapsulation key under the op:use_software_custody
        // grant.
        let Some(provider_kem) = ml_kem_provider_algorithm(kem) else {
            let sealed = self
                .state
                .manager()
                .wrap_envelope(
                    &body.key_id,
                    &body.plaintext,
                    body.aad.as_deref().unwrap_or_default(),
                )
                .await
                .map_err(|e| manager_status("wrap_envelope", &e))?;
            return Ok(Response::new(pb::WrapEnvelopeResponse {
                envelope: Some(kem_envelope(
                    body.kem_algorithm,
                    body.envelope_algorithm,
                    &sealed,
                )),
            }));
        };
        let envelope_algorithm =
            provider_envelope_algorithm(body.envelope_algorithm, "wrap_envelope")?;
        let gate = self.provider_gate(&actor, &body.key_id);
        let (envelope, dispatch) = self
            .state
            .manager()
            .provider_wrap_envelope(
                &body.key_id,
                provider_kem,
                envelope_algorithm,
                &body.plaintext,
                body.aad.as_deref().unwrap_or_default(),
                gate,
            )
            .await
            .inspect_err(|e| {
                self.audit_provider_failure(
                    uid,
                    "wrap_envelope",
                    &body.key_id,
                    provider_kem.token(),
                    e,
                );
            })
            .map_err(|e| manager_status("wrap_envelope", &e))?;
        self.audit_provider_success(uid, "wrap_envelope", &body.key_id, dispatch);
        Ok(Response::new(pb::WrapEnvelopeResponse {
            envelope: Some(ml_kem_wire_envelope(
                body.kem_algorithm,
                body.envelope_algorithm,
                &envelope,
            )),
        }))
    }

    /// Open a sealed envelope (`unwrap`) addressed to a sealing key: an X25519
    /// sealed box or ML-KEM software-custody envelope, selected by the wire
    /// `kem_algorithm`.
    ///
    /// **Confidentiality only, NOT sender authentication.** A sealed envelope is
    /// anonymous: a successful unseal proves only that the payload was sealed to
    /// this recipient's public key, never *who* sealed it (anyone with the public
    /// can produce a valid envelope). Callers MUST NOT treat a successful unwrap as
    /// proof of sender identity. Bind sender authenticity at a higher layer if
    /// needed.
    async fn unwrap_envelope(
        &self,
        request: Request<pb::UnwrapEnvelopeRequest>,
    ) -> GrpcResult<pb::UnwrapEnvelopeResponse> {
        let body = request.get_ref();
        let actor = self.authorize(&request, Op::Decrypt, &body.key_id)?;
        let uid = Self::require_unix_uid(&actor, "decrypt")?;
        let envelope = body
            .envelope
            .as_ref()
            .ok_or_else(|| invalid_request("unwrap_envelope", "missing KEM envelope"))?;
        let kem = ensure_supported_kem_algorithm(envelope.kem_algorithm, "unwrap_envelope")?;
        ensure_supported_envelope_algorithm(envelope.envelope_algorithm, "unwrap_envelope")?;
        if envelope.ciphertext.len() > self.state.limits().max_encrypt_size {
            return Err(payload_too_large(
                "unwrap_envelope",
                "envelope payload exceeds configured cap",
            ));
        }
        // X25519 opens through the classical sealing path; ML-KEM dispatches through
        // the software-custody crypto provider (gated by op:use_software_custody).
        let Some(provider_kem) = ml_kem_provider_algorithm(kem) else {
            // Validate the fixed-length wire fields (never index attacker bytes).
            let sealed = seal_envelope_from_wire(envelope)?;
            let plaintext = self
                .state
                .manager()
                .unwrap_envelope(
                    &body.key_id,
                    &sealed,
                    body.aad.as_deref().unwrap_or_default(),
                )
                .await
                .map_err(|e| manager_status("unwrap_envelope", &e))?;
            return Ok(Response::new(pb::UnwrapEnvelopeResponse {
                plaintext: plaintext.to_vec(),
            }));
        };
        let envelope_algorithm =
            provider_envelope_algorithm(envelope.envelope_algorithm, "unwrap_envelope")?;
        let gate = self.provider_gate(&actor, &body.key_id);
        let (plaintext, dispatch) = self
            .state
            .manager()
            .provider_unwrap_envelope(
                &body.key_id,
                provider_kem,
                envelope_algorithm,
                MlKemEnvelopeParts {
                    encapsulated_key: &envelope.encapsulated_key,
                    nonce: &envelope.nonce,
                    ciphertext: &envelope.ciphertext,
                },
                body.aad.as_deref().unwrap_or_default(),
                gate,
            )
            .await
            .inspect_err(|e| {
                self.audit_provider_failure(
                    uid,
                    "unwrap_envelope",
                    &body.key_id,
                    provider_kem.token(),
                    e,
                );
            })
            .map_err(|e| manager_status("unwrap_envelope", &e))?;
        self.audit_provider_success(uid, "unwrap_envelope", &body.key_id, dispatch);
        Ok(Response::new(pb::UnwrapEnvelopeResponse { plaintext }))
    }

    async fn unseal_cose(
        &self,
        request: Request<pb::UnsealCoseRequest>,
    ) -> GrpcResult<pb::UnsealCoseResponse> {
        let body = request.get_ref();
        self.authorize(&request, Op::Decrypt, &body.key_id)?;
        if body.cose_encrypt.len() > self.state.limits().max_encrypt_size {
            return Err(payload_too_large(
                "unseal_cose",
                "COSE payload exceeds configured cap",
            ));
        }
        let plaintext = self
            .state
            .manager()
            .unseal_cose(
                &body.key_id,
                &body.cose_encrypt,
                body.external_aad.as_deref().unwrap_or_default(),
            )
            .await
            .map_err(|e| manager_status("unseal_cose", &e))?;
        Ok(Response::new(pb::UnsealCoseResponse {
            plaintext: plaintext.to_vec(),
        }))
    }
}

/// Build the wire [`pb::KemEnvelope`] response from a sealed X25519 envelope. The
/// key version field is unused for a software-custodied sealing key (the private
/// is materialized from KV, not transit-versioned), so it is reported as 0.
fn kem_envelope(
    kem_algorithm: i32,
    envelope_algorithm: i32,
    sealed: &SealedEnvelope,
) -> pb::KemEnvelope {
    pb::KemEnvelope {
        kem_algorithm,
        envelope_algorithm,
        key_version: 0,
        encapsulated_key: sealed.encapsulated_key.to_vec(),
        nonce: sealed.nonce.to_vec(),
        ciphertext: sealed.ciphertext.clone(),
    }
}

/// Parse a wire [`pb::KemEnvelope`] into the crypto-core [`SealedEnvelope`],
/// validating the fixed-length `encapsulated_key` / `nonce` fields. A wrong length
/// is a client error, mapped through the manager `Malformed` surface.
fn seal_envelope_from_wire(envelope: &pb::KemEnvelope) -> Result<SealedEnvelope, tonic::Status> {
    crate::x25519_seal::envelope_from_parts(
        &envelope.encapsulated_key,
        &envelope.nonce,
        &envelope.ciphertext,
    )
    .map_err(|_| {
        invalid_request(
            "unwrap_envelope",
            "malformed KEM envelope (bad encapsulated_key or nonce length)",
        )
    })
}

/// Map a broker-supported KEM to the provider-dispatch ML-KEM algorithm. Returns
/// `None` for X25519, which is not provider-dispatched (it uses the classical
/// sealing path).
const fn ml_kem_provider_algorithm(kem: SupportedKem) -> Option<ProviderKemAlgorithm> {
    match kem {
        SupportedKem::MlKem512 => Some(ProviderKemAlgorithm::MlKem512),
        SupportedKem::MlKem768 => Some(ProviderKemAlgorithm::MlKem768),
        SupportedKem::MlKem1024 => Some(ProviderKemAlgorithm::MlKem1024),
        SupportedKem::X25519 => None,
    }
}

/// Map the wire envelope-AEAD enum to the provider-dispatch algorithm.
fn provider_envelope_algorithm(
    value: i32,
    op: &'static str,
) -> Result<ProviderEnvelopeAlgorithm, tonic::Status> {
    match pb::EnvelopeAlgorithm::try_from(value)
        .map_err(|_| invalid_request(op, "unknown envelope algorithm"))?
    {
        pb::EnvelopeAlgorithm::Unspecified => {
            Err(invalid_request(op, "missing envelope algorithm"))
        }
        pb::EnvelopeAlgorithm::Aes256Gcm => Ok(ProviderEnvelopeAlgorithm::Aes256Gcm),
        pb::EnvelopeAlgorithm::Chacha20Poly1305 => Ok(ProviderEnvelopeAlgorithm::ChaCha20Poly1305),
    }
}

/// Build the wire [`pb::KemEnvelope`] from a provider-dispatched ML-KEM
/// [`ProviderEnvelope`]. Self-describing: it echoes the requested KEM/envelope
/// algorithm and carries the custody record's `key_version`, so `unwrap` routes to
/// the right parameter set, AEAD algorithm, and key version without leaking secrets.
fn ml_kem_wire_envelope(
    kem_algorithm: i32,
    envelope_algorithm: i32,
    envelope: &ProviderEnvelope,
) -> pb::KemEnvelope {
    pb::KemEnvelope {
        kem_algorithm,
        envelope_algorithm,
        key_version: envelope.key_version,
        encapsulated_key: envelope.encapsulated_key.clone(),
        nonce: envelope.nonce.clone(),
        ciphertext: envelope.ciphertext.clone(),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, HashMap};
    use std::sync::Arc;
    use std::sync::Mutex;

    use async_trait::async_trait;
    use basil_cose::{
        ContentAlgorithm, ContentType, EncryptParams, ExternalAad, KdfParties, KeyId, PartyIdentity,
    };
    use basil_proto::broker::v1 as pb;
    use basil_proto::broker::v1::aead_service_server::AeadService;
    use basil_proto::{AeadAlgorithm, CiphertextEnvelope, KeyType};
    use tonic::{Code, Request};
    use zeroize::Zeroizing;

    use super::BrokerGrpc;
    use crate::backend::{Backend, BackendError, KvValue, NewKey};
    use crate::catalog::load;
    use crate::manager::BackendManager;
    use crate::peer::PeerInfo;
    use crate::state::BrokerState;

    /// In-memory backend that serves a pre-provisioned ML-KEM software-custody
    /// record from `kv_get` and unseals the seed from `decrypt`. `encrypt`
    /// length-prefixes the AAD so `decrypt` authenticates it (identity envelope;
    /// the test exercises the broker/provider wiring, not the storage AEAD).
    #[derive(Default)]
    struct SealingBackend {
        store: Mutex<HashMap<String, Vec<u8>>>,
    }

    impl SealingBackend {
        fn seeded(path: &str, record: Vec<u8>) -> Self {
            let backend = Self::default();
            if let Ok(mut store) = backend.store.lock() {
                store.insert(path.to_string(), record);
            }
            backend
        }
    }

    #[async_trait]
    impl Backend for SealingBackend {
        fn kind(&self) -> &'static str {
            "ml-kem-sealing-test"
        }

        async fn new_key(&self, _key_type: KeyType) -> Result<NewKey, BackendError> {
            Err(BackendError::Unsupported("new_key"))
        }

        async fn public_key(&self, _key_id: &str) -> Result<Vec<u8>, BackendError> {
            Err(BackendError::Unsupported("public_key"))
        }

        async fn sign(&self, _key_id: &str, _message: &[u8]) -> Result<Vec<u8>, BackendError> {
            Err(BackendError::Unsupported("sign"))
        }

        async fn verify(
            &self,
            _key_id: &str,
            _message: &[u8],
            _signature: &[u8],
        ) -> Result<bool, BackendError> {
            Err(BackendError::Unsupported("verify"))
        }

        async fn encrypt(
            &self,
            _key_id: &str,
            algorithm: AeadAlgorithm,
            plaintext: &[u8],
            aad: Option<&[u8]>,
        ) -> Result<CiphertextEnvelope, BackendError> {
            let aad = aad.unwrap_or(&[]);
            let mut ciphertext = vec![u8::try_from(aad.len()).unwrap_or(u8::MAX)];
            ciphertext.extend_from_slice(aad);
            ciphertext.extend_from_slice(plaintext);
            Ok(CiphertextEnvelope {
                alg: algorithm,
                key_version: 1,
                nonce: Vec::new(),
                ciphertext,
            })
        }

        async fn decrypt(
            &self,
            _key_id: &str,
            envelope: &CiphertextEnvelope,
            aad: Option<&[u8]>,
        ) -> Result<Vec<u8>, BackendError> {
            let aad = aad.unwrap_or(&[]);
            let ct = &envelope.ciphertext;
            let aad_len = *ct.first().ok_or(BackendError::DecryptFailed)? as usize;
            let bound = ct.get(1..1 + aad_len).ok_or(BackendError::DecryptFailed)?;
            if bound != aad {
                return Err(BackendError::DecryptFailed);
            }
            Ok(ct
                .get(1 + aad_len..)
                .ok_or(BackendError::DecryptFailed)?
                .to_vec())
        }

        async fn kv_put(&self, key_id: &str, value: &[u8]) -> Result<u32, BackendError> {
            self.store
                .lock()
                .map_err(|_| BackendError::Unsupported("kv_put"))?
                .insert(key_id.to_string(), value.to_vec());
            Ok(1)
        }

        async fn kv_get(
            &self,
            key_id: &str,
            _version: Option<u32>,
        ) -> Result<KvValue, BackendError> {
            let value = self
                .store
                .lock()
                .map_err(|_| BackendError::Unsupported("kv_get"))?
                .get(key_id)
                .cloned();
            value
                .map(|value| KvValue { value, version: 1 })
                .ok_or(BackendError::Unsupported("kv_get"))
        }

        async fn kv_get_secret(
            &self,
            key_id: &str,
            _version: Option<u32>,
        ) -> Result<crate::backend::KvSecret, BackendError> {
            let value = self
                .store
                .lock()
                .map_err(|_| BackendError::Unsupported("kv_get_secret"))?
                .get(key_id)
                .cloned();
            value
                .map(|value| crate::backend::KvSecret {
                    value: Zeroizing::new(value),
                    version: 1,
                })
                .ok_or(BackendError::Unsupported("kv_get_secret"))
        }
    }

    const CATALOG: &str = r#"{
      "schemaVersion": 1,
      "backends": { "bao": { "kind": "vault", "addr": "https://127.0.0.1:8200" } },
      "keys": {
        "cose.sealing": {
          "class": "sealing", "keyType": "x25519", "backend": "bao", "engine": "kv2",
          "path": "secret/data/cose/sealing",
          "publicPath": "secret/data/cose/sealing-public",
          "writable": true, "missing": "error",
          "description": "x25519 COSE recipient key"
        },
        "cose.wrong": {
          "class": "sealing", "keyType": "x25519", "backend": "bao", "engine": "kv2",
          "path": "secret/data/cose/wrong",
          "publicPath": "secret/data/cose/wrong-public",
          "writable": true, "missing": "error",
          "description": "wrong x25519 COSE recipient key"
        },
        "cose.pinparties": {
          "class": "sealing", "keyType": "x25519", "backend": "bao", "engine": "kv2",
          "path": "secret/data/cose/pin-parties",
          "publicPath": "secret/data/cose/pin-parties-public",
          "writable": true, "missing": "error",
          "sealingPin": { "parties": { "partyU": "alice", "partyV": "bob" } },
          "description": "x25519 COSE recipient key pinned to alice/bob KDF parties"
        },
        "cose.pinaad": {
          "class": "sealing", "keyType": "x25519", "backend": "bao", "engine": "kv2",
          "path": "secret/data/cose/pin-aad",
          "publicPath": "secret/data/cose/pin-aad-public",
          "writable": true, "missing": "error",
          "sealingPin": { "externalAad": ["ctx"] },
          "description": "x25519 COSE recipient key pinned to the ctx external_aad"
        },
        "pqc.sealing": {
          "class": "sealing", "keyType": "ml-kem-768", "backend": "bao", "engine": "kv2",
          "path": "secret/data/pqc/sealing",
          "publicPath": "secret/data/pqc/sealing-public",
          "writable": true, "missing": "error",
          "labels": ["crypto_provider=local-software", "crypto_provider_policy=local-software",
                     "pqc_custody=software-encrypted", "pqc_storage_key=pqc/aead",
                     "pqc_algorithm=ml-kem-768", "crypto_provider_version=1"],
          "description": "ml-kem-768 software-custodied sealing key"
        }
      }
    }"#;

    // uid 42 holds the local-software grant; uid 43 holds encrypt/decrypt but NOT
    // op:use_software_custody, so it cannot drive the local-software provider.
    const POLICY: &str = r#"{
      "schemaVersion": 2,
      "subjects": {
        "svc.granted": { "allOf": [ { "kind": "unix", "uid": 42 } ] },
        "svc.ungranted": { "allOf": [ { "kind": "unix", "uid": 43 } ] }
      },
      "roles": {},
      "rules": [
        { "id": "granted", "subjects": ["svc.granted"],
          "action": ["op:encrypt", "op:decrypt", "op:use_software_custody"],
          "target": ["pqc.*", "cose.*"] },
        { "id": "ungranted", "subjects": ["svc.ungranted"],
          "action": ["op:encrypt", "op:decrypt"],
          "target": ["pqc.*", "cose.*"] }
      ],
      "config": {
        "names": { "users": { "42": "svc-granted", "43": "svc-ungranted" }, "groups": {} },
        "memberships": { "42": [42], "43": [43] }
      }
    }"#;

    // The seed and its custody path are consumed only by the unwrap test and
    // `ml_kem_record`.
    const SEED: [u8; 64] = [0x42; 64];
    const SEALING_PATH: &str = "secret/data/pqc/sealing";
    const COSE_KEY_ID: &str = "cose.sealing";
    const COSE_WRONG_KEY_ID: &str = "cose.wrong";
    const COSE_PIN_PARTIES_KEY_ID: &str = "cose.pinparties";
    const COSE_PIN_AAD_KEY_ID: &str = "cose.pinaad";
    const COSE_PATH: &str = "secret/data/cose/sealing";
    const COSE_WRONG_PATH: &str = "secret/data/cose/wrong";
    const COSE_PIN_PARTIES_PATH: &str = "secret/data/cose/pin-parties";
    const COSE_PIN_AAD_PATH: &str = "secret/data/cose/pin-aad";
    const COSE_PRIVATE: [u8; 32] = [0x37; 32];
    const COSE_WRONG_PRIVATE: [u8; 32] = [0xA5; 32];

    fn service(backend: SealingBackend) -> BrokerGrpc {
        let (catalog, policy, config, warnings) = load(CATALOG, POLICY).expect("fixture loads");
        assert!(warnings.is_empty());
        let mut backends: BTreeMap<String, Box<dyn Backend>> = BTreeMap::new();
        backends.insert("bao".to_string(), Box::new(backend));
        let manager = BackendManager::new(catalog.clone(), backends).expect("manager builds");
        BrokerGrpc::new(Arc::new(BrokerState::new(
            catalog,
            policy,
            config,
            manager,
            "pqc-aead-test",
        )))
    }

    fn request<T>(uid: u32, body: T) -> Request<T> {
        let mut request = Request::new(body);
        request.extensions_mut().insert(PeerInfo {
            uid: Some(uid),
            ..PeerInfo::default()
        });
        request
    }

    fn cose_backend() -> SealingBackend {
        let backend = SealingBackend::seeded(COSE_PATH, COSE_PRIVATE.to_vec());
        if let Ok(mut store) = backend.store.lock() {
            store.insert(COSE_WRONG_PATH.to_string(), COSE_WRONG_PRIVATE.to_vec());
            // The pinned keys share the same private so a matching-context envelope
            // still opens; only the pin cross-check differs.
            store.insert(COSE_PIN_PARTIES_PATH.to_string(), COSE_PRIVATE.to_vec());
            store.insert(COSE_PIN_AAD_PATH.to_string(), COSE_PRIVATE.to_vec());
        }
        backend
    }

    fn cose_parties() -> KdfParties {
        KdfParties {
            party_u: PartyIdentity::from_bytes(b"alice".to_vec()).expect("valid PartyU"),
            party_v: PartyIdentity::from_bytes(b"bob".to_vec()).expect("valid PartyV"),
        }
    }

    fn cose_parties_other() -> KdfParties {
        KdfParties {
            party_u: PartyIdentity::from_bytes(b"alice".to_vec()).expect("valid PartyU"),
            party_v: PartyIdentity::from_bytes(b"carol".to_vec()).expect("valid PartyV"),
        }
    }

    fn cose_message(key_id: &str, private: [u8; 32], aad: &[u8], parties: KdfParties) -> Vec<u8> {
        let key_id = KeyId::from_text(key_id).expect("valid key id");
        let recipient = basil_cose::X25519Recipient::new(key_id, Zeroizing::new(private)).public();
        basil_cose::build_encrypted(&EncryptParams {
            content_type: ContentType::new("application/basil.peer".to_string())
                .expect("valid content type"),
            plaintext: b"peer message",
            recipient,
            content_algorithm: ContentAlgorithm::A256Gcm,
            external_aad: ExternalAad::from_bytes(aad.to_vec()),
            kdf_parties: parties,
        })
        .expect("COSE seal succeeds")
        .into_vec()
    }

    /// Build a valid ML-KEM software-custody record JSON sealing `SEED` under the
    /// `SealingBackend` identity envelope, with the AAD the provider reconstructs.
    fn ml_kem_record() -> Vec<u8> {
        use crate::core::crypto_provider::{SoftwareCustodyCatalog, encode_record_bytes};

        let meta = SoftwareCustodyCatalog {
            key_id: "pqc.sealing",
            algorithm: "ml-kem-768",
            provider: "local-software",
            provider_version: "1",
            custody: "software-encrypted",
            storage_key: "pqc/aead",
        };
        let aad = meta.aad(1);
        let mut ciphertext = vec![u8::try_from(aad.len()).expect("aad fits")];
        ciphertext.extend_from_slice(&aad);
        ciphertext.extend_from_slice(&SEED);
        serde_json::json!({
            "schemaVersion": 1,
            "keyId": "pqc.sealing",
            "keyVersion": 1,
            "publicKey": encode_record_bytes(&[0x7A; 1184]),
            "algorithm": "ml-kem-768",
            "provider": "local-software",
            "providerVersion": "1",
            "custody": "software-encrypted",
            "encryptedPrivateKey": {
                "wrappingKey": "pqc/aead",
                "algorithm": "aes-256-gcm",
                "keyVersion": 1,
                "nonce": encode_record_bytes(&[]),
                "ciphertext": encode_record_bytes(&ciphertext),
            }
        })
        .to_string()
        .into_bytes()
    }

    // The wire round trip wraps then unwraps through the gRPC contract; the deny
    // test below fails closed before the provider runs.
    #[tokio::test]
    async fn ml_kem_wrap_unwrap_through_grpc_with_grant() {
        let svc = service(SealingBackend::seeded(SEALING_PATH, ml_kem_record()));
        let wrapped = svc
            .wrap_envelope(request(
                42,
                pb::WrapEnvelopeRequest {
                    key_id: "pqc.sealing".to_string(),
                    plaintext: b"enrollment payload".to_vec(),
                    kem_algorithm: pb::KemAlgorithm::MlKem768.into(),
                    envelope_algorithm: pb::EnvelopeAlgorithm::Aes256Gcm.into(),
                    aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect("wrap succeeds with grant")
            .into_inner()
            .envelope
            .expect("wrap returns an envelope");
        // Self-describing: the wire envelope echoes the requested algorithms.
        assert_eq!(wrapped.kem_algorithm, i32::from(pb::KemAlgorithm::MlKem768));
        assert_eq!(
            wrapped.envelope_algorithm,
            i32::from(pb::EnvelopeAlgorithm::Aes256Gcm)
        );

        let plaintext = svc
            .unwrap_envelope(request(
                42,
                pb::UnwrapEnvelopeRequest {
                    key_id: "pqc.sealing".to_string(),
                    envelope: Some(wrapped),
                    aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect("unwrap succeeds with grant")
            .into_inner()
            .plaintext;
        assert_eq!(plaintext, b"enrollment payload");
    }

    #[tokio::test]
    async fn unseal_cose_through_grpc_with_x25519_key() {
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(COSE_KEY_ID, COSE_PRIVATE, b"ctx", cose_parties());

        let plaintext = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect("unseal succeeds")
            .into_inner()
            .plaintext;
        assert_eq!(plaintext, b"peer message");
    }

    #[tokio::test]
    async fn unseal_cose_wrong_key_fails_closed() {
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(COSE_KEY_ID, COSE_PRIVATE, b"ctx", cose_parties());

        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_WRONG_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect_err("wrong recipient key is rejected");
        assert_eq!(status.code(), Code::InvalidArgument);
    }

    #[tokio::test]
    async fn unseal_cose_wrong_aad_fails_closed() {
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(COSE_KEY_ID, COSE_PRIVATE, b"right", cose_parties());

        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"wrong".to_vec()),
                },
            ))
            .await
            .expect_err("wrong AAD is rejected");
        assert_eq!(status.code(), Code::InvalidArgument);
    }

    fn tamper_party_identity(mut cose_encrypt: Vec<u8>) -> Vec<u8> {
        let offset = cose_encrypt
            .windows(b"alice".len())
            .position(|w| w == b"alice")
            .expect("party identity is encoded");
        let end = offset + b"alica".len();
        cose_encrypt[offset..end].copy_from_slice(b"alica");
        cose_encrypt
    }

    #[tokio::test]
    async fn unseal_cose_tampered_party_info_fails_closed() {
        let svc = service(cose_backend());
        let cose_encrypt = tamper_party_identity(cose_message(
            COSE_KEY_ID,
            COSE_PRIVATE,
            b"ctx",
            cose_parties(),
        ));
        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect_err("unexpected party info is not accepted");
        assert_eq!(status.code(), Code::InvalidArgument);
    }

    // ---- Catalog pinning of the UnsealCose decrypt oracle (basil-2rqj) --------

    #[tokio::test]
    async fn unseal_cose_pinned_parties_match_succeeds() {
        // The key pins partyU=alice/partyV=bob; an envelope carrying exactly those
        // parties opens under the op:decrypt grant.
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(
            COSE_PIN_PARTIES_KEY_ID,
            COSE_PRIVATE,
            b"ctx",
            cose_parties(),
        );
        let plaintext = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_PIN_PARTIES_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect("matching pinned parties open")
            .into_inner()
            .plaintext;
        assert_eq!(plaintext, b"peer message");
    }

    #[tokio::test]
    async fn unseal_cose_pinned_wrong_party_fails_closed() {
        // Same key/grant, but the envelope names partyV=carol, outside the pin.
        // A least-privilege refusal: PermissionDenied, not a decrypt oracle.
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(
            COSE_PIN_PARTIES_KEY_ID,
            COSE_PRIVATE,
            b"ctx",
            cose_parties_other(),
        );
        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_PIN_PARTIES_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect_err("a party outside the pin is refused");
        assert_eq!(status.code(), Code::PermissionDenied);
    }

    #[tokio::test]
    async fn unseal_cose_pinned_absent_party_fails_closed() {
        // The pin requires named parties; an anonymous (nil) envelope is refused.
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(
            COSE_PIN_PARTIES_KEY_ID,
            COSE_PRIVATE,
            b"ctx",
            KdfParties::anonymous(),
        );
        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_PIN_PARTIES_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect_err("absent parties when pinned is refused");
        assert_eq!(status.code(), Code::PermissionDenied);
    }

    #[tokio::test]
    async fn unseal_cose_pinned_aad_match_succeeds() {
        // The key pins external_aad=["ctx"] but not parties; a ctx-bound envelope
        // with any parties opens.
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(
            COSE_PIN_AAD_KEY_ID,
            COSE_PRIVATE,
            b"ctx",
            KdfParties::anonymous(),
        );
        let plaintext = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_PIN_AAD_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"ctx".to_vec()),
                },
            ))
            .await
            .expect("matching pinned external_aad open")
            .into_inner()
            .plaintext;
        assert_eq!(plaintext, b"peer message");
    }

    #[tokio::test]
    async fn unseal_cose_pinned_wrong_aad_fails_closed() {
        // A caller-supplied external_aad outside the pinned set is refused before
        // the private is ever materialized: PermissionDenied.
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(
            COSE_PIN_AAD_KEY_ID,
            COSE_PRIVATE,
            b"other",
            KdfParties::anonymous(),
        );
        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_PIN_AAD_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: Some(b"other".to_vec()),
                },
            ))
            .await
            .expect_err("an external_aad outside the pin is refused");
        assert_eq!(status.code(), Code::PermissionDenied);
    }

    #[tokio::test]
    async fn unseal_cose_pinned_aad_absent_fails_closed() {
        // The pin requires a ctx binding; an absent (empty) external_aad is refused.
        let svc = service(cose_backend());
        let cose_encrypt = cose_message(
            COSE_PIN_AAD_KEY_ID,
            COSE_PRIVATE,
            b"ctx",
            KdfParties::anonymous(),
        );
        let status = svc
            .unseal_cose(request(
                42,
                pb::UnsealCoseRequest {
                    key_id: COSE_PIN_AAD_KEY_ID.to_string(),
                    cose_encrypt,
                    external_aad: None,
                },
            ))
            .await
            .expect_err("absent external_aad when pinned is refused");
        assert_eq!(status.code(), Code::PermissionDenied);
    }

    #[tokio::test]
    async fn ml_kem_wrap_without_software_custody_grant_is_denied() {
        // uid 43 may Encrypt (authorize passes) but lacks op:use_software_custody,
        // so the local-software provider is denied: fail closed as PermissionDenied
        // before any backend access.
        let svc = service(SealingBackend::default());
        let status = svc
            .wrap_envelope(request(
                43,
                pb::WrapEnvelopeRequest {
                    key_id: "pqc.sealing".to_string(),
                    plaintext: b"payload".to_vec(),
                    kem_algorithm: pb::KemAlgorithm::MlKem768.into(),
                    envelope_algorithm: pb::EnvelopeAlgorithm::Aes256Gcm.into(),
                    aad: None,
                },
            ))
            .await
            .expect_err("ml-kem wrap denied without local-software grant");
        assert_eq!(status.code(), Code::PermissionDenied);
    }
}