lake-client 0.34.0

TiDB Cloud Lake Client for Rust
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
// Copyright 2025 TiDB Cloud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use reqwest::RequestBuilder;
use serde::Serialize;

use crate::error::{Error, Result};

pub trait Auth: Sync + Send {
    fn wrap(&self, builder: RequestBuilder) -> Result<RequestBuilder>;
    fn can_reload(&self) -> bool {
        false
    }
    fn username(&self) -> String;
}

#[derive(Clone)]
pub struct BasicAuth {
    username: String,
    password: SensitiveString,
}

impl BasicAuth {
    pub fn new(username: impl ToString, password: impl ToString) -> Self {
        Self {
            username: username.to_string(),
            password: SensitiveString(password.to_string()),
        }
    }
}

impl Auth for BasicAuth {
    fn wrap(&self, builder: RequestBuilder) -> Result<RequestBuilder> {
        Ok(builder.basic_auth(&self.username, Some(self.password.inner())))
    }

    fn username(&self) -> String {
        self.username.clone()
    }
}

#[derive(Clone)]
pub struct AccessTokenAuth {
    token: SensitiveString,
}

impl AccessTokenAuth {
    pub fn new(token: impl ToString) -> Self {
        Self {
            token: SensitiveString::from(token.to_string()),
        }
    }
}

impl Auth for AccessTokenAuth {
    fn wrap(&self, builder: RequestBuilder) -> Result<RequestBuilder> {
        Ok(builder.bearer_auth(self.token.inner()))
    }

    fn username(&self) -> String {
        "token".to_string()
    }
}

#[derive(Clone)]
pub struct AccessTokenFileAuth {
    token_file: String,
}

impl AccessTokenFileAuth {
    pub fn new(token_file: impl ToString) -> Self {
        let token_file = token_file.to_string();
        Self { token_file }
    }
}

impl Auth for AccessTokenFileAuth {
    fn wrap(&self, builder: RequestBuilder) -> Result<RequestBuilder> {
        let token = std::fs::read_to_string(&self.token_file).map_err(|e| {
            Error::IO(format!(
                "cannot read access token from file {}: {}",
                self.token_file, e
            ))
        })?;
        Ok(builder.bearer_auth(token.trim()))
    }

    fn can_reload(&self) -> bool {
        true
    }

    fn username(&self) -> String {
        "token".to_string()
    }
}

const HEADER_AUTH_METHOD: &str = "X-DATABEND-AUTH-METHOD";
const KEYPAIR_TOKEN_TTL_SECS: u64 = 60;

#[derive(Serialize)]
struct KeyPairClaims {
    sub: String,
    iat: u64,
    exp: u64,
}

#[derive(Clone)]
pub struct KeyPairAuth {
    username: String,
    encoding_key: Arc<EncodingKey>,
    algorithm: Algorithm,
}

impl KeyPairAuth {
    pub fn new(
        username: impl ToString,
        private_key_file: &str,
        passphrase_file: Option<&str>,
    ) -> Result<Self> {
        let pem_data = std::fs::read(private_key_file).map_err(|e| {
            Error::IO(format!(
                "cannot read private key from file {}: {}",
                private_key_file, e
            ))
        })?;

        let passphrase = match passphrase_file {
            Some(path) => {
                let p = std::fs::read_to_string(path).map_err(|e| {
                    Error::IO(format!("cannot read passphrase from file {}: {}", path, e))
                })?;
                Some(Self::strip_line_ending(p))
            }
            None => None,
        };

        let (encoding_key, algorithm) = Self::parse_private_key(&pem_data, passphrase.as_deref())?;

        Ok(Self {
            username: username.to_string(),
            encoding_key: Arc::new(encoding_key),
            algorithm,
        })
    }

    fn strip_line_ending(mut value: String) -> String {
        if value.ends_with('\n') {
            value.pop();
            if value.ends_with('\r') {
                value.pop();
            }
        }
        value
    }

