opentdf 0.18.0

Rust implementation of OpenTDF (Trusted Data Format)
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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! KAS (Key Access Service) client implementation for OpenTDF rewrap protocol
//!
//! This module implements the KAS v2 rewrap protocol for unwrapping encrypted payload keys.
//! It supports both Standard TDF (ZIP-based) and NanoTDF formats with RSA and EC key wrapping.
//!
//! # Protocol Flow
//!
//! ## Standard TDF (TDF3, ZTDF) - RSA-2048:
//! 1. Generate ephemeral RSA-2048 key pair
//! 2. Build unsigned rewrap request with manifest data
//! 3. Accept pre-signed JWT token (ES256) - see `examples/jwt_helper.rs`
//! 4. POST to KAS `/kas.AccessService/Rewrap` (ConnectRPC) endpoint
//! 5. Receive RSA-encrypted wrapped key
//! 6. Unwrap key using RSA-OAEP (SHA-1 default, SHA-256 available)
//!
//! ## NanoTDF - EC P-256:
//! 1. Generate ephemeral EC P-256 key pair
//! 2. Build unsigned rewrap request with manifest data
//! 3. Accept pre-signed JWT token (ES256) - see `examples/jwt_helper.rs`
//! 4. POST to KAS `/kas.AccessService/Rewrap` (ConnectRPC) endpoint
//! 5. Receive wrapped key and session public key
//! 6. Unwrap key using ECDH + HKDF + AES-GCM
//!
//! # JWT Token Creation
//!
//! This client requires pre-signed JWT tokens. For a complete JWT helper implementation,
//! see `examples/jwt_helper.rs`.
//!
//! # Caller key (DPoP)
//!
//! A caller whose access token is bound to its own key (`cnf`), such as an
//! agent, sets that key with [`KasClient::with_caller_key`]. Each rewrap then
//! carries an RFC 9449 DPoP proof and a request token, both signed by that
//! key, and goes to the Connect rewrap endpoint.
//!
//! # Example
//!
//! ```no_run
//! use opentdf::kas::KasClient;
//! use opentdf::kas_discovery::OpentdfConfiguration;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let config = OpentdfConfiguration::for_kas_connect("https://kas.example.com");
//! let client = KasClient::new(&config, "oauth_token_here")?;
//!
//! let manifest = opentdf::TdfManifest::new(
//!     "0.payload".to_string(),
//!     "https://kas.example.com".to_string()
//! );
//!
//! let payload_key = client.rewrap_standard_tdf(&manifest).await?;
//! # Ok(())
//! # }
//! ```

// Allow deprecated warnings for Nonce::from_slice() which is the correct API for aes-gcm 0.10.x
// This will be resolved when aes-gcm updates to generic-array 1.x
#![allow(deprecated)]

use crate::manifest::TdfManifest;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use opentdf_protocol::{KasError, kas::Policy, *};

#[cfg(feature = "kas-client")]
use {
    crate::hkdf::Hkdf,
    crate::p256::{
        PublicKey, SecretKey,
        pkcs8::{DecodePublicKey, EncodePublicKey},
    },
    crate::sha2::{Digest, Sha256},
    aes_gcm::{
        Aes256Gcm, Nonce,
        aead::{Aead, KeyInit},
    },
    aws_lc_rs::{
        encoding::{AsDer, Pkcs8V1Der, PublicKeyX509Der},
        rsa::{KeySize, OAEP_SHA1_MGF1SHA1, OaepPrivateDecryptingKey, PrivateDecryptingKey},
    },
    reqwest::Client,
};

#[cfg(feature = "kas-client")]
pub use crate::kas_dpop::CallerKey;

#[cfg(feature = "kas-client")]
use crate::kas_dpop::{CONNECT_REWRAP_PROCEDURE, REWRAP_HTM};

// NOTE: KAS protocol types are now imported from opentdf-protocol crate
// The types below (KasError, UnsignedRewrapRequest, etc.) are re-exported from there

/// Key type for TDF encryption
#[cfg(feature = "kas-client")]
#[derive(Debug, Clone, Copy)]
pub enum KeyType {
    /// Elliptic Curve (P-256) - used for NanoTDF
    EC,
    /// RSA-2048 - used for Standard TDF (TDF3, ZTDF)
    RSA,
}

/// Ephemeral key pair for KAS communication
pub enum EphemeralKeyPair {
    #[cfg(feature = "kas-client")]
    EC {
        private_key: SecretKey,
        public_key_pem: String,
    },
    #[cfg(feature = "kas-client")]
    RSA {
        /// aws-lc-rs RSA private key for decryption
        private_key: PrivateDecryptingKey,
        public_key_pem: String,
    },
}

