takproto 0.4.2

Rust library for TAK (Team Awareness Kit) Protocol - send CoT messages to TAK servers with mTLS support
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
use crate::error::{Result, TakError};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::{ClientConfig, RootCertStore, SignatureScheme, DigitallySignedStruct};
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use std::sync::Arc;

/// TLS configuration for TAK client connections
#[derive(Clone)]
pub struct TlsConfig {
    pub(crate) config: Arc<ClientConfig>,
}

/// Builder for TLS configuration with validation options
///
/// Provides fine-grained control over certificate and hostname verification.
/// Useful for development, testing, or self-signed certificates.
///
/// # Warning
///
/// Disabling certificate or hostname verification reduces security.
/// Only use in trusted environments or during development.
///
/// # Example
///
/// ```no_run
/// # use takproto::TlsConfigBuilder;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // For production: full validation (default)
/// let tls_config = TlsConfigBuilder::new()
///     .with_p12("user.p12", "password")?
///     .build()?;
///
/// // For development: disable hostname verification
/// let tls_config = TlsConfigBuilder::new()
///     .with_p12("user.p12", "password")?
///     .danger_disable_hostname_verification(true)
///     .build()?;
///
/// // For testing: accept self-signed certs
/// let tls_config = TlsConfigBuilder::new()
///     .with_p12("user.p12", "password")?
///     .danger_accept_invalid_certs(true)
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct TlsConfigBuilder {
    client_certs: Option<Vec<CertificateDer<'static>>>,
    client_key: Option<PrivateKeyDer<'static>>,
    root_store: Option<RootCertStore>,
    disable_hostname_verification: bool,
    accept_invalid_certs: bool,
}

/// Custom certificate verifier that optionally skips validation
#[derive(Debug)]
struct DangerousVerifier {
    accept_invalid_certs: bool,
    root_store: Option<Arc<RootCertStore>>,
}

impl ServerCertVerifier for DangerousVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: rustls::pki_types::UnixTime,
    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
        if self.accept_invalid_certs {
            // Skip all validation - dangerous!
            Ok(ServerCertVerified::assertion())
        } else if let Some(ref root_store) = self.root_store {
            // Validate cert but not hostname (dangerous!)
            let verifier = rustls::client::WebPkiServerVerifier::builder(root_store.clone())
                .build()
                .map_err(|e| rustls::Error::General(format!("Failed to build verifier: {}", e)))?;
            // Verify with a dummy hostname that we ignore
            verifier.verify_server_cert(end_entity, intermediates, _server_name, ocsp_response, now)
        } else {
            Err(rustls::Error::General("Certificate verification not configured".to_string()))
        }
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
        if self.accept_invalid_certs {
            Ok(HandshakeSignatureValid::assertion())
        } else {
            Err(rustls::Error::General("Signature verification not configured".to_string()))
        }
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
        if self.accept_invalid_certs {
            Ok(HandshakeSignatureValid::assertion())
        } else {
            Err(rustls::Error::General("Signature verification not configured".to_string()))
        }
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        vec![
            SignatureScheme::RSA_PKCS1_SHA256,
            SignatureScheme::RSA_PKCS1_SHA384,
            SignatureScheme::RSA_PKCS1_SHA512,
            SignatureScheme::ECDSA_NISTP256_SHA256,
            SignatureScheme::ECDSA_NISTP384_SHA384,
            SignatureScheme::ECDSA_NISTP521_SHA512,
            SignatureScheme::RSA_PSS_SHA256,
            SignatureScheme::RSA_PSS_SHA384,
            SignatureScheme::RSA_PSS_SHA512,
            SignatureScheme::ED25519,
        ]
    }
}