    fn parse_private_key(
        pem_data: &[u8],
        passphrase: Option<&str>,
    ) -> Result<(EncodingKey, Algorithm)> {
        let pem_str = std::str::from_utf8(pem_data)
            .map_err(|e| Error::IO(format!("private key is not valid UTF-8: {e}")))?;

        if let Some(passphrase) = passphrase {
            let pem = Self::parse_pem_block(pem_data, "ENCRYPTED PRIVATE KEY").map_err(|_| {
                Error::IO(
                    "encrypted private keys with passphrase must use PKCS#8 PEM (BEGIN ENCRYPTED PRIVATE KEY)".to_string(),
                )
            })?;
            // Encrypted PKCS#8 key — decrypt using pkcs8 crate to get DER.
            Self::parse_encrypted_key(pem.contents(), passphrase)
        } else {
            // Unencrypted key — detect type and use jsonwebtoken's PEM methods
            Self::parse_unencrypted_key(pem_data, pem_str)
        }
    }

    fn parse_encrypted_key(
        encrypted_der: &[u8],
        passphrase: &str,
    ) -> Result<(EncodingKey, Algorithm)> {
        let doc = pkcs8::EncryptedPrivateKeyInfoRef::try_from(encrypted_der)
            .and_then(|encrypted| encrypted.decrypt(passphrase.as_bytes()))
            .map_err(|e| Error::IO(format!("failed to decrypt private key: {e}")))?;

        let der_bytes = doc.as_bytes();

        // Try each key type with DER
        // from_*_der returns EncodingKey directly (infallible for the struct construction),
        // but the underlying parsing may still fail at sign time.
        // We try RSA first, then EC, then Ed25519 by attempting to parse the key info.
        // Since from_*_der doesn't validate, we use the OID from the PKCS#8 structure.
        let private_key_info = pkcs8::PrivateKeyInfoRef::try_from(der_bytes)
            .map_err(|e| Error::IO(format!("failed to parse PKCS#8 DER: {e}")))?;

        let algorithm_oid = private_key_info.algorithm.oid;

        // RSA: 1.2.840.113549.1.1.1
        const RSA_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
        // EC: 1.2.840.10045.2.1
        const EC_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
        // Ed25519: 1.3.101.112
        const ED25519_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.3.101.112");

        if algorithm_oid == RSA_OID {
            // Ring's from_der expects PKCS#1 RSAPrivateKey DER, not full PKCS#8.
            // Extract the inner private key bytes from PKCS#8 PrivateKeyInfo.
            let rsa_der = private_key_info.private_key.as_bytes();
            Ok((EncodingKey::from_rsa_der(rsa_der), Algorithm::RS256))
        } else if algorithm_oid == EC_OID {
            let (ec_der, algorithm) = Self::rebuild_ec_pkcs8_named_curve(private_key_info)?;
            Ok((EncodingKey::from_ec_der(&ec_der), algorithm))
        } else if algorithm_oid == ED25519_OID {
            Ok((EncodingKey::from_ed_der(der_bytes), Algorithm::EdDSA))
        } else {
            Err(Error::IO(format!(
                "unsupported key algorithm OID: {algorithm_oid}"
            )))
        }
    }

    /// Rebuild a named-curve PKCS#8 DER for supported EC keys.
    ///
    /// jsonwebtoken/ring supports ES256 and ES384. Reject explicit parameters or
    /// unsupported curves instead of silently relabeling them with the wrong JWT alg.
    fn rebuild_ec_pkcs8_named_curve(pki: pkcs8::PrivateKeyInfoRef) -> Result<(Vec<u8>, Algorithm)> {
        use pkcs8::der::Encode;

        let (curve_oid, algorithm) = Self::ec_curve_oid_to_algorithm(
            pki.algorithm
                .parameters
                .and_then(|params| params.decode_as::<pkcs8::ObjectIdentifier>().ok()),
        )?;

        let alg_id = pkcs8::AlgorithmIdentifierRef {
            oid: pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"),
            parameters: Some(pkcs8::der::asn1::AnyRef::from(&curve_oid)),
        };

        let new_pki = pkcs8::PrivateKeyInfo {
            algorithm: alg_id,
            private_key: pki.private_key,
            public_key: pki.public_key,
        };

        let der = new_pki
            .to_der()
            .map_err(|e| Error::IO(format!("failed to re-encode EC PKCS#8: {e}")))?;
        Ok((der, algorithm))
    }

