auths-index 0.0.1-rc.10

SQLite-backed index for O(1) attestation lookups
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
use crate::error::Result;
use crate::schema;
use auths_verifier::core::{CommitOid, ResourceId};
use auths_verifier::keri::{Prefix, Said};
use auths_verifier::types::{CanonicalDid, IdentityDID};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlite::Connection;
use std::path::Path;

/// Indexed metadata for an attestation stored in the SQLite index.
/// This contains only metadata - full attestation data is loaded from Git when needed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedAttestation {
    /// Primary key - the attestation RID
    pub rid: ResourceId,
    /// DID of the issuer (controller)
    pub issuer_did: IdentityDID,
    /// DID of the attestation subject (device or identity).
    pub device_did: CanonicalDid,
    /// Git ref path (e.g., refs/auths/devices/nodes/...)
    pub git_ref: String,
    /// Git commit OID for loading full attestation (None when OID is not yet known)
    pub commit_oid: Option<CommitOid>,
    /// When this attestation was revoked, if applicable
    pub revoked_at: Option<DateTime<Utc>>,
    /// Optional expiration timestamp
    pub expires_at: Option<DateTime<Utc>>,
    /// When this index entry was last updated
    pub updated_at: DateTime<Utc>,
}

/// Index entry for a KERI identity (prefix → current key state summary).
///
/// Stores only the fields needed for O(1) membership and key lookups.
/// Full `KeyState` is loaded from `GitRegistryBackend` when needed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedIdentity {
    pub prefix: Prefix,
    pub current_keys: Vec<String>,
    pub sequence: u64,
    pub tip_said: Said,
    pub updated_at: DateTime<Utc>,
}

/// Index entry for an org membership attestation.
///
/// Enables O(1) org member listing without Git tree traversal.
/// Full `Attestation` is loaded from Git when policy evaluation needs it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedOrgMember {
    pub org_prefix: Prefix,
    pub member_did: CanonicalDid,
    pub issuer_did: IdentityDID,
    pub rid: ResourceId,
    pub revoked_at: Option<DateTime<Utc>>,
    pub expires_at: Option<DateTime<Utc>>,
    pub updated_at: DateTime<Utc>,
}

/// SQLite-backed index for O(1) attestation, identity, and org member lookups.
pub struct AttestationIndex {
    conn: Connection,
}

impl AttestationIndex {
    /// Opens an existing index or creates a new one at the given path.
    pub fn open_or_create(path: &Path) -> Result<Self> {
        let conn = Connection::open(path)?;
        schema::init_schema(&conn)?;
        Ok(Self { conn })
    }

    /// Creates an in-memory index (for testing).
    pub fn in_memory() -> Result<Self> {
        let conn = Connection::open(":memory:")?;
        schema::init_schema(&conn)?;
        Ok(Self { conn })
    }

    // =========================================================================
    // Attestation methods
    // =========================================================================