impl TlsConfigBuilder {
    /// Create a new TLS configuration builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Load credentials from a PKCS#12 file
    ///
    /// # Arguments
    ///
    /// * `p12_path` - Path to the PKCS#12 file
    /// * `password` - Password to decrypt the P12 file
    #[cfg(feature = "openssl-p12")]
    pub fn with_p12(mut self, p12_path: impl AsRef<Path>, password: &str) -> Result<Self> {
        let (client_certs, client_key, root_store) = load_p12_openssl(p12_path, password)?;
        self.client_certs = Some(client_certs);
        self.client_key = Some(client_key);
        self.root_store = Some(root_store);
        Ok(self)
    }

    /// Load credentials from a PKCS#12 file (pure Rust implementation)
    #[cfg(not(feature = "openssl-p12"))]
    pub fn with_p12(mut self, p12_path: impl AsRef<Path>, password: &str) -> Result<Self> {
        let (client_certs, client_key, root_store) = load_p12_rust(p12_path, password)?;
        self.client_certs = Some(client_certs);
        self.client_key = Some(client_key);
        self.root_store = Some(root_store);
        Ok(self)
    }

    /// Load credentials from separate PEM files
    ///
    /// # Arguments
    ///
    /// * `ca_cert_path` - Path to CA certificate (PEM)
    /// * `client_cert_path` - Path to client certificate (PEM)
    /// * `client_key_path` - Path to client private key (PEM)
    pub fn with_client_cert(
        mut self,
        ca_cert_path: impl AsRef<Path>,
        client_cert_path: impl AsRef<Path>,
        client_key_path: impl AsRef<Path>,
    ) -> Result<Self> {
        let ca_certs = load_certs(ca_cert_path.as_ref())?;
        let mut root_store = RootCertStore::empty();
        for cert in ca_certs {
            root_store
                .add(cert)
                .map_err(|e| TakError::Certificate(format!("Failed to add CA cert: {}", e)))?;
        }

        let client_certs = load_certs(client_cert_path.as_ref())?;
        let client_key = load_private_key(client_key_path.as_ref())?;

        self.client_certs = Some(client_certs);
        self.client_key = Some(client_key);
        self.root_store = Some(root_store);
        Ok(self)
    }

    /// Use system root certificates (no client authentication)
    pub fn with_system_roots(mut self) -> Result<Self> {
        let mut root_store = RootCertStore::empty();
        let certs = rustls_native_certs::load_native_certs();
        for cert in certs.certs {
            root_store.add(cert).ok();
        }
        if !certs.errors.is_empty() && root_store.is_empty() {
            return Err(TakError::Certificate(
                "Failed to load any system certificates".to_string(),
            ));
        }
        self.root_store = Some(root_store);
        Ok(self)
    }

    /// Add an additional trusted certificate to the root store
    ///
    /// This is useful for trusting self-signed server certificates while
    /// maintaining proper certificate validation.
    ///
    /// # Arguments
    ///
    /// * `cert_path` - Path to the certificate file (PEM format)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use takproto::TlsConfigBuilder;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tls_config = TlsConfigBuilder::new()
    ///     .with_p12("client.p12", "password")?
    ///     .with_additional_root_cert("server_cert.pem")?  // Trust the server's self-signed cert
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_additional_root_cert(mut self, cert_path: impl AsRef<Path>) -> Result<Self> {
        let certs = load_certs(cert_path.as_ref())?;

        // Get or create root store
        let mut root_store = self.root_store.take().unwrap_or_else(RootCertStore::empty);

        // Add the additional certificates
        for cert in certs {
            root_store
                .add(cert)
                .map_err(|e| TakError::Certificate(format!("Failed to add certificate: {}", e)))?;
        }

        self.root_store = Some(root_store);
        Ok(self)
    }

    /// Load a custom CA certificate (no client authentication)
    pub fn with_ca_cert(mut self, ca_cert_path: impl AsRef<Path>) -> Result<Self> {
        let ca_certs = load_certs(ca_cert_path.as_ref())?;
        let mut root_store = RootCertStore::empty();
        for cert in ca_certs {
            root_store
                .add(cert)
                .map_err(|e| TakError::Certificate(format!("Failed to add CA cert: {}", e)))?;
        }
        self.root_store = Some(root_store);
        Ok(self)
    }

