passless-rs 0.11.2

FIDO2 security token emulator
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
//! TPM (Trusted Platform Module) storage adapter

pub mod init;

use crate::storage::credential::Credential;
use crate::storage::index::{
    CredentialCache, CredentialIndexes, CredentialPathInfo, get_credential_path,
    load_credential_paths, update_indexes_on_delete, update_indexes_on_write,
};
use crate::storage::{CredentialFilter, CredentialStorage};
use crate::util::{bytes_to_hex, create_secure_dir_all, create_secure_file};

use soft_fido2::Result;

use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Mutex;
use std::time::Instant;

use aes_gcm::aead::{Aead, KeyInit, OsRng};
use aes_gcm::{Aes256Gcm, Nonce};
use log::{debug, info};
use rand::RngCore;
use tss_esapi::constants::SessionType;
use tss_esapi::interface_types::algorithm::PublicAlgorithm;
use tss_esapi::interface_types::key_bits::RsaKeyBits;
use tss_esapi::interface_types::{algorithm::HashingAlgorithm, resource_handles::Hierarchy};
use tss_esapi::structures::{KeyedHashScheme, Public, PublicBuilder, PublicKeyedHashParameters};

use tss_esapi::structures::{
    PublicKeyRsa, PublicRsaParametersBuilder, RsaExponent, RsaScheme, SymmetricDefinitionObject,
};
use tss_esapi::tss2_esys::{TPM2B_PRIVATE, TPM2B_PUBLIC};
use tss_esapi::{Context, Tcti};
use zeroize::Zeroizing;

/// TPM storage adapter
///
/// Stores credentials as TPM-sealed files in a directory structure.
/// File structure: {storage_dir}/{rp_id}/{cred_id_hex}.tpm
/// Uses indexes for efficient lookups without unsealing all credentials.
pub struct TpmStorageAdapter {
    storage_dir: PathBuf,
    indexes: CredentialIndexes,
    cache: CredentialCache,
    iteration_index: usize,
    iteration_entries: Vec<PathBuf>,
    context: Mutex<Context>,
}

/// Represents a sealed credential blob stored on disk
#[derive(serde::Serialize, serde::Deserialize)]
struct SealedBlob {
    /// The encrypted credential data (AES-GCM encrypted)
    encrypted_data: Vec<u8>,
    /// The nonce used for AES-GCM encryption (96 bits)
    nonce: Vec<u8>,
    /// The private part of the TPM-sealed encryption key
    tpm_private: Vec<u8>,
    /// The public part of the TPM-sealed encryption key
    tpm_public: Vec<u8>,
}

impl TpmStorageAdapter {
    /// Create a new TPM storage adapter
    pub fn new(storage_dir: PathBuf, tcti: Option<String>) -> Result<Self> {
        info!("Using TPM 2.0 backend");
        info!("Storage path: {}", storage_dir.display());

        // Ensure the storage directory is initialized
        // This will prompt the user via notifications if not initialized
        self::init::ensure_initialized(&storage_dir).map_err(|_| soft_fido2::Error::Other)?;

        // Initialize TPM context
        let tcti_conf = if let Some(ref tcti_str) = tcti {
            info!("Using TCTI configuration: {}", tcti_str);
            Tcti::from_str(tcti_str).map_err(|e| {
                log::error!("Failed to parse TCTI configuration '{}': {}", tcti_str, e);
                log::error!("TCTI format examples:");
                log::error!("  - Hardware TPM: device:/dev/tpmrm0");
                log::error!("  - swtpm socket: swtpm:path=/path/to/socket");

                soft_fido2::Error::Other
            })?
        } else {
            // Default TCTI (device or simulator)
            info!("Using default TCTI: device:/dev/tpmrm0");
            Tcti::Device(Default::default())
        };

        let mut context = Context::new(tcti_conf).map_err(|e| {
            log::error!("Failed to create TPM context: {}", e);
            if let Some(ref tcti_str) = tcti {
                log::error!("TCTI used: {}", tcti_str);
            } else {
                log::error!("TCTI used: device:/dev/tpmrm0 (default)");
            }
            log::error!("Troubleshooting steps:");
            log::error!("  1. Verify TPM device exists: ls -l /dev/tpm*");
            log::error!("  2. Check permissions on TPM device");
            soft_fido2::Error::Other
        })?;

        // Start auth session for encryption
        let session = context
            .start_auth_session(
                None,
                None,
                None,
                SessionType::Hmac,
                SymmetricDefinitionObject::AES_128_CFB.into(),
                HashingAlgorithm::Sha256,
            )
            .map_err(|e| {
                log::error!("Failed to start TPM auth session: {}", e);
                soft_fido2::Error::Other
            })?
            .ok_or_else(|| {
                log::error!("TPM auth session returned None");
                soft_fido2::Error::Other
            })?;

        context.set_sessions((Some(session), None, None));

        info!("TPM context initialized successfully");

        // Load indexes by scanning directory structure (no unsealing!)
        let indexes = load_credential_paths(&storage_dir, "tpm").map_err(|e| {
            log::error!("Failed to load credential paths: {}", e);
            soft_fido2::Error::Other
        })?;

        let adapter = Self {
            storage_dir,
            indexes,
            cache: Default::default(),
            iteration_index: 0,
            iteration_entries: Vec::new(),
            context: Mutex::new(context),
        };

        Ok(adapter)
    }