#[cfg(feature = "kas-client")]
impl EphemeralKeyPair {
    /// Generate a new ephemeral key pair of the specified type
    ///
    /// Uses aws-lc-rs for RSA key generation (constant-time, FIPS validated).
    pub fn new(key_type: KeyType) -> Result<Self, KasError> {
        use crate::p256::elliptic_curve::Generate;

        match key_type {
            KeyType::EC => {
                // Generate EC P-256 key pair for NanoTDF
                let private_key = SecretKey::generate();
                let public_key = private_key.public_key();

                let public_key_pem = public_key
                    .to_public_key_pem(crate::p256::pkcs8::LineEnding::LF)
                    .map_err(|e| KasError::Pkcs8Error(e.to_string()))?;

                Ok(EphemeralKeyPair::EC {
                    private_key,
                    public_key_pem,
                })
            }
            KeyType::RSA => {
                // Generate RSA-2048 key pair for Standard TDF using aws-lc-rs
                let private_key =
                    PrivateDecryptingKey::generate(KeySize::Rsa2048).map_err(|e| {
                        KasError::CryptoError {
                            operation: "RSA_key_generation".to_string(),
                            reason: format!("RSA key generation failed: {:?}", e),
                        }
                    })?;

                // Get public key from private key and export to DER
                let public_key = private_key.public_key();
                let public_key_der =
                    AsDer::<PublicKeyX509Der>::as_der(&public_key).map_err(|e| {
                        KasError::Pkcs8Error(format!("Failed to export public key: {:?}", e))
                    })?;

                // Convert DER to PEM (ensure trailing newline for consistency)
                let mut public_key_pem =
                    pem::encode(&pem::Pem::new("PUBLIC KEY", public_key_der.as_ref()));
                if !public_key_pem.ends_with('\n') {
                    public_key_pem.push('\n');
                }

                Ok(EphemeralKeyPair::RSA {
                    private_key,
                    public_key_pem,
                })
            }
        }
    }

    /// Get the public key PEM string
    pub fn public_key_pem(&self) -> &str {
        match self {
            EphemeralKeyPair::EC { public_key_pem, .. } => public_key_pem,
            EphemeralKeyPair::RSA { public_key_pem, .. } => public_key_pem,
        }
    }
}

/// KAS client for rewrap protocol
///
/// By default the client signs the rewrap request (the signed request token)
/// with an internal ephemeral RSA key (RS256) and sends the access token as a
/// bearer. [`KasClient::with_caller_key`] switches to the caller's own key.
/// Uses aws-lc-rs for constant-time RSA operations (FIPS validated).
#[cfg(feature = "kas-client")]
pub struct KasClient {
    http_client: Client,
    endpoints: crate::kas_discovery::KasEndpoints,
    oauth_token: String,
    signing_key: PrivateDecryptingKey,
    caller_key: Option<CallerKey>,
}

#[cfg(feature = "kas-client")]
impl KasClient {
    /// Create a new KAS client from a resolved configuration document.
    ///
    /// # Arguments
    ///
    /// * `config` - A pre-resolved `OpentdfConfiguration`. Obtain via
    ///   `fetch_well_known(...)` for discovery-driven setups, or build
    ///   directly with `OpentdfConfiguration::for_kas_connect(base_url)`
    ///   when the platform doesn't expose `/.well-known/opentdf-configuration`.
    ///   `OpentdfConfiguration::for_kas_legacy_rest(base_url)` is the escape
    ///   hatch for pre-ConnectRPC deployments.
    /// * `oauth_token` - The access token sent in the `Authorization` header.
    ///   Opaque passthrough: pass a JWT or a base64url-encoded CWT — the
    ///   server decides how to validate. Sent as `Bearer <token>` by default.
    ///   Once [`KasClient::with_caller_key`] sets a caller key, requests
    ///   switch to `Authorization: DPoP <token>` plus an RFC 9449 DPoP proof.
    ///
    /// # Security
    ///
    /// Both resolved KAS URLs (rewrap and public-key) are validated during
    /// endpoint resolution (see [`crate::kas_discovery::validate_kas_url`]):
    /// - **HTTPS required**: HTTP is only allowed for `localhost`/`127.0.0.1`/`::1` (development use)
    /// - **SSRF protection**: Private and link-local IP addresses are rejected (IPv4 and IPv6, including IPv4-mapped literals)
    /// - **Scheme validation**: Only `http` and `https` schemes are accepted
    /// - **No redirects**: The rewrap HTTP client follows no redirects, so a 3xx
    ///   cannot re-issue the bearer-carrying request to an unvalidated host
    ///
    /// # Note
    ///
    /// This client generates an ephemeral RSA-2048 key pair for signing the
    /// inner JWT rewrap request envelope. That is separate from the access
    /// token — the inner JWT is the rewrap-request signature; the `oauth_token`
    /// is the platform-issued access token. When [`KasClient::with_caller_key`]
    /// sets a caller key, that caller key signs the inner (signed request)
    /// token instead of the ephemeral RSA key.
    pub fn new(
        config: &crate::kas_discovery::OpentdfConfiguration,
        oauth_token: impl Into<String>,
    ) -> Result<Self, KasError> {
        // `from_config` validates both the rewrap and public-key URLs for
        // HTTPS / scheme / SSRF constraints before returning.
        let endpoints = crate::kas_discovery::KasEndpoints::from_config(config)?;

        // Disable redirect following. The KAS rewrap endpoint is an RPC target
        // that should never redirect; allowing redirects would let a 3xx from a
        // validated host re-issue the bearer-carrying request to an unvalidated
        // one (e.g. an internal address), since `validate_kas_url` only runs on
        // the initial URL, not per-hop.
        let http_client = Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|e| KasError::HttpError {
                status: 0,
                message: format!("Failed to build HTTP client: {}", e),
            })?;