    /// **DANGER**: Disable hostname verification
    ///
    /// When enabled, the client will not verify that the server's certificate
    /// matches the hostname you're connecting to.
    ///
    /// # Warning
    ///
    /// This makes you vulnerable to man-in-the-middle attacks.
    /// Only use in trusted networks or during development.
    pub fn danger_disable_hostname_verification(mut self, disable: bool) -> Self {
        self.disable_hostname_verification = disable;
        self
    }

    /// **DANGER**: Accept invalid/self-signed certificates
    ///
    /// When enabled, the client will accept any server certificate without
    /// validation, including self-signed, expired, or invalid certificates.
    ///
    /// # Warning
    ///
    /// This completely disables certificate validation and makes you vulnerable
    /// to man-in-the-middle attacks. Only use in trusted networks or during development.
    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }

    /// Build the TLS configuration
    pub fn build(self) -> Result<TlsConfig> {
        // If both dangerous options are disabled, use normal path
        if !self.accept_invalid_certs && !self.disable_hostname_verification {
            // Normal validation path (full validation)
            let root_store = self.root_store
                .ok_or_else(|| TakError::Certificate("No root certificates configured".to_string()))?;

            let config = if let (Some(certs), Some(key)) = (self.client_certs, self.client_key) {
                ClientConfig::builder()
                    .with_root_certificates(root_store)
                    .with_client_auth_cert(certs, key)
                    .map_err(|e| TakError::Certificate(format!("Failed to configure client auth: {}", e)))?
            } else {
                ClientConfig::builder()
                    .with_root_certificates(root_store)
                    .with_no_client_auth()
            };

            return Ok(TlsConfig {
                config: Arc::new(config),
            });
        }

        // Use custom verifier for dangerous options
        let root_store = if self.accept_invalid_certs {
            // No root store needed - accepting all certs
            None
        } else {
            // Need root store for cert validation (but not hostname)
            Some(Arc::new(self.root_store
                .ok_or_else(|| TakError::Certificate("No root certificates configured".to_string()))?))
        };

        let verifier = Arc::new(DangerousVerifier {
            accept_invalid_certs: self.accept_invalid_certs,
            root_store,
        });

        let config_builder = ClientConfig::builder()
            .dangerous()
            .with_custom_certificate_verifier(verifier);

        // Add client authentication if credentials are available
        let config = if let (Some(certs), Some(key)) = (self.client_certs, self.client_key) {
            config_builder.with_client_auth_cert(certs, key)
                .map_err(|e| TakError::Certificate(format!("Failed to configure client auth: {}", e)))?
        } else {
            config_builder.with_no_client_auth()
        };

        Ok(TlsConfig {
            config: Arc::new(config),
        })
    }
}