    /// Create a primary storage key in the owner hierarchy
    ///
    /// This creates a transient primary key that can be used as a parent for sealing operations.
    /// The key is created with the same parameters each time, so it has the same handle.
    fn create_primary_key(&self, context: &mut Context) -> Result<tss_esapi::handles::KeyHandle> {
        // Create a primary storage key (RSA 2048, storage parent)
        let object_attributes = tss_esapi::attributes::ObjectAttributesBuilder::new()
            .with_fixed_tpm(true)
            .with_fixed_parent(true)
            .with_sensitive_data_origin(true)
            .with_user_with_auth(true)
            .with_decrypt(true)
            .with_restricted(true)
            .build()
            .map_err(|e| {
                log::error!("Failed to build object attributes: {}", e);
                soft_fido2::Error::Other
            })?;

        // For a storage key, we need to specify the symmetric algorithm used to encrypt child objects
        let rsa_params = PublicRsaParametersBuilder::new()
            .with_symmetric(SymmetricDefinitionObject::AES_128_CFB)
            .with_scheme(RsaScheme::Null)
            .with_key_bits(RsaKeyBits::Rsa2048)
            .with_exponent(RsaExponent::default())
            .with_is_signing_key(false)
            .with_is_decryption_key(true)
            .with_restricted(true)
            .build()
            .map_err(|e| {
                log::error!("Failed to build RSA parameters: {}", e);
                soft_fido2::Error::Other
            })?;

        let primary_pub = PublicBuilder::new()
            .with_public_algorithm(PublicAlgorithm::Rsa)
            .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
            .with_object_attributes(object_attributes)
            .with_rsa_parameters(rsa_params)
            .with_rsa_unique_identifier(PublicKeyRsa::default())
            .build()
            .map_err(|e| {
                log::error!("Failed to build primary key public: {}", e);
                soft_fido2::Error::Other
            })?;

        let primary_key_result = context
            .create_primary(Hierarchy::Owner, primary_pub, None, None, None, None)
            .map_err(|e| {
                log::error!("Failed to create primary key: {}", e);
                soft_fido2::Error::Other
            })?;

        Ok(primary_key_result.key_handle)
    }

    /// Create a keyed hash object public structure for sealing data
    fn create_sealing_public(&self) -> Result<Public> {
        // For a sealing object, we need minimal attributes
        let object_attributes = tss_esapi::attributes::ObjectAttributesBuilder::new()
            .with_fixed_tpm(true)
            .with_fixed_parent(true)
            .with_user_with_auth(true)
            .build()
            .map_err(|e| {
                log::error!("Failed to build sealing object attributes: {}", e);
                soft_fido2::Error::Other
            })?;

        // Create keyed hash parameters for sealing (Null scheme)
        let keyed_hash_params = PublicKeyedHashParameters::new(KeyedHashScheme::Null);

        // Build the sealing object with required unique identifier
        PublicBuilder::new()
            .with_public_algorithm(PublicAlgorithm::KeyedHash)
            .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
            .with_object_attributes(object_attributes)
            .with_keyed_hash_parameters(keyed_hash_params)
            .with_keyed_hash_unique_identifier(tss_esapi::structures::Digest::default())
            .build()
            .map_err(|e| {
                log::error!("Failed to build sealing object public: {}", e);
                soft_fido2::Error::Other
            })
    }