    fn ec_curve_oid_to_algorithm(
        curve_oid: Option<pkcs8::ObjectIdentifier>,
    ) -> Result<(pkcs8::ObjectIdentifier, Algorithm)> {
        const P256_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
        const P384_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.3.132.0.34");

        match curve_oid {
            Some(P256_OID) => Ok((P256_OID, Algorithm::ES256)),
            Some(P384_OID) => Ok((P384_OID, Algorithm::ES384)),
            Some(curve_oid) => Err(Error::IO(format!(
                "unsupported EC private key curve OID: {curve_oid}; supported curves are P-256 and P-384"
            ))),
            None => Err(Error::IO(
                "unsupported EC private key parameters: expected named P-256 or P-384 curve"
                    .to_string(),
            )),
        }
    }

    fn parse_sec1_ec_pem(pem_data: &[u8]) -> Result<(Vec<u8>, Algorithm)> {
        use sec1::der::Decode;

        let pem = Self::parse_pem_block(pem_data, "EC PRIVATE KEY")?;
        let ec_key = sec1::EcPrivateKey::from_der(pem.contents())
            .map_err(|e| Error::IO(format!("failed to parse EC private key: {e}")))?;

        let curve_oid = ec_key
            .parameters
            .and_then(|params| params.named_curve())
            .ok_or_else(|| {
                Error::IO(
                    "unsupported EC private key parameters: expected named P-256 or P-384 curve"
                        .to_string(),
                )
            })?;

        let algorithm = match curve_oid.to_string().as_str() {
            "1.2.840.10045.3.1.7" => Ok(Algorithm::ES256),
            "1.3.132.0.34" => Ok(Algorithm::ES384),
            _ => Err(Error::IO(format!(
                "unsupported EC private key curve OID: {curve_oid}; supported curves are P-256 and P-384"
            ))),
        }?;

        Ok((pem.contents().to_vec(), algorithm))
    }

    fn parse_pem_block(pem_data: &[u8], tag: &str) -> Result<pem::Pem> {
        pem::parse_many(pem_data)
            .map_err(|e| Error::IO(format!("failed to parse PEM: {e}")))?
            .into_iter()
            .find(|pem| pem.tag() == tag)
            .ok_or_else(|| Error::IO(format!("failed to find {tag} PEM block")))
    }