impl TlsConfig {
    /// Create a new TLS configuration from a PKCS#12 file (TAK server format)
    ///
    /// TAK servers typically generate `.p12` files containing the client certificate,
    /// private key, and CA certificate bundle.
    ///
    /// # Feature Flags
    ///
    /// - **Default**: Uses pure Rust `p12` crate (may not support legacy formats)
    /// - **`openssl-p12`**: Uses OpenSSL for full legacy P12 support
    ///
    /// Enable full support with:
    /// ```toml
    /// [dependencies]
    /// takproto = { version = "0.2", features = ["openssl-p12"] }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `p12_path` - Path to the PKCS#12 file (usually .p12 extension)
    /// * `password` - Password to decrypt the PKCS#12 file
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use takproto::TlsConfig;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tls_config = TlsConfig::new_with_p12("user.p12", "atakatak")?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "openssl-p12")]
    pub fn new_with_p12(p12_path: impl AsRef<Path>, password: &str) -> Result<Self> {
        Self::new_with_p12_openssl(p12_path, password)
    }

    /// Create a new TLS configuration from a PKCS#12 file (pure Rust implementation)
    ///
    /// **Note**: This implementation may not support legacy PKCS#12 files from TAK servers.
    /// For full support, enable the `openssl-p12` feature flag.
    #[cfg(not(feature = "openssl-p12"))]
    pub fn new_with_p12(p12_path: impl AsRef<Path>, password: &str) -> Result<Self> {
        Self::new_with_p12_rust(p12_path, password)
    }

    /// OpenSSL-based P12 implementation (full legacy support)
    #[cfg(feature = "openssl-p12")]
    fn new_with_p12_openssl(p12_path: impl AsRef<Path>, password: &str) -> Result<Self> {
        let (client_certs, client_key, root_store) = load_p12_openssl(p12_path, password)?;

        // Build TLS config
        let config = ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_client_auth_cert(client_certs, client_key)
            .map_err(|e| TakError::Certificate(format!("Failed to configure client auth: {}", e)))?;

        Ok(Self {
            config: Arc::new(config),
        })
    }

    /// Pure Rust P12 implementation (limited legacy support)
    #[cfg(not(feature = "openssl-p12"))]
    fn new_with_p12_rust(p12_path: impl AsRef<Path>, password: &str) -> Result<Self> {
        let (client_certs, client_key, root_store) = load_p12_rust(p12_path, password)?;

        // Build TLS config
        let config = ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_client_auth_cert(client_certs, client_key)
            .map_err(|e| TakError::Certificate(format!("Failed to configure client auth: {}", e)))?;

        Ok(Self {
            config: Arc::new(config),
        })
    }

    /// Create a new TLS configuration with client certificate authentication (mTLS)
    ///
    /// # Arguments
    ///
    /// * `ca_cert_path` - Path to the CA certificate file (PEM format)
    /// * `client_cert_path` - Path to the client certificate file (PEM format)
    /// * `client_key_path` - Path to the client private key file (PEM format)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use takproto::TlsConfig;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tls_config = TlsConfig::new_with_client_cert(
    ///     "ca.pem",
    ///     "client.pem",
    ///     "client-key.pem"
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_with_client_cert(
        ca_cert_path: impl AsRef<Path>,
        client_cert_path: impl AsRef<Path>,
        client_key_path: impl AsRef<Path>,
    ) -> Result<Self> {
        // Load CA certificates
        let ca_certs = load_certs(ca_cert_path.as_ref())?;
        let mut root_store = RootCertStore::empty();
        for cert in ca_certs {
            root_store
                .add(cert)
                .map_err(|e| TakError::Certificate(format!("Failed to add CA cert: {}", e)))?;
        }

        // Load client certificate and key
        let client_certs = load_certs(client_cert_path.as_ref())?;
        let client_key = load_private_key(client_key_path.as_ref())?;

        // Build TLS config
        let config = ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_client_auth_cert(client_certs, client_key)
            .map_err(|e| TakError::Certificate(format!("Failed to configure client auth: {}", e)))?;

        Ok(Self {
            config: Arc::new(config),
        })
    }

    /// Create a TLS configuration that trusts the system root certificates
    /// without client authentication
    ///
    /// Note: Most TAK servers require client certificate authentication,
    /// so you'll typically want to use `new_with_client_cert` instead.
    pub fn new_with_system_roots() -> Result<Self> {
        let mut root_store = RootCertStore::empty();

        // Add system root certificates
        let certs = rustls_native_certs::load_native_certs();
        for cert in certs.certs {
            root_store.add(cert).ok(); // Ignore individual cert errors
        }
        // Check if there were any errors loading certs, but don't fail if some succeeded
        if !certs.errors.is_empty() && root_store.is_empty() {
            return Err(TakError::Certificate(
                "Failed to load any system certificates".to_string(),
            ));
        }

        let config = ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();

        Ok(Self {
            config: Arc::new(config),
        })
    }

    /// Create a TLS configuration with a custom CA certificate
    /// without client authentication
    pub fn new_with_ca_cert(ca_cert_path: impl AsRef<Path>) -> Result<Self> {
        let ca_certs = load_certs(ca_cert_path.as_ref())?;
        let mut root_store = RootCertStore::empty();

        for cert in ca_certs {
            root_store
                .add(cert)
                .map_err(|e| TakError::Certificate(format!("Failed to add CA cert: {}", e)))?;
        }

        let config = ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();

        Ok(Self {
            config: Arc::new(config),
        })
    }
}