    /// Seal data using TPM with hybrid encryption
    ///
    /// Uses AES-256-GCM to encrypt the data, then seals only the encryption key with TPM.
    /// This avoids TPM size limits on sealed data (typically 128 bytes).
    fn seal_data(&self, data: &[u8]) -> Result<Vec<u8>> {
        debug!("Sealing {} bytes with TPM (hybrid encryption)", data.len());

        // Generate a random 256-bit AES key
        let mut aes_key = [0u8; 32];
        OsRng.fill_bytes(&mut aes_key);

        // Generate a random 96-bit nonce for AES-GCM
        let mut nonce_bytes = [0u8; 12];
        OsRng.fill_bytes(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        // Encrypt the credential data with AES-GCM
        let cipher = Aes256Gcm::new_from_slice(&aes_key).map_err(|e| {
            log::error!("Failed to create AES cipher: {}", e);
            soft_fido2::Error::Other
        })?;

        let encrypted_data = cipher.encrypt(nonce, data).map_err(|e| {
            log::error!("Failed to encrypt data with AES-GCM: {}", e);
            soft_fido2::Error::Other
        })?;

        debug!(
            "Encrypted {} bytes to {} bytes, now sealing 32-byte AES key with TPM",
            data.len(),
            encrypted_data.len()
        );

        // Now seal only the AES key (32 bytes) with TPM
        let mut context = self.context.lock().map_err(|e| {
            log::error!("Failed to lock TPM context: {}", e);
            soft_fido2::Error::Other
        })?;

        // Create primary key
        let primary_key = self.create_primary_key(&mut context)?;

        // Create sealing object public
        let sealing_pub = self.create_sealing_public()?;

        // Create the sealed object with the AES key
        let sensitive_data = tss_esapi::structures::SensitiveData::try_from(aes_key.to_vec())
            .map_err(|e| {
                log::error!("Failed to create sensitive data for AES key: {}", e);
                soft_fido2::Error::Other
            })?;

        let create_result = context
            .create(
                primary_key,
                sealing_pub,
                None,
                Some(sensitive_data),
                None,
                None,
            )
            .map_err(|e| {
                log::error!("Failed to create sealed object: {}", e);
                soft_fido2::Error::Other
            })?;

        // Flush the primary key (we'll recreate it when unsealing)
        context.flush_context(primary_key.into()).map_err(|e| {
            log::error!("Failed to flush primary key: {}", e);
            soft_fido2::Error::Other
        })?;

        let private_tpm: TPM2B_PRIVATE = create_result.out_private.into();
        // Store just the actual data, not the whole buffer
        let private_bytes = private_tpm.buffer[..private_tpm.size as usize].to_vec();

        #[allow(clippy::unnecessary_fallible_conversions)]
        let public_tpm: TPM2B_PUBLIC = create_result.out_public.try_into().map_err(|e| {
            log::error!("Failed to convert public to TPM2B: {:?}", e);
            soft_fido2::Error::Other
        })?;

        // For Public, we need to store the entire TPM2B_PUBLIC structure as bytes
        // because it has a complex nested structure
        let public_bytes = unsafe {
            let ptr = &public_tpm as *const TPM2B_PUBLIC as *const u8;
            std::slice::from_raw_parts(ptr, std::mem::size_of::<TPM2B_PUBLIC>()).to_vec()
        };

        let sealed_blob = SealedBlob {
            encrypted_data,
            nonce: nonce_bytes.to_vec(),
            tpm_private: private_bytes,
            tpm_public: public_bytes,
        };

        // Serialize the blob to JSON
        // Use Zeroizing to ensure the serialization buffer is cleared from memory after use
        let serialized = Zeroizing::new(serde_json::to_vec(&sealed_blob).map_err(|e| {
            log::error!("Failed to serialize sealed blob: {}", e);
            soft_fido2::Error::Other
        })?);

        Ok(serialized.to_vec())
    }

    /// Unseal data using TPM with hybrid decryption
    ///
    /// Unseals the AES key from TPM, then decrypts the data with AES-GCM.
    fn unseal_data(&self, sealed_data: &[u8]) -> Result<Vec<u8>> {
        debug!("Unsealing data with TPM (hybrid decryption)");

        let mut context = self.context.lock().map_err(|e| {
            log::error!("Failed to lock TPM context: {}", e);
            soft_fido2::Error::Other
        })?;

        let sealed_blob: SealedBlob = serde_json::from_slice(sealed_data).map_err(|e| {
            log::error!("Failed to deserialize sealed blob: {}", e);
            soft_fido2::Error::Other
        })?;

        let primary_key = self.create_primary_key(&mut context)?;

        let mut private_tpm = TPM2B_PRIVATE {
            size: sealed_blob.tpm_private.len() as u16,
            buffer: [0u8; 1550],
        };
        private_tpm.buffer[..sealed_blob.tpm_private.len()]
            .copy_from_slice(&sealed_blob.tpm_private);

        let public_tpm: TPM2B_PUBLIC = unsafe {
            let mut public_struct: TPM2B_PUBLIC = std::mem::zeroed();
            let ptr = &mut public_struct as *mut TPM2B_PUBLIC as *mut u8;
            std::ptr::copy_nonoverlapping(
                sealed_blob.tpm_public.as_ptr(),
                ptr,
                std::cmp::min(
                    sealed_blob.tpm_public.len(),
                    std::mem::size_of::<TPM2B_PUBLIC>(),
                ),
            );
            public_struct
        };

        // Convert to tss-esapi types
        let private = tss_esapi::structures::Private::try_from(private_tpm).map_err(|e| {
            log::error!("Failed to convert TPM2B_PRIVATE to Private: {}", e);
            soft_fido2::Error::Other
        })?;

        let public = tss_esapi::structures::Public::try_from(public_tpm).map_err(|e| {
            log::error!("Failed to convert TPM2B_PUBLIC to Public: {}", e);
            soft_fido2::Error::Other
        })?;

        // Load the sealed object
        let sealed_handle = context.load(primary_key, private, public).map_err(|e| {
            log::error!("Failed to load sealed object: {}", e);
            soft_fido2::Error::Other
        })?;

        // Unseal the AES key from TPM
        let unsealed_key = context.unseal(sealed_handle.into()).map_err(|e| {
            log::error!("Failed to unseal AES key: {}", e);
            soft_fido2::Error::Other
        })?;

        // Flush handles
        context.flush_context(sealed_handle.into()).map_err(|e| {
            log::error!("Failed to flush sealed handle: {}", e);
            soft_fido2::Error::Other
        })?;

        context.flush_context(primary_key.into()).map_err(|e| {
            log::error!("Failed to flush primary key: {}", e);
            soft_fido2::Error::Other
        })?;

        // Drop the mutex before AES decryption
        drop(context);

        // Extract the AES key
        let aes_key = unsealed_key.value();
        if aes_key.len() != 32 {
            log::error!(
                "Unsealed key has wrong size: {} (expected 32)",
                aes_key.len()
            );
            return Err(soft_fido2::Error::Other);
        }

        // Decrypt the data with AES-GCM
        let nonce = Nonce::from_slice(&sealed_blob.nonce);
        let cipher = Aes256Gcm::new_from_slice(aes_key).map_err(|e| {
            log::error!("Failed to create AES cipher: {}", e);
            soft_fido2::Error::Other
        })?;

        let decrypted_data = cipher
            .decrypt(nonce, sealed_blob.encrypted_data.as_ref())
            .map_err(|e| {
                log::error!("Failed to decrypt data with AES-GCM: {}", e);
                soft_fido2::Error::Other
            })?;

        debug!("Successfully decrypted {} bytes", decrypted_data.len());

        Ok(decrypted_data)
    }

    /// Read a credential from a specific file path WITHOUT caching
    /// Used for operations that need &self
    #[allow(dead_code)]
    fn read_credential_from_path_no_cache(&self, path: &Path) -> Result<soft_fido2::Credential> {
        debug!("Reading credential (no cache) from path: {:?}", path);

        let mut file = File::open(path).map_err(|e| {
            log::error!("Failed to open credential file {}: {}", path.display(), e);
            soft_fido2::Error::DoesNotExist
        })?;

        let mut sealed_data = Vec::new();
        file.read_to_end(&mut sealed_data).map_err(|e| {
            log::error!("Failed to read credential file {}: {}", path.display(), e);
            soft_fido2::Error::Other
        })?;

        // Unseal the data using TPM
        // Use Zeroizing to ensure the unsealed data is cleared from memory after use
        let unsealed_data = Zeroizing::new(self.unseal_data(&sealed_data)?);

        // Load using auto format (tries our format, falls back to soft-fido2 format)
        Credential::from_bytes(&unsealed_data).map(|cred| cred.to_soft_fido2())
    }

    /// Read a credential from a specific file path
    /// Uses time-limited cache to avoid redundant TPM unsealing
    fn read_credential_from_path(&mut self, path: &Path) -> Result<soft_fido2::Credential> {
        if let Some(cached) = self.cache.get(path) {
            if Instant::now() < cached.expires_at {
                debug!("Cache HIT for path: {:?}", path);
                return Ok(cached.credential.clone());
            } else {
                debug!("Cache entry expired for path: {:?}", path);
            }
        }

        debug!(
            "Cache MISS - reading and unsealing credential from path: {:?}",
            path
        );

        // Evict expired entries before adding new one
        self.cache.evict_expired();

        // If cache is full, evict oldest entry
        self.cache.evict_oldest_if_full();

        let mut file = File::open(path).map_err(|e| {
            log::error!("Failed to open credential file {}: {}", path.display(), e);
            soft_fido2::Error::DoesNotExist
        })?;

        let mut sealed_data = Vec::new();
        file.read_to_end(&mut sealed_data).map_err(|e| {
            log::error!("Failed to read credential file {}: {}", path.display(), e);
            soft_fido2::Error::Other
        })?;

        // Unseal the data using TPM
        // Use Zeroizing to ensure the unsealed data is cleared from memory after use
        let unsealed_data = Zeroizing::new(self.unseal_data(&sealed_data)?);

        // Load using auto format (tries our format, falls back to soft-fido2 format)
        let credential = Credential::from_bytes(&unsealed_data).map(|cred| cred.to_soft_fido2())?;

        // Cache the unsealed credential with automatic TTL
        self.cache.insert(path.to_path_buf(), credential.clone());

        Ok(credential)
    }

    /// Read a credential by its ID
    fn read_credential_by_id(&mut self, id: &[u8]) -> Result<soft_fido2::Credential> {
        let path_info = self.indexes.id.get(id).ok_or_else(|| {
            debug!("Credential not found in index");
            soft_fido2::Error::DoesNotExist
        })?;

        let path = path_info.to_path(&self.storage_dir);
        self.read_credential_from_path(&path)
    }

    /// Find the next credential matching the current filter
    /// Uses indexes for efficient lookup
    fn find_next(&mut self) -> Result<soft_fido2::Credential> {
        debug!(
            "Finding next credential (index: {}/{})",
            self.iteration_index,
            self.iteration_entries.len()
        );

        if self.iteration_index >= self.iteration_entries.len() {
            debug!("No more credentials matching filter");
            return Err(soft_fido2::Error::DoesNotExist);
        }

        let path = self.iteration_entries[self.iteration_index].clone();
        self.iteration_index += 1;

        self.read_credential_from_path(&path)
    }

    /// Write a credential to storage
    /// Uses new directory structure: {storage_dir}/{rp_id}/{cred_id_hex}.tpm
    fn write_credential(&mut self, cred: &soft_fido2::Credential) -> Result<()> {
        self.cache.evict_expired();

        let path = get_credential_path(&self.storage_dir, &cred.rp.id, &cred.id, "tpm");
        debug!("Writing credential to: {:?}", path);

        // Ensure parent directory exists with secure permissions
        if let Some(parent) = path.parent() {
            create_secure_dir_all(parent).map_err(|e| {
                debug!("Failed to create directory: {}", e);
                soft_fido2::Error::Other
            })?;
        }

        // Convert to our format for controlled serialization
        let our_cred = Credential::from_soft_fido2(cred);
        // Use Zeroizing to ensure credential bytes are cleared from memory after use
        let bytes = Zeroizing::new(our_cred.to_bytes()?);

        // Seal the data using TPM
        let sealed_data = self.seal_data(&bytes)?;

        let mut file = create_secure_file(&path).map_err(|e| {
            log::error!("Failed to create credential file {}: {}", path.display(), e);
            soft_fido2::Error::Other
        })?;

        file.write_all(&sealed_data).map_err(|e| {
            log::error!("Failed to write credential file {}: {}", path.display(), e);
            soft_fido2::Error::Other
        })?;

        debug!("Successfully wrote and sealed credential");

        // Invalidate cache entry for this credential to ensure fresh reads
        self.cache.remove(&path);

        // Update all indexes using shared function
        let path_info =
            CredentialPathInfo::new(cred.rp.id.clone(), cred.id.to_vec(), "tpm".to_string());
        update_indexes_on_write(&mut self.indexes, path_info);

        Ok(())
    }

    /// Delete a credential from storage
    fn delete_credential(&mut self, id: &[u8]) -> Result<()> {
        self.cache.evict_expired();

        debug!("Deleting credential with ID: {}", bytes_to_hex(id));

        let path_info = self
            .indexes
            .id
            .get(id)
            .ok_or_else(|| {
                debug!("Credential not found in index");
                soft_fido2::Error::DoesNotExist
            })?
            .clone();

        let path = path_info.to_path(&self.storage_dir);

        // Delete the file
        std::fs::remove_file(&path).map_err(|e| {
            debug!("Failed to delete file: {}", e);
            soft_fido2::Error::Other
        })?;

        // Remove from cache
        self.cache.remove(&path);

        // Remove from all indexes using shared function
        update_indexes_on_delete(&mut self.indexes, id);

        debug!("Successfully deleted credential");

        Ok(())
    }
}

impl CredentialStorage for TpmStorageAdapter {
    fn read_first(&mut self, filter: CredentialFilter) -> Result<soft_fido2::Credential> {
        self.cache.evict_expired();

        debug!("read_first called with filter: {:?}", filter);

        // Initialize iteration using the appropriate index
        self.iteration_entries = match &filter {
            CredentialFilter::None => {
                // No filter: iterate all credentials
                self.indexes
                    .id
                    .values()
                    .map(|path_info| path_info.to_path(&self.storage_dir))
                    .collect()
            }
            CredentialFilter::ById(id) => {
                // ById: direct lookup in index
                if let Some(path_info) = self.indexes.id.get(id.as_slice()) {
                    vec![path_info.to_path(&self.storage_dir)]
                } else {
                    Vec::new()
                }
            }
            CredentialFilter::ByRp(rp_id) => {
                // ByRp: lookup in index
                self.indexes
                    .rp
                    .get(rp_id.as_str())
                    .map(|cred_ids| {
                        cred_ids
                            .iter()
                            .filter_map(|cred_id| {
                                self.indexes
                                    .id
                                    .get(cred_id)
                                    .map(|path_info| path_info.to_path(&self.storage_dir))
                            })
                            .collect()
                    })
                    .unwrap_or_default()
            }
            CredentialFilter::ByHash(hash) => {
                // ByHash: lookup in index
                self.indexes
                    .rp_hash
                    .get(hash)
                    .map(|cred_ids| {
                        cred_ids
                            .iter()
                            .filter_map(|cred_id| {
                                self.indexes
                                    .id
                                    .get(cred_id)
                                    .map(|path_info| path_info.to_path(&self.storage_dir))
                            })
                            .collect()
                    })
                    .unwrap_or_default()
            }
        };

        self.iteration_index = 0;

        debug!(
            "Starting iteration with {} entries for filter: {:?}",
            self.iteration_entries.len(),
            filter
        );

        self.find_next()
    }