    fn parse_unencrypted_key(pem_data: &[u8], pem_str: &str) -> Result<(EncodingKey, Algorithm)> {
        if pem_str.contains("RSA PRIVATE KEY") {
            // PKCS#1 RSA key. Select the key block when PEM bundles include
            // another block before the private key.
            let pem = Self::parse_pem_block(pem_data, "RSA PRIVATE KEY")?;
            let key_pem = pem::encode(&pem);
            let key = EncodingKey::from_rsa_pem(key_pem.as_bytes())
                .map_err(|e| Error::IO(format!("failed to parse RSA private key: {e}")))?;
            return Ok((key, Algorithm::RS256));
        }

        if pem_str.contains("EC PRIVATE KEY") {
            use pkcs8::der::Encode;

            // SEC1 EC key. Choose the JWT alg from the curve instead of
            // advertising the wrong alg for non-P-256 keys.
            let (ec_private_key_der, algorithm) = Self::parse_sec1_ec_pem(pem_data)?;
            let pkcs8_der = pkcs8::PrivateKeyInfo {
                algorithm: pkcs8::AlgorithmIdentifierRef {
                    oid: pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"),
                    parameters: Some(pkcs8::der::asn1::AnyRef::from(&match algorithm {
                        Algorithm::ES256 => {
                            pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")
                        }
                        Algorithm::ES384 => pkcs8::ObjectIdentifier::new_unwrap("1.3.132.0.34"),
                        _ => unreachable!(),
                    })),
                },
                private_key: pkcs8::der::asn1::OctetStringRef::new(&ec_private_key_der)
                    .map_err(|e| Error::IO(format!("failed to wrap EC private key: {e}")))?,
                public_key: None::<pkcs8::der::asn1::BitStringRef<'_>>,
            }
            .to_der()
            .map_err(|e| Error::IO(format!("failed to re-encode EC PKCS#8: {e}")))?;
            return Ok((EncodingKey::from_ec_der(&pkcs8_der), algorithm));
        }

        // PKCS#8 "BEGIN PRIVATE KEY" — parse OID to determine key type,
        // then use from_*_der with full PKCS#8 DER (from_ec_pem has issues with PKCS#8 EC keys)
        let pem_parsed = Self::parse_pem_block(pem_data, "PRIVATE KEY")?;
        let der_bytes = pem_parsed.contents();

        let private_key_info = pkcs8::PrivateKeyInfoRef::try_from(der_bytes)
            .map_err(|e| Error::IO(format!("failed to parse PKCS#8 DER: {e}")))?;

        let algorithm_oid = private_key_info.algorithm.oid;

        const RSA_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
        const EC_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
        const ED25519_OID: pkcs8::ObjectIdentifier =
            pkcs8::ObjectIdentifier::new_unwrap("1.3.101.112");

        if algorithm_oid == RSA_OID {
            // Ring's from_der expects PKCS#1 RSAPrivateKey DER, not full PKCS#8.
            // Extract the inner private key bytes from PKCS#8 PrivateKeyInfo.
            let rsa_der = private_key_info.private_key.as_bytes();
            Ok((EncodingKey::from_rsa_der(rsa_der), Algorithm::RS256))
        } else if algorithm_oid == EC_OID {
            let (ec_der, algorithm) = Self::rebuild_ec_pkcs8_named_curve(private_key_info)?;
            Ok((EncodingKey::from_ec_der(&ec_der), algorithm))
        } else if algorithm_oid == ED25519_OID {
            Ok((EncodingKey::from_ed_der(der_bytes), Algorithm::EdDSA))
        } else {
            Err(Error::IO(format!(
                "unsupported key algorithm OID: {algorithm_oid}"
            )))
        }
    }

    fn generate_jwt(&self) -> Result<String> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| Error::IO(format!("system time error: {e}")))?
            .as_secs();

        let claims = KeyPairClaims {
            sub: self.username.clone(),
            iat: now,
            exp: now + KEYPAIR_TOKEN_TTL_SECS,
        };

        let header = Header::new(self.algorithm);
        encode(&header, &claims, &self.encoding_key)
            .map_err(|e| Error::IO(format!("failed to sign JWT: {e}")))
    }
}

impl Auth for KeyPairAuth {
    fn wrap(&self, builder: RequestBuilder) -> Result<RequestBuilder> {
        let token = self.generate_jwt()?;
        Ok(builder
            .bearer_auth(token)
            .header(HEADER_AUTH_METHOD, "keypair"))
    }

    fn can_reload(&self) -> bool {
        true
    }

    fn username(&self) -> String {
        self.username.clone()
    }
}

#[derive(::serde::Deserialize, ::serde::Serialize)]
#[serde(from = "String", into = "String")]
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SensitiveString(String);

impl From<String> for SensitiveString {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for SensitiveString {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl From<SensitiveString> for String {
    fn from(value: SensitiveString) -> Self {
        value.0
    }
}

impl std::fmt::Display for SensitiveString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "**REDACTED**")
    }
}

impl std::fmt::Debug for SensitiveString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // we keep the double quotes here to keep the String behavior
        write!(f, "\"**REDACTED**\"")
    }
}