/// Load certificates from a PEM file
fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
    let file = File::open(path)
        .map_err(|e| TakError::Certificate(format!("Failed to open cert file: {}", e)))?;
    let mut reader = BufReader::new(file);

    let certs = rustls_pemfile::certs(&mut reader)
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|e| TakError::Certificate(format!("Failed to parse certificates: {}", e)))?;

    if certs.is_empty() {
        return Err(TakError::Certificate(
            "No certificates found in file".to_string(),
        ));
    }

    Ok(certs)
}

/// Load a private key from a PEM file
fn load_private_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
    let file = File::open(path)
        .map_err(|e| TakError::Certificate(format!("Failed to open key file: {}", e)))?;
    let mut reader = BufReader::new(file);

    // Try to read any private key format (PKCS#8, RSA, EC, etc.)
    let keys = rustls_pemfile::private_key(&mut reader)
        .map_err(|e| TakError::Certificate(format!("Failed to parse private key: {}", e)))?
        .ok_or_else(|| TakError::Certificate("No private key found in file".to_string()))?;

    Ok(keys)
}

/// Load P12 file using OpenSSL (full legacy support)
#[cfg(feature = "openssl-p12")]
fn load_p12_openssl(
    p12_path: impl AsRef<Path>,
    password: &str,
) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>, RootCertStore)> {
    use openssl::pkcs12::Pkcs12;

    // Read the PKCS#12 file
    let mut file = File::open(p12_path.as_ref())
        .map_err(|e| TakError::Certificate(format!("Failed to open P12 file: {}", e)))?;
    let mut p12_data = Vec::new();
    file.read_to_end(&mut p12_data)
        .map_err(|e| TakError::Certificate(format!("Failed to read P12 file: {}", e)))?;

    // Parse with OpenSSL (supports legacy formats)
    let pkcs12 = Pkcs12::from_der(&p12_data)
        .map_err(|e| TakError::Certificate(format!("Failed to parse P12 file: {}", e)))?;

    let parsed = pkcs12
        .parse2(password)
        .map_err(|e| TakError::Certificate(format!("Failed to decrypt P12 file: {}", e)))?;

    // Extract client certificate
    let client_cert = parsed.cert
        .ok_or_else(|| TakError::Certificate("No client certificate found in P12 file".to_string()))?;
    let client_cert_der = client_cert.to_der()
        .map_err(|e| TakError::Certificate(format!("Failed to encode client certificate: {}", e)))?;
    let client_certs = vec![CertificateDer::from(client_cert_der)];

    // Extract private key
    let pkey = parsed.pkey
        .ok_or_else(|| TakError::Certificate("No private key found in P12 file".to_string()))?;

    // Convert to PKCS#8 DER format (required by rustls)
    let key_der = pkey.private_key_to_pkcs8()
        .map_err(|e| TakError::Certificate(format!("Failed to encode private key as PKCS#8: {}", e)))?;
    let client_key = PrivateKeyDer::Pkcs8(key_der.into());

    // Build root certificate store
    let mut root_store = RootCertStore::empty();

    // Add CA chain from P12
    if let Some(ca_stack) = parsed.ca {
        for ca_cert in ca_stack {
            let ca_der = ca_cert.to_der()
                .map_err(|e| TakError::Certificate(format!("Failed to encode CA certificate: {}", e)))?;
            root_store.add(CertificateDer::from(ca_der)).ok();
        }
    }

    // If no CA certs in P12, fall back to system roots
    if root_store.is_empty() {
        let sys_certs = rustls_native_certs::load_native_certs();
        for cert in sys_certs.certs {
            root_store.add(cert).ok();
        }
    }

    Ok((client_certs, client_key, root_store))
}