    fn read_next(&mut self) -> Result<soft_fido2::Credential> {
        self.cache.evict_expired();

        debug!("read_next called");
        self.find_next()
    }

    fn read(&mut self, id: &[u8]) -> Result<soft_fido2::Credential> {
        self.cache.evict_expired();

        debug!("read called with id: {}", bytes_to_hex(id));

        // Load and return credential directly (no re-serialization)
        self.read_credential_by_id(id)
    }

    fn write(&mut self, cred_ref: soft_fido2::CredentialRef) -> Result<()> {
        self.cache.evict_expired();

        debug!("write called for RP: {}", cred_ref.rp_id);

        // Just save the credential as provided by soft-fido2
        // This is called both during registration (new credential) and
        // during authentication (updating sign counter)
        let credential = cred_ref.to_owned();
        self.write_credential(&credential)
    }

    fn delete(&mut self, id: &[u8]) -> Result<()> {
        self.cache.evict_expired();

        debug!("delete called with id: {}", bytes_to_hex(id));
        self.delete_credential(id)
    }

    fn count_credentials(&self) -> usize {
        let count = self.indexes.id.len();
        debug!("count_credentials: {}", count);
        count
    }

    fn disable_user_verification(&self) -> bool {
        // TPM backend supports user verification
        false
    }

    fn cleanup_expired_cache(&mut self) {
        self.cache.evict_expired();
    }
}