        let signing_key = PrivateDecryptingKey::generate(KeySize::Rsa2048).map_err(|e| {
            KasError::CryptoError {
                operation: "generate_signing_key".to_string(),
                reason: format!("Failed to generate RSA signing key: {:?}", e),
            }
        })?;

        Ok(Self {
            http_client,
            endpoints,
            oauth_token: oauth_token.into(),
            signing_key,
            caller_key: None,
        })
    }

    /// Bind this client to the caller's own key: the key its access token
    /// names in `cnf`.
    ///
    /// Every rewrap then:
    /// - signs the signed request token with `key` (`EdDSA` for Ed25519,
    ///   `ES256` for P-256) instead of the ephemeral RSA key;
    /// - sends `Authorization: DPoP <token>` and a `DPoP` proof signed by
    ///   `key`, built at send time from the current token, with `htu` set to
    ///   the Connect procedure `/kas.AccessService/Rewrap`;
    /// - requires the Connect rewrap endpoint. A configuration that resolved
    ///   to the legacy REST endpoint fails with [`KasError::ConfigError`]
    ///   before any request is sent.
    ///
    /// ```
    /// use opentdf::kas::{CallerKey, KasClient};
    /// use opentdf::kas_discovery::OpentdfConfiguration;
    ///
    /// let cfg = OpentdfConfiguration::for_kas_connect("https://platform.arkavo.net");
    /// let agent_key = opentdf::ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
    /// let client = KasClient::new(&cfg, "agent-access-token")?
    ///     .with_caller_key(CallerKey::Ed25519(agent_key));
    /// # drop(client);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn with_caller_key(mut self, key: CallerKey) -> Self {
        self.caller_key = Some(key);
        self
    }

    /// Replace the access token used from the next request on.
    ///
    /// Agent tokens are short-lived and refreshed while the client lives. The
    /// DPoP `ath` is computed from this token at send time, so a refreshed
    /// token is bound on its first use.
    pub fn set_access_token(&mut self, oauth_token: impl Into<String>) {
        self.oauth_token = oauth_token.into();
    }

    /// Caller-bound rewraps go only to the Connect procedure: the proof's
    /// `htu` names it, and the REST path behind a proxy cannot verify `htu`.
    fn require_connect_rewrap(&self) -> Result<(), KasError> {
        use crate::kas_discovery::KasTransport;
        // Both checks are needed: `transport` records how the endpoint was
        // discovered/configured, not the path actually resolved, so a
        // Connect-advertised endpoint could still carry a non-standard rewrap
        // path; the URL suffix check catches that. And `htu` in the DPoP
        // proof is always the well-known procedure path, so it must equal
        // what we're about to call, not merely look like a Connect endpoint.
        let is_connect_rewrap = self.endpoints.transport == KasTransport::Connect
            && url::Url::parse(&self.endpoints.rewrap_url)
                .is_ok_and(|u| u.path().ends_with(CONNECT_REWRAP_PROCEDURE));
        if is_connect_rewrap {
            Ok(())
        } else {
            Err(KasError::ConfigError {
                reason: format!(
                    "caller-key (DPoP) rewrap requires the Connect endpoint {}; resolved rewrap URL is {}",
                    CONNECT_REWRAP_PROCEDURE, self.endpoints.rewrap_url
                ),
            })
        }
    }

    /// Internal helper for sending signed rewrap requests to KAS via ConnectRPC
    ///
    /// Handles HTTP POST to /kas.AccessService/Rewrap, parses Connect error
    /// envelopes for richer error messages, and deserializes the response.
    async fn send_rewrap_request(
        &self,
        signed_request: &SignedRewrapRequest,
    ) -> Result<RewrapResponse, KasError> {
        let request = self
            .http_client
            .post(&self.endpoints.rewrap_url)
            .header("Content-Type", "application/json");
        let request = match &self.caller_key {
            None => request.header("Authorization", format!("Bearer {}", self.oauth_token)),
            Some(caller_key) => {
                self.require_connect_rewrap()?;
                // Built per request from the current token, so `ath` binds a
                // token replaced with `set_access_token` on its first use.
                let proof = caller_key.dpop_proof(
                    REWRAP_HTM,
                    CONNECT_REWRAP_PROCEDURE,
                    &self.oauth_token,
                )?;
                request
                    .header("Authorization", format!("DPoP {}", self.oauth_token))
                    .header("DPoP", proof)
                    .header("Connect-Protocol-Version", "1")
            }
        };
        let response =
            request
                .json(signed_request)
                .send()
                .await
                .map_err(|e| KasError::RequestError {
                    method: "POST".to_string(),
                    url: self.endpoints.rewrap_url.clone(),
                    reason: e.to_string(),
                })?;

        let status = response.status();
        if !status.is_success() {
            let error_body = response.text().await.unwrap_or_default();
            let detail = crate::kas_discovery::parse_connect_error(&error_body)
                .map(|e| format!("{}: {}", e.code, e.message))
                .unwrap_or_else(|| {
                    if error_body.is_empty() {
                        format!("HTTP {}", status)
                    } else {
                        error_body.clone()
                    }
                });

            return Err(match status.as_u16() {
                401 => KasError::AuthenticationFailed { reason: detail },
                403 => KasError::AccessDenied {
                    resource: "KAS endpoint".to_string(),
                    reason: detail,
                },
                _ => KasError::HttpError {
                    status: status.as_u16(),
                    message: detail,
                },
            });
        }

        response
            .json()
            .await
            .map_err(|e| KasError::InvalidResponse {
                reason: format!("Failed to parse JSON response: {}", e),
                expected: Some("RewrapResponse".to_string()),
            })
    }

    /// Rewrap a key from a Standard TDF manifest
    ///
    /// This performs the complete KAS rewrap flow:
    /// 1. Generate RSA-2048 ephemeral key pair (Standard TDF uses RSA)
    /// 2. Build unsigned rewrap request
    /// 3. Sign request with internal signing key to create JWT (RS256)
    /// 4. POST to KAS /kas.AccessService/Rewrap (ConnectRPC) endpoint with signed JWT
    /// 5. Unwrap the returned key using RSA-OAEP
    ///
    /// # Arguments
    ///
    /// * `manifest` - TDF manifest containing the wrapped key
    ///
    /// Perform KAS rewrap for NanoTDF
    ///
    /// Sends the NanoTDF header bytes to KAS which extracts the ephemeral public key
    /// and performs ECDH to derive the symmetric encryption key.
    ///
    /// # Arguments
    /// * `header_bytes` - The serialized NanoTDF header
    /// * `kas_url` - The KAS URL from the NanoTDF header
    ///
    /// # Returns
    /// The symmetric key for decrypting the NanoTDF payload
    pub async fn rewrap_nanotdf(
        &self,
        header_bytes: &[u8],
        kas_url: &str,
    ) -> Result<Vec<u8>, KasError> {
        // Build unsigned rewrap request for NanoTDF
        let unsigned_request = self.build_nanotdf_rewrap_request(header_bytes, kas_url)?;

        // Create and sign JWT
        let signed_request_token = self.sign_rewrap_request(&unsigned_request)?;

        // Wrap in SignedRewrapRequest
        let signed_request = SignedRewrapRequest {
            signed_request_token,
        };

        // Send request and parse response
        let rewrap_response = self.send_rewrap_request(&signed_request).await?;

        // For NanoTDF, extract the DEK (symmetric key) directly from response
        // The KAS has already performed ECDH and derived the key
        self.extract_nanotdf_key(&rewrap_response)
    }

    /// Returns the unwrapped payload key ready for TDF decryption
    pub async fn rewrap_standard_tdf(&self, manifest: &TdfManifest) -> Result<Vec<u8>, KasError> {
        // Generate RSA ephemeral key pair for Standard TDF
        let ephemeral_key_pair = EphemeralKeyPair::new(KeyType::RSA)?;

        // Build the unsigned rewrap request
        let unsigned_request = self.build_rewrap_request(manifest, &ephemeral_key_pair)?;

        // Create and sign JWT with the unsigned request
        let signed_request_token = self.sign_rewrap_request(&unsigned_request)?;

        // Wrap the signed token in SignedRewrapRequest per OpenTDF protocol
        let signed_request = SignedRewrapRequest {
            signed_request_token,
        };

        // Send request and parse response
        let rewrap_response = self.send_rewrap_request(&signed_request).await?;

        // Extract the wrapped key and session public key
        let (wrapped_key, session_public_key_pem) = self.extract_wrapped_key(&rewrap_response)?;

        // Unwrap the key using ECDH + HKDF + AES-GCM
        let payload_key =
            self.unwrap_key(&wrapped_key, &session_public_key_pem, &ephemeral_key_pair)?;

        Ok(payload_key)
    }

    /// Sign an unsigned rewrap request to create a JWT
    ///
    /// Creates a JWT with the following structure:
    /// ```json
    /// {
    ///   "requestBody": "<json-serialized-UnsignedRewrapRequest>",
    ///   "iat": <timestamp>,
    ///   "exp": <timestamp+60>
    /// }
    /// ```
    ///
    /// The JWT is signed with RS256 using the client's internal signing key,
    /// or with the caller key (`EdDSA`/`ES256`) when one is set.
    /// Uses aws-lc-rs for constant-time RSA operations (FIPS validated).
    fn sign_rewrap_request(&self, request: &UnsignedRewrapRequest) -> Result<String, KasError> {
        use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Serialize, Deserialize)]
        struct Claims {
            #[serde(rename = "requestBody")]
            request_body: String,
            iat: i64,
            exp: i64,
        }

        // Serialize the unsigned request to JSON
        let request_json = serde_json::to_string(request).map_err(KasError::SerializationError)?;

        // Create JWT claims
        let now = chrono::Utc::now().timestamp();

        // The KAS verifies the SRT with the key the caller proved possession
        // of, so a caller-bound token needs the SRT signed by that same key.
        if let Some(caller_key) = &self.caller_key {
            return caller_key.signed_request_token_at(&request_json, now);
        }

        let claims = Claims {
            request_body: request_json,
            iat: now,
            exp: now + 60, // 60 second expiration
        };

        // Convert aws-lc-rs RSA private key to PKCS#8 PEM format for jsonwebtoken
        // jsonwebtoken's from_rsa_der expects PKCS#1, but aws-lc-rs exports PKCS#8
        // Use from_rsa_pem instead which accepts PKCS#8 PEM
        let key_der = AsDer::<Pkcs8V1Der>::as_der(&self.signing_key)
            .map_err(|e| KasError::Pkcs8Error(format!("Failed to encode signing key: {:?}", e)))?;

        let key_pem = pem::encode(&pem::Pem::new("PRIVATE KEY", key_der.as_ref()));

        let encoding_key = EncodingKey::from_rsa_pem(key_pem.as_bytes())
            .map_err(|e| KasError::Pkcs8Error(format!("Failed to parse RSA PEM: {}", e)))?;

        // Sign the JWT with RS256
        let token =
            encode(&Header::new(Algorithm::RS256), &claims, &encoding_key).map_err(|e| {
                KasError::JwtError {
                    operation: "sign_jwt".to_string(),
                    reason: format!("Failed to sign JWT: {}", e),
                }
            })?;

        Ok(token)
    }

    /// Extract policy UUID from base64-encoded policy JSON
    ///
    /// The policy is stored as base64-encoded JSON in the manifest.
    /// This function decodes and parses it to extract the UUID field.
    fn extract_policy_uuid(&self, base64_policy: &str) -> Result<String, KasError> {
        // Decode base64 policy
        let policy_bytes = BASE64
            .decode(base64_policy)
            .map_err(KasError::Base64Error)?;

        // Parse JSON
        let policy_json: serde_json::Value =
            serde_json::from_slice(&policy_bytes).map_err(|e| KasError::InvalidResponse {
                reason: format!("Failed to parse policy JSON: {}", e),
                expected: Some("valid JSON policy".to_string()),
            })?;

        // Extract UUID field
        let uuid = policy_json
            .get("uuid")
            .and_then(|v| v.as_str())
            .ok_or_else(|| KasError::InvalidResponse {
                reason: "Policy missing 'uuid' field".to_string(),
                expected: Some("uuid field in policy".to_string()),
            })?;

        // Validate UUID format (should be 36 characters with hyphens)
        if uuid.len() != 36 {
            return Err(KasError::InvalidResponse {
                reason: format!(
                    "Invalid UUID format: expected 36 characters, got {}",
                    uuid.len()
                ),
                expected: Some("36-character UUID".to_string()),
            });
        }

        Ok(uuid.to_string())
    }

    /// Build the unsigned rewrap request from manifest data
    fn build_rewrap_request(
        &self,
        manifest: &TdfManifest,
        ephemeral_key_pair: &EphemeralKeyPair,
    ) -> Result<UnsignedRewrapRequest, KasError> {
        // Convert manifest key access objects to KAS format
        let key_access_wrappers: Vec<KeyAccessObjectWrapper> = manifest
            .encryption_information
            .key_access
            .iter()
            .enumerate()
            .map(|(idx, kao)| {
                // Decode wrapped key to ensure it's valid base64
                let wrapped_key_bytes = BASE64
                    .decode(&kao.wrapped_key)
                    .map_err(KasError::Base64Error)?;

                Ok(KeyAccessObjectWrapper {
                    key_access_object_id: format!("kao-{}", idx),
                    key_access_object: KeyAccessObject {
                        key_type: kao.access_type.clone(),
                        url: kao.url.clone(),
                        protocol: kao.protocol.clone(),
                        wrapped_key: BASE64.encode(&wrapped_key_bytes),
                        policy_binding: KasPolicyBinding {
                            hash: kao.policy_binding.hash.clone(),
                            algorithm: Some(kao.policy_binding.alg.clone()),
                        },
                        encrypted_metadata: kao.encrypted_metadata.clone(),
                        kid: kao.kid.clone(),
                        header: None, // Not used for standard TDF
                        ephemeral_public_key: kao.ephemeral_public_key.clone(),
                    },
                })
            })
            .collect::<Result<Vec<_>, KasError>>()?;

        // Create policy from manifest
        // Extract UUID from the base64-encoded policy JSON
        let policy_uuid = self.extract_policy_uuid(&manifest.encryption_information.policy)?;
        let policy = Policy {
            id: policy_uuid,
            body: manifest.encryption_information.policy.clone(),
        };

        // Create policy request
        let policy_request = PolicyRequest {
            algorithm: None, // For Standard TDF, algorithm is optional and should be None
            policy,
            key_access_objects: key_access_wrappers,
        };

        Ok(UnsignedRewrapRequest {
            client_public_key: ephemeral_key_pair.public_key_pem().to_string(),
            requests: vec![policy_request],
        })
    }

    /// Build unsigned rewrap request for NanoTDF
    fn build_nanotdf_rewrap_request(
        &self,
        header_bytes: &[u8],
        kas_url: &str,
    ) -> Result<UnsignedRewrapRequest, KasError> {
        use base64::Engine;

        // For NanoTDF, we send the header bytes as base64 in the KeyAccessObject
        let header_b64 = BASE64.encode(header_bytes);

        let key_access_object = KeyAccessObjectWrapper {
            key_access_object_id: "kao-0".to_string(),
            key_access_object: KeyAccessObject {
                key_type: "wrapped".to_string(),
                url: kas_url.to_string(),
                protocol: "kas".to_string(),
                wrapped_key: String::new(), // Not used for NanoTDF
                policy_binding: KasPolicyBinding {
                    hash: String::new(), // Extracted from header by KAS
                    algorithm: Some("HS256".to_string()),
                },
                encrypted_metadata: None,
                kid: None,
                header: Some(header_b64),   // NanoTDF header bytes (base64)
                ephemeral_public_key: None, // Not used for NanoTDF rewrap
            },
        };

        // Create policy request
        let policy_request = PolicyRequest {
            algorithm: Some("ec:secp256r1".to_string()), // NanoTDF uses EC algorithm
            policy: Policy {
                id: "policy".to_string(),
                body: String::new(), // Policy is in the header
            },
            key_access_objects: vec![key_access_object],
        };

        Ok(UnsignedRewrapRequest {
            client_public_key: String::new(), // Not used for NanoTDF
            requests: vec![policy_request],
        })
    }

    /// Extract the symmetric key from NanoTDF rewrap response
    fn extract_nanotdf_key(&self, response: &RewrapResponse) -> Result<Vec<u8>, KasError> {
        let policy_result =
            response
                .responses
                .first()
                .ok_or_else(|| KasError::InvalidResponse {
                    reason: "Empty response from KAS".to_string(),
                    expected: Some("at least one policy response".to_string()),
                })?;

        let key_result =
            policy_result
                .results
                .first()
                .ok_or_else(|| KasError::InvalidResponse {
                    reason: "No key access object in response".to_string(),
                    expected: Some("at least one KAO result".to_string()),
                })?;

        // For NanoTDF, the DEK is returned directly (base64 encoded)
        let dek_b64 =
            key_result
                .entity_wrapped_key
                .as_ref()
                .ok_or_else(|| KasError::InvalidResponse {
                    reason: "No DEK in NanoTDF rewrap response".to_string(),
                    expected: Some("entity_wrapped_key field".to_string()),
                })?;

        // Decode the symmetric key
        BASE64.decode(dek_b64).map_err(KasError::Base64Error)
    }

    /// Extract wrapped key from rewrap response
    fn extract_wrapped_key(
        &self,
        response: &RewrapResponse,
    ) -> Result<(Vec<u8>, String), KasError> {
        let policy_result =
            response
                .responses
                .first()
                .ok_or_else(|| KasError::InvalidResponse {
                    reason: "Empty response from KAS".to_string(),
                    expected: Some("at least one policy response".to_string()),
                })?;

        let key_result =
            policy_result
                .results
                .first()
                .ok_or_else(|| KasError::InvalidResponse {
                    reason: "No key results in response".to_string(),
                    expected: Some("at least one key result".to_string()),
                })?;

        // Check status
        if key_result.status != "permit" {
            let error_msg = key_result
                .error
                .clone()
                .unwrap_or_else(|| "Access denied".to_string());
            return Err(KasError::AccessDenied {
                resource: "key".to_string(),
                reason: error_msg,
            });
        }

        // Get wrapped key (try kasWrappedKey first, then entityWrappedKey for legacy)
        let wrapped_key_b64 = key_result
            .kas_wrapped_key
            .as_ref()
            .or(key_result.entity_wrapped_key.as_ref())
            .ok_or_else(|| KasError::InvalidResponse {
                reason: "Missing wrapped key in response".to_string(),
                expected: Some("kasWrappedKey or entityWrappedKey".to_string()),
            })?;

        let wrapped_key = BASE64.decode(wrapped_key_b64)?;

        // Session public key is required for EC rewrap (EC client key) but optional
        // for Standard TDF RSA rewrap: KAS returns the DEK encrypted to the client's
        // RSA public key with no ECDH session material.
        let session_public_key = response.session_public_key.clone().unwrap_or_default();

        Ok((wrapped_key, session_public_key))
    }

    /// Unwrap the key based on key type (EC or RSA)
    ///
    /// # Protocol
    ///
    /// ## For RSA rewrap (Standard TDF - TDF3, ZTDF):
    /// 1. KAS returns wrapped_key directly encrypted with client's RSA public key
    /// 2. Decrypt using client's RSA private key with OAEP padding (SHA-1)
    /// 3. Return the unwrapped payload key
    ///
    /// ## For EC rewrap (Standard TDF with an EC client key):
    /// 1. ECDH: client_private × session_public → shared_secret
    /// 2. HKDF-SHA256: salt=SHA256("TDF"), empty info, shared_secret → symmetric_key
    /// 3. AES-256-GCM decrypt: wrapped_key (nonce ‖ ciphertext ‖ tag) → payload_key
    ///
    /// This is the session key the OpenTDF platform derives when a TDF3 rewrap
    /// request carries an EC `clientPublicKey`. In `opentdf/platform`:
    /// - KAS: `Provider.tdf3Rewrap` (`service/kas/access/rewrap.go`) wraps with
    ///   `ocrypto.FromPublicPEMWithSalt(clientPublicKey, security.TDFSalt(), nil)`;
    ///   `TDFSalt` (`service/internal/security/standard_crypto.go`) is
    ///   SHA256("TDF"), and `ECEncryptor.Encrypt` (`lib/ocrypto/asym_encryption.go`)
    ///   is the ECDH + HKDF + AES-GCM above.
    /// - Go SDK: `KASClient.handleECKeyResponse` (`sdk/kas_client.go`) derives
    ///   the same key with `ocrypto.CalculateHKDF(SHA256("TDF"), ecdhKey)`.
    ///
    /// It is **not** the NanoTDF derivation. NanoTDF rewrap salted the session
    /// key with SHA256("L1L") (`nanoUnwrap` / `versionSalt` in the Go SDK, until
    /// NanoTDF was removed in opentdf/platform#3013); `opentdf_kas::ec_unwrap`
    /// implements that one. [`KasClient::rewrap_nanotdf`] does not call this
    /// function.
    ///
    /// Uses aws-lc-rs for constant-time RSA operations (FIPS validated).
    fn unwrap_key(
        &self,
        wrapped_key: &[u8],
        session_public_key_pem: &str,
        ephemeral_key_pair: &EphemeralKeyPair,
    ) -> Result<Vec<u8>, KasError> {
        match ephemeral_key_pair {
            EphemeralKeyPair::RSA { private_key, .. } => {
                // RSA-OAEP decryption for Standard TDF using aws-lc-rs
                //
                // SECURITY NOTE: Using SHA-1 with RSA-OAEP for Go SDK compatibility
                //
                // ⚠️  SHA-1 is cryptographically deprecated (collision attacks since 2017)
                // However, it's required to match the OpenTDF platform implementation.
                // The Go SDK uses SHA-1 for RSA-OAEP padding (see platform/lib/ocrypto/asym_decryption.go:104)
                //
                // This is a known limitation for cross-platform interoperability.
                // TODO: File issue to migrate entire OpenTDF ecosystem to SHA-256
                //
                // See: https://shattered.io/ for SHA-1 collision attack details
                //
                // aws-lc-rs provides constant-time RSA operations, eliminating timing attacks

                // Create OAEP decrypting key
                let oaep_key = OaepPrivateDecryptingKey::new(private_key.clone()).map_err(|e| {
                    KasError::CryptoError {
                        operation: "create_oaep_key".to_string(),
                        reason: format!("Failed to create OAEP key: {:?}", e),
                    }
                })?;

                // Allocate plaintext buffer
                let mut plaintext = vec![0u8; oaep_key.min_output_size()];

                // Decrypt using SHA-1 OAEP
                let plaintext_slice = oaep_key
                    .decrypt(&OAEP_SHA1_MGF1SHA1, wrapped_key, &mut plaintext, None)
                    .map_err(|e| KasError::UnwrapError {
                        algorithm: "RSA-OAEP".to_string(),
                        reason: format!("RSA-OAEP decryption failed: {:?}", e),
                    })?;

                Ok(plaintext_slice.to_vec())
            }
            EphemeralKeyPair::EC { private_key, .. } => {
                // EC/ECDH unwrap (EC client key) — sessionPublicKey is required.
                // (RSA/Standard TDF may pass empty string; EC must not.)
                if session_public_key_pem.trim().is_empty() {
                    return Err(KasError::InvalidResponse {
                        reason: "Missing session public key in response".to_string(),
                        expected: Some("sessionPublicKey".to_string()),
                    });
                }
                // Parse session public key from PEM
                let session_public_key = PublicKey::from_public_key_pem(session_public_key_pem)
                    .map_err(|e| KasError::CryptoError {
                        operation: "parse_session_public_key".to_string(),
                        reason: format!("Failed to parse session public key: {}", e),
                    })?;

                // Perform ECDH key agreement
                let shared_secret = crate::p256::ecdh::diffie_hellman(
                    private_key.to_nonzero_scalar(),
                    session_public_key.as_affine(),
                );

                // Derive the session key: HKDF-SHA256, salt = SHA256("TDF"), empty info.
                // Same salt as opentdf/platform `security.TDFSalt()` (KAS,
                // `Provider.tdf3Rewrap`) and `KASClient.handleECKeyResponse` (Go SDK).
                // The NanoTDF salts SHA256("L1L"/"L1M") belong to a different
                // derivation; see the doc comment on this function.
                let mut salt_hasher = Sha256::new();
                salt_hasher.update(b"TDF");
                let salt = salt_hasher.finalize();

                let hkdf = Hkdf::<Sha256>::new(Some(&salt), shared_secret.raw_secret_bytes());
                let mut symmetric_key = [0u8; 32];
                hkdf.expand(&[], &mut symmetric_key)
                    .map_err(|e| KasError::CryptoError {
                        operation: "HKDF".to_string(),
                        reason: format!("HKDF expansion failed: {}", e),
                    })?;

                // Unwrap key using AES-GCM
                // Format: nonce (12 bytes) || ciphertext || tag (16 bytes)
                if wrapped_key.len() < 28 {
                    return Err(KasError::UnwrapError {
                        algorithm: "ECDH-AES-GCM".to_string(),
                        reason: format!(
                            "Wrapped key too short: {} bytes (expected at least 28)",
                            wrapped_key.len()
                        ),
                    });
                }

                let nonce = Nonce::from_slice(&wrapped_key[..12]);
                let ciphertext_and_tag = &wrapped_key[12..];

                let cipher = Aes256Gcm::new_from_slice(&symmetric_key).map_err(|e| {
                    KasError::CryptoError {
                        operation: "AES-GCM-init".to_string(),
                        reason: format!("Failed to create cipher: {}", e),
                    }
                })?;

                let payload_key = cipher.decrypt(nonce, ciphertext_and_tag).map_err(|e| {
                    KasError::UnwrapError {
                        algorithm: "AES-GCM".to_string(),
                        reason: format!("AES-GCM decryption failed: {}", e),
                    }
                })?;

                Ok(payload_key)
            }
        }
    }
}

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

    #[test]
    fn test_ephemeral_key_pair_generation() {
        #[cfg(feature = "kas-client")]
        {
            // Test RSA key generation
            let key_pair_rsa =
                EphemeralKeyPair::new(KeyType::RSA).expect("Failed to generate RSA key pair");
            assert!(
                key_pair_rsa
                    .public_key_pem()
                    .starts_with("-----BEGIN PUBLIC KEY-----")
            );

            // Test EC key generation
            let key_pair_ec =
                EphemeralKeyPair::new(KeyType::EC).expect("Failed to generate EC key pair");
            assert!(
                key_pair_ec
                    .public_key_pem()
                    .starts_with("-----BEGIN PUBLIC KEY-----")
            );
        }
    }

    #[test]
    fn test_policy_serialization() {
        let policy = Policy {
            id: "test-policy".to_string(),
            body: BASE64.encode(b"test-policy-body"),
        };

        let json = serde_json::to_string(&policy).expect("Failed to serialize");
        assert!(json.contains("test-policy"));
    }

    #[cfg(feature = "kas-client")]
    mod url_validation_tests {
        use super::*;
        use crate::kas_discovery::OpentdfConfiguration;

        /// Helper: construct via for_kas_connect and capture the error.
        fn expect_err(url: &str) -> KasError {
            let cfg = OpentdfConfiguration::for_kas_connect(url);
            match KasClient::new(&cfg, "token") {
                Err(e) => e,
                Ok(_) => panic!("Expected error for {url}, got Ok"),
            }
        }

        #[test]
        fn test_kas_rejects_http_url() {
            let err = expect_err("http://evil.com");
            assert!(matches!(err, KasError::InvalidUrl(_)), "got: {err}");
            assert!(err.to_string().contains("HTTPS"));
        }

        #[test]
        fn test_kas_accepts_https_url() {
            let cfg = OpentdfConfiguration::for_kas_connect("https://kas.example.com");
            assert!(KasClient::new(&cfg, "token").is_ok());
        }

        #[test]
        fn test_kas_allows_http_localhost() {
            for base in [
                "http://127.0.0.1:8080",
                "http://localhost:8080",
                "http://[::1]:8080",
            ] {
                let cfg = OpentdfConfiguration::for_kas_connect(base);
                assert!(
                    KasClient::new(&cfg, "token").is_ok(),
                    "HTTP loopback {base} should be allowed"
                );
            }
        }

        #[test]
        fn test_kas_rejects_private_ip() {
            for base in [
                "https://10.0.0.1",
                "https://172.16.0.1",
                "https://192.168.1.1",
            ] {
                let err = expect_err(base);
                assert!(matches!(err, KasError::InvalidUrl(_)), "{base}: {err}");
            }
        }

        #[test]
        fn test_kas_rejects_metadata_ip() {
            let err = expect_err("http://169.254.169.254");
            assert!(matches!(err, KasError::InvalidUrl(_)), "got: {err}");
        }

        #[test]
        fn test_kas_rejects_invalid_scheme() {
            let err = expect_err("ftp://kas.example.com");
            assert!(matches!(err, KasError::InvalidUrl(_)), "got: {err}");
            assert!(err.to_string().contains("ftp"));
        }

        #[test]
        fn test_kas_rejects_invalid_url() {
            let err = expect_err("not-a-url");
            assert!(matches!(err, KasError::InvalidUrl(_)), "got: {err}");
        }
    }
}