/// Load P12 file using pure Rust parser (limited legacy support)
#[cfg(not(feature = "openssl-p12"))]
fn load_p12_rust(
    p12_path: impl AsRef<Path>,
    password: &str,
) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>, RootCertStore)> {
    // Read the PKCS#12 file
    let mut file = File::open(p12_path.as_ref())
        .map_err(|e| TakError::Certificate(format!("Failed to open P12 file: {}", e)))?;
    let mut p12_data = Vec::new();
    file.read_to_end(&mut p12_data)
        .map_err(|e| TakError::Certificate(format!("Failed to read P12 file: {}", e)))?;

    // Parse the PKCS#12 file
    let p12 = p12::PFX::parse(&p12_data)
        .map_err(|e| TakError::Certificate(format!("Failed to parse P12 file: {}", e)))?;

    // Extract key
    let key_bags = p12
        .key_bags(password)
        .map_err(|e| TakError::Certificate(format!(
            "Failed to decrypt P12 file: {}\n\
            \n\
            TAK servers often generate legacy PKCS#12 files not supported by pure Rust parsers.\n\
            \n\
            Option 1: Enable OpenSSL support for full P12 compatibility:\n\
              [dependencies]\n\
              takproto = {{ version = \"0.3\", features = [\"openssl-p12\"] }}\n\
            \n\
            Option 2: Extract to PEM files and use TlsConfig::new_with_client_cert():\n\
              openssl pkcs12 -legacy -in {} -nokeys -out client.pem -passin pass:{}\n\
              openssl pkcs12 -legacy -in {} -nocerts -nodes -out client-key.pem -passin pass:{}\n\
              openssl pkcs12 -legacy -in {} -cacerts -nokeys -out ca.pem -passin pass:{}",
            e,
            p12_path.as_ref().display(),
            password,
            p12_path.as_ref().display(),
            password,
            p12_path.as_ref().display(),
            password
        )))?;

    let client_key = key_bags
        .into_iter()
        .next()
        .ok_or_else(|| TakError::Certificate("No private key found in P12 file".to_string()))?;
    let client_key = PrivateKeyDer::Pkcs8(client_key.into());

    // Extract certificates
    let cert_bags = p12
        .cert_bags(password)
        .map_err(|e| TakError::Certificate(format!("Failed to extract certificates from P12 file: {}", e)))?;

    if cert_bags.is_empty() {
        return Err(TakError::Certificate("No certificates found in P12 file".to_string()));
    }

    // First cert is typically the client cert, rest are CA chain
    let mut cert_iter = cert_bags.into_iter();
    let client_cert = cert_iter.next()
        .ok_or_else(|| TakError::Certificate("No client certificate found in P12 file".to_string()))?;
    let client_certs = vec![CertificateDer::from(client_cert)];

    // Build root certificate store with remaining certs (CA chain)
    let mut root_store = RootCertStore::empty();
    for ca_cert in cert_iter {
        let cert = CertificateDer::from(ca_cert);
        root_store.add(cert).ok(); // Ignore individual cert errors
    }

    // If no CA certs in P12, fall back to system roots
    if root_store.is_empty() {
        let sys_certs = rustls_native_certs::load_native_certs();
        for cert in sys_certs.certs {
            root_store.add(cert).ok();
        }
    }

    Ok((client_certs, client_key, root_store))
}