impl SensitiveString {
    #[must_use]
    pub fn inner(&self) -> &str {
        self.0.as_str()
    }
}

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

    #[test]
    fn serialization() {
        let json_value = "\"foo\"";
        let value: SensitiveString = serde_json::from_str(json_value).unwrap();
        let result: String = serde_json::to_string(&value).unwrap();
        assert_eq!(result, json_value);
    }

    #[test]
    fn hide_content() {
        let value = SensitiveString("hello world".to_string());
        let display = format!("{value}");
        assert_eq!(display, "**REDACTED**");
        let debug = format!("{value:?}");
        assert_eq!(debug, "\"**REDACTED**\"");
    }

    #[test]
    fn keypair_auth_rsa() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        // Generate a test RSA private key in PKCS#8 format using openssl command
        // Note: `openssl genrsa` outputs PKCS#1 which may have compatibility issues
        // with some versions of ring. Using genpkey ensures PKCS#8 format.
        let output = std::process::Command::new("openssl")
            .args([
                "genpkey",
                "-algorithm",
                "RSA",
                "-pkeyopt",
                "rsa_keygen_bits:2048",
            ])
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            _ => {
                // Skip test if openssl is not available
                return;
            }
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&output.stdout).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.username(), "testuser");
        assert!(auth.can_reload());
        assert_eq!(auth.algorithm, Algorithm::RS256);

        // Verify JWT can be generated
        let token = auth.generate_jwt().unwrap();
        assert!(!token.is_empty());

        // Verify JWT structure (header.payload.signature)
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_rsa_pkcs1_bundle_selects_private_key_block() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let output = std::process::Command::new("openssl")
            .args(["genrsa", "2048"])
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            _ => return,
        };

        let pem_str = String::from_utf8_lossy(&output.stdout);
        if !pem_str.contains("RSA PRIVATE KEY") {
            return;
        }

        let key = prepend_dummy_public_key_pem(&output.stdout);
        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::RS256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_rsa_pkcs1() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        // Generate a PKCS#1 RSA key (BEGIN RSA PRIVATE KEY)
        let output = std::process::Command::new("openssl")
            .args(["genrsa", "2048"])
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            _ => return,
        };

        let pem_str = String::from_utf8_lossy(&output.stdout);
        if !pem_str.contains("RSA PRIVATE KEY") {
            // Skip if openssl outputs PKCS#8 format instead
            return;
        }

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&output.stdout).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::RS256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    fn prepend_dummy_public_key_pem(key: &[u8]) -> Vec<u8> {
        let mut bundle = pem::encode(&pem::Pem::new("PUBLIC KEY", vec![1, 2, 3])).into_bytes();
        bundle.extend_from_slice(key);
        bundle
    }

    fn gen_sec1_ec_private_key(curve: &str) -> Option<Vec<u8>> {
        gen_sec1_ec_private_key_with_params(curve, false)
    }

    fn gen_sec1_ec_private_key_with_params(curve: &str, include_params: bool) -> Option<Vec<u8>> {
        let mut args = vec!["ecparam", "-name", curve, "-genkey"];
        if !include_params {
            args.push("-noout");
        }
        let output = std::process::Command::new("openssl")
            .args(args)
            .output()
            .ok()?;
        output.status.success().then_some(output.stdout)
    }

    fn gen_ec_private_key(curve: &str, encrypted: bool) -> Option<Vec<u8>> {
        let mut args = vec![
            "genpkey",
            "-algorithm",
            "EC",
            "-pkeyopt",
            curve,
            "-pkeyopt",
            "ec_param_enc:named_curve",
        ];
        if encrypted {
            args.extend([
                "-aes-256-cbc",
                "-pass",
                "pass:testpass",
                "-v2prf",
                "hmacWithSHA256",
            ]);
        }

        let output = std::process::Command::new("openssl")
            .args(args)
            .output()
            .ok()?;
        output.status.success().then_some(output.stdout)
    }

    #[test]
    fn keypair_auth_pkcs8_bundle_selects_private_key_block() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_ec_private_key("ec_paramgen_curve:P-256", false) else {
            return;
        };
        let key = prepend_dummy_public_key_pem(&key);

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::ES256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_ec() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_ec_private_key("ec_paramgen_curve:P-256", false) else {
            return;
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::ES256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_ec_p384() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_ec_private_key("ec_paramgen_curve:P-384", false) else {
            return;
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::ES384);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_sec1_ec_with_parameters_block() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_sec1_ec_private_key_with_params("prime256v1", true) else {
            return;
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::ES256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_sec1_ec_p384() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_sec1_ec_private_key("secp384r1") else {
            return;
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::ES384);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_encrypted_ec_p384() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_ec_private_key("ec_paramgen_curve:P-384", true) else {
            return;
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let mut pass_file = NamedTempFile::new().unwrap();
        pass_file.write_all(b"testpass\n").unwrap();

        let auth = KeyPairAuth::new(
            "testuser",
            key_file.path().to_str().unwrap(),
            Some(pass_file.path().to_str().unwrap()),
        )
        .unwrap();
        assert_eq!(auth.algorithm, Algorithm::ES384);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_rejects_unsupported_ec_curves() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let Some(key) = gen_ec_private_key("ec_paramgen_curve:P-521", false) else {
            return;
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let err = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None)
            .err()
            .expect("unsupported EC curve should be rejected");
        assert!(
            err.to_string()
                .contains("unsupported EC private key curve OID"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn keypair_auth_ed25519() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        // Generate a test Ed25519 private key
        let output = std::process::Command::new("openssl")
            .args(["genpkey", "-algorithm", "ed25519"])
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            _ => return,
        };

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&output.stdout).unwrap();

        let auth = KeyPairAuth::new("testuser", key_file.path().to_str().unwrap(), None).unwrap();
        assert_eq!(auth.algorithm, Algorithm::EdDSA);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_encrypted_pkcs8_bundle_selects_private_key_block() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let output = std::process::Command::new("openssl")
            .args([
                "genpkey",
                "-algorithm",
                "RSA",
                "-pkeyopt",
                "rsa_keygen_bits:2048",
                "-aes-256-cbc",
                "-pass",
                "pass: testpass ",
                "-v2prf",
                "hmacWithSHA256",
            ])
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            _ => return,
        };

        let key = prepend_dummy_public_key_pem(&output.stdout);
        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&key).unwrap();

        let mut pass_file = NamedTempFile::new().unwrap();
        pass_file.write_all(b" testpass \n").unwrap();

        let auth = KeyPairAuth::new(
            "testuser",
            key_file.path().to_str().unwrap(),
            Some(pass_file.path().to_str().unwrap()),
        )
        .unwrap();
        assert_eq!(auth.algorithm, Algorithm::RS256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }

    #[test]
    fn keypair_auth_encrypted_key() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        // Generate an encrypted RSA private key with scrypt KDF (supported by pkcs8 crate)
        let output = std::process::Command::new("openssl")
            .args([
                "genpkey",
                "-algorithm",
                "RSA",
                "-pkeyopt",
                "rsa_keygen_bits:2048",
                "-aes-256-cbc",
                "-pass",
                "pass:testpass",
                "-v2prf",
                "hmacWithSHA256",
            ])
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            _ => return,
        };

        // Check if the generated key is actually encrypted
        let pem_str = String::from_utf8_lossy(&output.stdout);
        if !pem_str.contains("ENCRYPTED") {
            return;
        }

        let mut key_file = NamedTempFile::new().unwrap();
        key_file.write_all(&output.stdout).unwrap();

        let mut pass_file = NamedTempFile::new().unwrap();
        pass_file.write_all(b"testpass\n").unwrap();

        let auth = KeyPairAuth::new(
            "testuser",
            key_file.path().to_str().unwrap(),
            Some(pass_file.path().to_str().unwrap()),
        )
        .unwrap();
        assert_eq!(auth.algorithm, Algorithm::RS256);

        let token = auth.generate_jwt().unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
    }
}