    /// Inserts or updates an attestation in the index.
    pub fn upsert_attestation(&self, att: &IndexedAttestation) -> Result<()> {
        let revoked_at_str = att.revoked_at.map(|dt| dt.to_rfc3339());
        let expires_at_str = att.expires_at.map(|dt| dt.to_rfc3339());
        let updated_at_str = att.updated_at.to_rfc3339();

        let mut stmt = self.conn.prepare(
            r#"
            INSERT INTO attestations (rid, issuer_did, device_did, git_ref, commit_oid, revoked_at, expires_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(rid) DO UPDATE SET
                issuer_did = excluded.issuer_did,
                device_did = excluded.device_did,
                git_ref = excluded.git_ref,
                commit_oid = excluded.commit_oid,
                revoked_at = excluded.revoked_at,
                expires_at = excluded.expires_at,
                updated_at = excluded.updated_at
            "#,
        )?;

        stmt.bind((1, att.rid.as_str()))?;
        stmt.bind((2, att.issuer_did.as_str()))?;
        stmt.bind((3, att.device_did.as_str()))?;
        stmt.bind((4, att.git_ref.as_str()))?;
        stmt.bind((5, att.commit_oid.as_ref().map(|c| c.as_str())))?;
        stmt.bind((6, revoked_at_str.as_deref()))?;
        stmt.bind((7, expires_at_str.as_deref()))?;
        stmt.bind((8, updated_at_str.as_str()))?;

        stmt.next()?;
        Ok(())
    }

    /// Queries attestations by device DID.
    pub fn query_by_device(&self, device_did: &str) -> Result<Vec<IndexedAttestation>> {
        let mut stmt = self
            .conn
            .prepare("SELECT rid, issuer_did, device_did, git_ref, commit_oid, revoked_at, expires_at, updated_at FROM attestations WHERE device_did = ?")?;

        stmt.bind((1, device_did))?;

        let mut results = Vec::new();
        while let Ok(sqlite::State::Row) = stmt.next() {
            results.push(self.row_to_attestation(&stmt)?);
        }
        Ok(results)
    }

    /// Queries attestations by issuer DID.
    pub fn query_by_issuer(&self, issuer_did: &str) -> Result<Vec<IndexedAttestation>> {
        let mut stmt = self
            .conn
            .prepare("SELECT rid, issuer_did, device_did, git_ref, commit_oid, revoked_at, expires_at, updated_at FROM attestations WHERE issuer_did = ?")?;

        stmt.bind((1, issuer_did))?;

        let mut results = Vec::new();
        while let Ok(sqlite::State::Row) = stmt.next() {
            results.push(self.row_to_attestation(&stmt)?);
        }
        Ok(results)
    }

    /// Queries attestations expiring before the given deadline.
    pub fn query_expiring_before(
        &self,
        deadline: DateTime<Utc>,
    ) -> Result<Vec<IndexedAttestation>> {
        let deadline_str = deadline.to_rfc3339();
        let mut stmt = self.conn.prepare(
            "SELECT rid, issuer_did, device_did, git_ref, commit_oid, revoked_at, expires_at, updated_at FROM attestations WHERE expires_at IS NOT NULL AND expires_at < ? AND revoked_at IS NULL",
        )?;

        stmt.bind((1, deadline_str.as_str()))?;

        let mut results = Vec::new();
        while let Ok(sqlite::State::Row) = stmt.next() {
            results.push(self.row_to_attestation(&stmt)?);
        }
        Ok(results)
    }

    /// Queries all active (non-revoked) attestations.
    pub fn query_active(&self) -> Result<Vec<IndexedAttestation>> {
        let mut stmt = self.conn.prepare(
            "SELECT rid, issuer_did, device_did, git_ref, commit_oid, revoked_at, expires_at, updated_at FROM attestations WHERE revoked_at IS NULL",
        )?;

        let mut results = Vec::new();
        while let Ok(sqlite::State::Row) = stmt.next() {
            results.push(self.row_to_attestation(&stmt)?);
        }
        Ok(results)
    }

    /// Clears all attestations from the index.
    pub fn clear(&self) -> Result<()> {
        self.conn.execute("DELETE FROM attestations")?;
        Ok(())
    }

    /// Returns the count of attestations in the index.
    pub fn count(&self) -> Result<usize> {
        let mut stmt = self.conn.prepare("SELECT COUNT(*) FROM attestations")?;
        if let Ok(sqlite::State::Row) = stmt.next() {
            let count: i64 = stmt.read(0)?;
            return Ok(count as usize);
        }
        Ok(0)
    }

    /// Returns statistics about the index.
    pub fn stats(&self) -> Result<IndexStats> {
        let total = self.count()?;

        let mut stmt_active = self
            .conn
            .prepare("SELECT COUNT(*) FROM attestations WHERE revoked_at IS NULL")?;
        let active = if let Ok(sqlite::State::Row) = stmt_active.next() {
            stmt_active.read::<i64, _>(0)?
        } else {
            0
        };

        let mut stmt_revoked = self
            .conn
            .prepare("SELECT COUNT(*) FROM attestations WHERE revoked_at IS NOT NULL")?;
        let revoked = if let Ok(sqlite::State::Row) = stmt_revoked.next() {
            stmt_revoked.read::<i64, _>(0)?
        } else {
            0
        };

        let mut stmt_expiry = self
            .conn
            .prepare("SELECT COUNT(*) FROM attestations WHERE expires_at IS NOT NULL")?;
        let with_expiry = if let Ok(sqlite::State::Row) = stmt_expiry.next() {
            stmt_expiry.read::<i64, _>(0)?
        } else {
            0
        };

        let mut stmt_devices = self
            .conn
            .prepare("SELECT COUNT(DISTINCT device_did) FROM attestations")?;
        let unique_devices = if let Ok(sqlite::State::Row) = stmt_devices.next() {
            stmt_devices.read::<i64, _>(0)?
        } else {
            0
        };

        let mut stmt_issuers = self
            .conn
            .prepare("SELECT COUNT(DISTINCT issuer_did) FROM attestations")?;
        let unique_issuers = if let Ok(sqlite::State::Row) = stmt_issuers.next() {
            stmt_issuers.read::<i64, _>(0)?
        } else {
            0
        };

        Ok(IndexStats {
            total_attestations: total,
            active_attestations: active as usize,
            revoked_attestations: revoked as usize,
            with_expiry: with_expiry as usize,
            unique_devices: unique_devices as usize,
            unique_issuers: unique_issuers as usize,
        })
    }

    /// Helper to convert a database row to an IndexedAttestation.
    fn row_to_attestation(&self, stmt: &sqlite::Statement) -> Result<IndexedAttestation> {
        let rid: String = stmt.read(0)?;
        let issuer_did: String = stmt.read(1)?;
        let device_did: String = stmt.read(2)?;
        let git_ref: String = stmt.read(3)?;
        let commit_oid: Option<String> = stmt.read(4)?;
        let revoked_at_str: Option<String> = stmt.read(5)?;
        let expires_at_str: Option<String> = stmt.read(6)?;
        let updated_at_str: String = stmt.read(7)?;

        let revoked_at = revoked_at_str
            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
            .map(|dt| dt.with_timezone(&Utc));

        let expires_at = expires_at_str
            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
            .map(|dt| dt.with_timezone(&Utc));

        let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
            .map(|dt| dt.with_timezone(&Utc))
            .unwrap_or_else(|_| Utc::now());

        #[allow(clippy::disallowed_methods)]
        // INVARIANT: issuer_did was validated on insert via upsert_attestation and stored in SQLite
        let issuer_did = IdentityDID::new_unchecked(issuer_did);
        #[allow(clippy::disallowed_methods)]
        // INVARIANT: device_did was validated on insert via upsert_attestation and stored in SQLite
        let device_did = CanonicalDid::new_unchecked(device_did);

        Ok(IndexedAttestation {
            rid: ResourceId::new(rid),
            issuer_did,
            device_did,
            git_ref,
            commit_oid: commit_oid
                .filter(|s| !s.is_empty())
                .and_then(|s| CommitOid::parse(&s).ok()),
            revoked_at,
            expires_at,
            updated_at,
        })
    }

    // =========================================================================
    // Identity methods
    // =========================================================================

    /// Inserts or updates an identity in the index.
    pub fn upsert_identity(&self, identity: &IndexedIdentity) -> Result<()> {
        let keys_json = serde_json::to_string(&identity.current_keys)?;
        let mut stmt = self.conn.prepare(
            r#"
            INSERT INTO identities (prefix, current_keys, sequence, tip_said, updated_at)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(prefix) DO UPDATE SET
                current_keys = excluded.current_keys,
                sequence     = excluded.sequence,
                tip_said     = excluded.tip_said,
                updated_at   = excluded.updated_at
            "#,
        )?;

        stmt.bind((1, identity.prefix.as_str()))?;
        stmt.bind((2, keys_json.as_str()))?;
        stmt.bind((3, identity.sequence as i64))?;
        stmt.bind((4, identity.tip_said.as_str()))?;
        stmt.bind((5, identity.updated_at.to_rfc3339().as_str()))?;

        stmt.next()?;
        Ok(())
    }

    /// Queries an identity by prefix.
    pub fn query_identity(&self, prefix: &str) -> Result<Option<IndexedIdentity>> {
        let mut stmt = self.conn.prepare(
            "SELECT prefix, current_keys, sequence, tip_said, updated_at
             FROM identities WHERE prefix = ?",
        )?;

        stmt.bind((1, prefix))?;

        if let Ok(sqlite::State::Row) = stmt.next() {
            let prefix: String = stmt.read(0)?;
            let keys_json: String = stmt.read(1)?;
            let sequence: i64 = stmt.read(2)?;
            let tip_said: String = stmt.read(3)?;
            let updated_at_str: String = stmt.read(4)?;

            let current_keys: Vec<String> = serde_json::from_str(&keys_json)?;
            let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
                .map(|dt| dt.with_timezone(&Utc))
                .unwrap_or_else(|_| Utc::now());
            Ok(Some(IndexedIdentity {
                prefix: Prefix::new_unchecked(prefix),
                current_keys,
                sequence: sequence as u64,
                tip_said: Said::new_unchecked(tip_said),
                updated_at,
            }))
        } else {
            Ok(None)
        }
    }

    // =========================================================================
    // Org member methods
    // =========================================================================

    /// Inserts or updates an org member in the index.
    pub fn upsert_org_member(&self, member: &IndexedOrgMember) -> Result<()> {
        let mut stmt = self.conn.prepare(
            r#"
            INSERT INTO org_members
                (org_prefix, member_did, issuer_did, rid, revoked_at, expires_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(org_prefix, member_did) DO UPDATE SET
                issuer_did = excluded.issuer_did,
                rid        = excluded.rid,
                revoked_at = excluded.revoked_at,
                expires_at = excluded.expires_at,
                updated_at = excluded.updated_at
            "#,
        )?;

        stmt.bind((1, member.org_prefix.as_str()))?;
        stmt.bind((2, member.member_did.as_str()))?;
        stmt.bind((3, member.issuer_did.as_str()))?;
        stmt.bind((4, member.rid.as_str()))?;
        stmt.bind((5, member.revoked_at.map(|dt| dt.to_rfc3339()).as_deref()))?;
        stmt.bind((6, member.expires_at.map(|dt| dt.to_rfc3339()).as_deref()))?;
        stmt.bind((7, member.updated_at.to_rfc3339().as_str()))?;

        stmt.next()?;
        Ok(())
    }

    /// Lists all members of an org from the index.
    pub fn list_org_members_indexed(&self, org_prefix: &str) -> Result<Vec<IndexedOrgMember>> {
        let mut stmt = self.conn.prepare(
            "SELECT org_prefix, member_did, issuer_did, rid, revoked_at, expires_at, updated_at
             FROM org_members WHERE org_prefix = ?
             ORDER BY member_did ASC",
        )?;

        stmt.bind((1, org_prefix))?;

        let parse_dt = |s: Option<String>| {
            s.and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                .map(|dt| dt.with_timezone(&Utc))
        };

        let mut members = Vec::new();
        while let Ok(sqlite::State::Row) = stmt.next() {
            let org_prefix: String = stmt.read(0)?;
            let member_did: String = stmt.read(1)?;
            let issuer_did: String = stmt.read(2)?;
            let rid: String = stmt.read(3)?;
            let revoked_str: Option<String> = stmt.read(4)?;
            let expires_str: Option<String> = stmt.read(5)?;
            let updated_str: String = stmt.read(6)?;

            #[allow(clippy::disallowed_methods)]
            // INVARIANT: org_prefix was validated on insert via upsert_org_member and stored in SQLite
            let org_prefix = Prefix::new_unchecked(org_prefix);
            #[allow(clippy::disallowed_methods)]
            // INVARIANT: member_did was validated on insert via upsert_org_member and stored in SQLite
            let member_did = CanonicalDid::new_unchecked(member_did);
            #[allow(clippy::disallowed_methods)]
            // INVARIANT: issuer_did was validated on insert via upsert_org_member and stored in SQLite
            let issuer_did = IdentityDID::new_unchecked(issuer_did);

            members.push(IndexedOrgMember {
                org_prefix,
                member_did,
                issuer_did,
                rid: ResourceId::new(rid),
                revoked_at: parse_dt(revoked_str),
                expires_at: parse_dt(expires_str),
                updated_at: DateTime::parse_from_rfc3339(&updated_str)
                    .map(|dt| dt.with_timezone(&Utc))
                    .unwrap_or_else(|_| Utc::now()),
            });
        }

        Ok(members)
    }

    /// Returns the count of org members for a given org in the index.
    pub fn count_org_members(&self, org_prefix: &str) -> Result<usize> {
        let mut stmt = self
            .conn
            .prepare("SELECT COUNT(*) FROM org_members WHERE org_prefix = ?")?;
        stmt.bind((1, org_prefix))?;
        if let Ok(sqlite::State::Row) = stmt.next() {
            let count: i64 = stmt.read(0)?;
            return Ok(count as usize);
        }
        Ok(0)
    }
}

/// Statistics about the attestation index.
#[derive(Debug, Clone)]
pub struct IndexStats {
    pub total_attestations: usize,
    pub active_attestations: usize,
    pub revoked_attestations: usize,
    pub with_expiry: usize,
    pub unique_devices: usize,
    pub unique_issuers: usize,
}

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

    fn create_test_attestation(
        rid: &str,
        device: &str,
        revoked_at: Option<DateTime<Utc>>,
    ) -> IndexedAttestation {
        #[allow(clippy::disallowed_methods)] // INVARIANT: test-only hardcoded DID string literal
        let issuer_did = IdentityDID::new_unchecked("did:key:issuer123");
        #[allow(clippy::disallowed_methods)] // INVARIANT: test-only DID string from caller
        let device_did = CanonicalDid::new_unchecked(device);

        IndexedAttestation {
            rid: ResourceId::new(rid),
            issuer_did,
            device_did,
            git_ref: format!("refs/auths/devices/nodes/{}/signatures", device),
            commit_oid: None,
            revoked_at,
            expires_at: Some(Utc::now() + Duration::days(30)),
            updated_at: Utc::now(),
        }
    }

    #[test]
    fn test_in_memory_index() {
        let index = AttestationIndex::in_memory().unwrap();
        assert_eq!(index.count().unwrap(), 0);
    }

    #[test]
    fn test_upsert_and_query() {
        let index = AttestationIndex::in_memory().unwrap();
        let att = create_test_attestation("rid1", "did:key:device1", None);

        index.upsert_attestation(&att).unwrap();
        assert_eq!(index.count().unwrap(), 1);

        let results = index.query_by_device("did:key:device1").unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].rid, "rid1");
    }

    #[test]
    fn test_upsert_updates_existing() {
        let index = AttestationIndex::in_memory().unwrap();
        let mut att = create_test_attestation("rid1", "did:key:device1", None);

        index.upsert_attestation(&att).unwrap();
        assert_eq!(index.count().unwrap(), 1);

        // Update the attestation
        att.revoked_at = Some(Utc::now());
        index.upsert_attestation(&att).unwrap();
        assert_eq!(index.count().unwrap(), 1);

        let results = index.query_by_device("did:key:device1").unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].revoked_at.is_some());
    }

    #[test]
    fn test_query_by_issuer() {
        let index = AttestationIndex::in_memory().unwrap();
        let att1 = create_test_attestation("rid1", "did:key:device1", None);
        let att2 = create_test_attestation("rid2", "did:key:device2", None);

        index.upsert_attestation(&att1).unwrap();
        index.upsert_attestation(&att2).unwrap();

        let results = index.query_by_issuer("did:key:issuer123").unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_query_active() {
        let index = AttestationIndex::in_memory().unwrap();
        let att1 = create_test_attestation("rid1", "did:key:device1", None);
        let att2 = create_test_attestation("rid2", "did:key:device2", Some(Utc::now()));

        index.upsert_attestation(&att1).unwrap();
        index.upsert_attestation(&att2).unwrap();

        let active = index.query_active().unwrap();
        assert_eq!(active.len(), 1);
        assert_eq!(active[0].rid, "rid1");
    }

    #[test]
    fn test_query_expiring_before() {
        let index = AttestationIndex::in_memory().unwrap();

        let mut att1 = create_test_attestation("rid1", "did:key:device1", None);
        att1.expires_at = Some(Utc::now() + Duration::days(5));

        let mut att2 = create_test_attestation("rid2", "did:key:device2", None);
        att2.expires_at = Some(Utc::now() + Duration::days(60));

        index.upsert_attestation(&att1).unwrap();
        index.upsert_attestation(&att2).unwrap();

        let deadline = Utc::now() + Duration::days(10);
        let expiring = index.query_expiring_before(deadline).unwrap();
        assert_eq!(expiring.len(), 1);
        assert_eq!(expiring[0].rid, "rid1");
    }

    #[test]
    fn test_clear() {
        let index = AttestationIndex::in_memory().unwrap();
        let att = create_test_attestation("rid1", "did:key:device1", None);

        index.upsert_attestation(&att).unwrap();
        assert_eq!(index.count().unwrap(), 1);

        index.clear().unwrap();
        assert_eq!(index.count().unwrap(), 0);
    }

    #[test]
    fn test_stats() {
        let index = AttestationIndex::in_memory().unwrap();
        let att1 = create_test_attestation("rid1", "did:key:device1", None);
        let att2 = create_test_attestation("rid2", "did:key:device2", Some(Utc::now()));

        index.upsert_attestation(&att1).unwrap();
        index.upsert_attestation(&att2).unwrap();

        let stats = index.stats().unwrap();
        assert_eq!(stats.total_attestations, 2);
        assert_eq!(stats.active_attestations, 1);
        assert_eq!(stats.revoked_attestations, 1);
        assert_eq!(stats.unique_devices, 2);
        assert_eq!(stats.unique_issuers, 1);
    }

    #[test]
    fn test_upsert_and_query_identity() {
        let index = AttestationIndex::in_memory().unwrap();
        let identity = IndexedIdentity {
            prefix: Prefix::new_unchecked("ETestPrefix123".to_string()),
            current_keys: vec!["DKey1".to_string(), "DKey2".to_string()],
            sequence: 3,
            tip_said: Said::new_unchecked("ETipSaid123".to_string()),
            updated_at: Utc::now(),
        };

        index.upsert_identity(&identity).unwrap();

        let result = index.query_identity("ETestPrefix123").unwrap();
        assert!(result.is_some());
        let result = result.unwrap();
        assert_eq!(result.prefix, "ETestPrefix123");
        assert_eq!(result.sequence, 3);
        assert_eq!(result.current_keys.len(), 2);
        assert_eq!(result.tip_said, "ETipSaid123");
    }

    #[test]
    fn test_upsert_identity_updates_existing() {
        let index = AttestationIndex::in_memory().unwrap();
        let identity = IndexedIdentity {
            prefix: Prefix::new_unchecked("ETestPrefix".to_string()),
            current_keys: vec!["DKey1".to_string()],
            sequence: 0,
            tip_said: Said::new_unchecked("ESaid0".to_string()),
            updated_at: Utc::now(),
        };
        index.upsert_identity(&identity).unwrap();

        let updated = IndexedIdentity {
            prefix: Prefix::new_unchecked("ETestPrefix".to_string()),
            current_keys: vec!["DKey2".to_string()],
            sequence: 1,
            tip_said: Said::new_unchecked("ESaid1".to_string()),
            updated_at: Utc::now(),
        };
        index.upsert_identity(&updated).unwrap();

        let result = index.query_identity("ETestPrefix").unwrap().unwrap();
        assert_eq!(result.sequence, 1);
        assert_eq!(result.tip_said, "ESaid1");
        assert_eq!(result.current_keys, vec!["DKey2"]);
    }

    #[test]
    fn test_query_identity_not_found() {
        let index = AttestationIndex::in_memory().unwrap();
        let result = index.query_identity("ENotExist").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_upsert_and_list_org_members() {
        let index = AttestationIndex::in_memory().unwrap();
        #[allow(clippy::disallowed_methods)] // INVARIANT: test-only hardcoded DID string literals
        let member = IndexedOrgMember {
            org_prefix: Prefix::new_unchecked("did:keri:EOrg".to_string()),
            member_did: CanonicalDid::new_unchecked("did:key:z6MkMember1"),
            issuer_did: IdentityDID::new_unchecked("did:keri:EOrg"),
            rid: ResourceId::new("rid-member-1"),
            revoked_at: None,
            expires_at: None,
            updated_at: Utc::now(),
        };

        index.upsert_org_member(&member).unwrap();

        let members = index.list_org_members_indexed("did:keri:EOrg").unwrap();
        assert_eq!(members.len(), 1);
        assert_eq!(members[0].member_did.as_str(), "did:key:z6MkMember1");
        assert_eq!(members[0].rid, "rid-member-1");
    }

    #[test]
    fn test_upsert_org_member_updates_existing() {
        let index = AttestationIndex::in_memory().unwrap();
        #[allow(clippy::disallowed_methods)] // INVARIANT: test-only hardcoded DID string literals
        let member = IndexedOrgMember {
            org_prefix: Prefix::new_unchecked("did:keri:EOrg".to_string()),
            member_did: CanonicalDid::new_unchecked("did:key:z6MkMember1"),
            issuer_did: IdentityDID::new_unchecked("did:keri:EOrg"),
            rid: ResourceId::new("rid-v1"),
            revoked_at: None,
            expires_at: None,
            updated_at: Utc::now(),
        };
        index.upsert_org_member(&member).unwrap();

        #[allow(clippy::disallowed_methods)] // INVARIANT: test-only hardcoded DID string literals
        let updated = IndexedOrgMember {
            org_prefix: Prefix::new_unchecked("did:keri:EOrg".to_string()),
            member_did: CanonicalDid::new_unchecked("did:key:z6MkMember1"),
            issuer_did: IdentityDID::new_unchecked("did:keri:EOrg"),
            rid: ResourceId::new("rid-v2"),
            revoked_at: Some(Utc::now()),
            expires_at: None,
            updated_at: Utc::now(),
        };
        index.upsert_org_member(&updated).unwrap();

        let members = index.list_org_members_indexed("did:keri:EOrg").unwrap();
        assert_eq!(members.len(), 1);
        assert_eq!(members[0].rid, "rid-v2");
        assert!(members[0].revoked_at.is_some());
    }

    #[test]
    fn test_count_org_members() {
        let index = AttestationIndex::in_memory().unwrap();
        assert_eq!(index.count_org_members("did:keri:EOrg").unwrap(), 0);

        for i in 0..3 {
            #[allow(clippy::disallowed_methods)]
            // INVARIANT: test-only hardcoded DID string literals
            let member = IndexedOrgMember {
                org_prefix: Prefix::new_unchecked("did:keri:EOrg".to_string()),
                member_did: CanonicalDid::new_unchecked(format!("did:key:z6MkMember{}", i)),
                issuer_did: IdentityDID::new_unchecked("did:keri:EOrg"),
                rid: ResourceId::new(format!("rid-{}", i)),
                revoked_at: None,
                expires_at: None,
                updated_at: Utc::now(),
            };
            index.upsert_org_member(&member).unwrap();
        }

        assert_eq!(index.count_org_members("did:keri:EOrg").unwrap(), 3);
        assert_eq!(index.count_org_members("did:keri:EOther").unwrap(), 0);
    }
}