auths-id 0.1.2

Multi-device identity and attestation crate for Auths
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
use auths_core::signing::StorageSigner;
use auths_core::storage::keychain::{IdentityDID, KeyAlias, KeyRole, KeyStorage};
use auths_core::testing::{IsolatedKeychainHandle, TestPassphraseProvider};
use auths_id::attestation::create::create_signed_attestation;
use auths_id::identity::initialize::initialize_keri_identity;
use auths_id::identity::rotate::rotate_keri_identity;
use auths_id::keri::{Event, GitKel, resolve_did_keri, resolve_did_keri_at_sequence, validate_kel};
use auths_id::storage::git_refs::AttestationMetadata;
use auths_id::storage::layout::StorageLayoutConfig;
use auths_id::testing::fakes::FakeIdentityStorage;
use auths_verifier::verify::{verify_at_time, verify_with_keys};
use auths_verifier::{
    CanonicalDid, DevicePublicKey, VerificationStatus, verify_chain, verify_device_authorization,
};

/// Wrap a raw Ed25519 public key (32 bytes) into a `DevicePublicKey` for tests.
fn ed(pk: &[u8]) -> DevicePublicKey {
    DevicePublicKey::try_new(auths_crypto::CurveType::Ed25519, pk).unwrap()
}

use chrono::Utc;
use git2::Repository;
use ring::rand::SystemRandom;
use ring::signature::{Ed25519KeyPair, KeyPair};
use std::path::Path;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Initializes a KERI identity with an isolated (per-test) keychain.
/// Returns (identity_did, alias).
fn init_identity(
    repo_path: &Path,
    alias: &str,
    passphrase: &str,
    keychain: &IsolatedKeychainHandle,
) -> (String, String) {
    let provider = TestPassphraseProvider::new(passphrase);
    let identity_storage = FakeIdentityStorage::new();

    let alias = KeyAlias::new_unchecked(alias);
    let (did, alias) = initialize_keri_identity(
        repo_path,
        &alias,
        None,
        &provider,
        &identity_storage,
        keychain,
        chrono::Utc::now(),
        auths_crypto::CurveType::Ed25519,
    )
    .expect("Failed to initialize identity");
    (did.to_string(), alias.into_inner())
}

/// Generates a fresh Ed25519 device keypair and stores it in the provided keychain.
/// Returns (device_did, device_public_key_bytes_32).
fn generate_device_keypair(
    identity_did: &str,
    device_alias: &str,
    passphrase: &str,
    keychain: &IsolatedKeychainHandle,
) -> (CanonicalDid, [u8; 32]) {
    let rng = SystemRandom::new();
    let device_pkcs8 =
        Ed25519KeyPair::generate_pkcs8(&rng).expect("Failed to generate device keypair");
    let device_keypair =
        Ed25519KeyPair::from_pkcs8(device_pkcs8.as_ref()).expect("Failed to parse device keypair");
    let device_pk: [u8; 32] = device_keypair
        .public_key()
        .as_ref()
        .try_into()
        .expect("Public key should be 32 bytes");

    let device_did =
        CanonicalDid::from_public_key_did_key(&device_pk, auths_crypto::CurveType::Ed25519);

    let encrypted = auths_core::crypto::signer::encrypt_keypair(device_pkcs8.as_ref(), passphrase)
        .expect("Failed to encrypt device key");
    let identity_did_typed = IdentityDID::new_unchecked(identity_did);
    keychain
        .store_key(
            &KeyAlias::new_unchecked(device_alias),
            &identity_did_typed,
            KeyRole::Primary,
            &encrypted,
        )
        .expect("Failed to store device key");

    (device_did, device_pk)
}

/// Creates a signed attestation using the real `create_signed_attestation` API.
#[allow(clippy::too_many_arguments)]
fn create_test_attestation(
    rid: &str,
    identity_did: &str,
    identity_alias: &str,
    subject: &CanonicalDid,
    device_pk: &[u8],
    device_alias: Option<&str>,
    passphrase: &str,
    keychain: &IsolatedKeychainHandle,
) -> auths_verifier::core::Attestation {
    let signer = StorageSigner::new(keychain.clone());
    let provider = TestPassphraseProvider::new(passphrase);
    let now = Utc::now();
    let meta = AttestationMetadata {
        note: Some("integration test".to_string()),
        timestamp: Some(now),
        expires_at: None,
    };
    let identity_did = IdentityDID::new_unchecked(identity_did);
    let identity_alias = KeyAlias::new_unchecked(identity_alias);
    let device_alias = device_alias.map(KeyAlias::new_unchecked);

    create_signed_attestation(
        now,
        auths_id::attestation::create::AttestationInput {
            rid,
            identity_did: &identity_did,
            subject,
            device_public_key: device_pk,
            // Test fixture: ring Ed25519KeyPair pubkey (32 bytes by construction).
            device_curve: auths_crypto::CurveType::Ed25519,
            payload: None,
            meta: &meta,
            identity_alias: Some(&identity_alias),
            device_alias: device_alias.as_ref(),
            delegated_by: None,
            commit_sha: None,
            signer_type: None,
        },
        &signer,
        &provider,
    )
    .expect("Failed to create signed attestation")
}

/// Resolves the current public key for a did:keri identity by replaying the KEL.
fn resolve_identity_public_key(repo_path: &Path, did: &str) -> Vec<u8> {
    let repo = Repository::open(repo_path).expect("Failed to open repo");
    let resolution = resolve_did_keri(&repo, did).expect("Failed to resolve did:keri");
    resolution.public_key
}

/// Resolves the public key at a specific KEL sequence.
fn resolve_identity_public_key_at_sequence(repo_path: &Path, did: &str, sequence: u64) -> Vec<u8> {
    let repo = Repository::open(repo_path).expect("Failed to open repo");
    let resolution = resolve_did_keri_at_sequence(&repo, did, sequence as u128)
        .expect("Failed to resolve at sequence");
    resolution.public_key
}

/// Rotates a KERI identity via the high-level API.
fn rotate_identity(
    repo_path: &Path,
    current_alias: &str,
    next_alias: &str,
    passphrase: &str,
    keychain: &IsolatedKeychainHandle,
) {
    let provider = TestPassphraseProvider::new(passphrase);
    let config = StorageLayoutConfig::default();

    let current_alias = KeyAlias::new_unchecked(current_alias);
    let next_alias = KeyAlias::new_unchecked(next_alias);
    rotate_keri_identity(
        repo_path,
        &current_alias,
        &next_alias,
        &provider,
        &config,
        keychain,
        None,
        chrono::Utc::now(),
    )
    .expect("Failed to rotate identity");
}

// ---------------------------------------------------------------------------
// Test cases
// ---------------------------------------------------------------------------

/// Full lifecycle: init -> attest -> verify -> rotate -> historical verify -> new attest -> verify
#[tokio::test(flavor = "multi_thread")]
async fn test_full_identity_lifecycle() {
    let kc = IsolatedKeychainHandle::new();
    let (_dir, _repo) = auths_test_utils::git::init_test_repo();
    let repo_path = _dir.path().to_path_buf();
    let passphrase = "Test-P@ss12345";

    // 1. Initialize identity
    let (identity_did, identity_alias) = init_identity(&repo_path, "main", passphrase, &kc);
    assert!(
        identity_did.starts_with("did:keri:"),
        "DID should be a KERI DID"
    );

    // 2. Resolve the identity public key from KEL
    let identity_pk = resolve_identity_public_key(&repo_path, &identity_did);
    assert_eq!(
        identity_pk.len(),
        32,
        "Ed25519 public key should be 32 bytes"
    );

    // 3. Generate a device keypair and create attestation
    let (device_did, device_pk) =
        generate_device_keypair(&identity_did, "device-laptop", passphrase, &kc);
    let attestation = create_test_attestation(
        "test-repo",
        &identity_did,
        &identity_alias,
        &device_did,
        &device_pk,
        Some("device-laptop"),
        passphrase,
        &kc,
    );

    // 4. Verify the attestation with the identity's public key
    verify_with_keys(&attestation, &ed(&identity_pk))
        .await
        .expect("Attestation should verify");

    // 5. Rotate the identity key
    rotate_identity(&repo_path, "main", "main-rot1", passphrase, &kc);

    // 6. Verify OLD attestation still passes with historical key (sequence 0)
    let old_pk = resolve_identity_public_key_at_sequence(&repo_path, &identity_did, 0);
    assert_eq!(old_pk, identity_pk, "Historical key should match original");
    verify_at_time(&attestation, &ed(&old_pk), attestation.timestamp.unwrap())
        .await
        .expect("Old attestation should verify with historical key");

    // 7. Create NEW attestation with rotated key
    let new_identity_pk = resolve_identity_public_key(&repo_path, &identity_did);
    assert_ne!(
        new_identity_pk, identity_pk,
        "Rotated key should differ from original"
    );

    let (device_did2, device_pk2) =
        generate_device_keypair(&identity_did, "device-phone", passphrase, &kc);
    let new_attestation = create_test_attestation(
        "test-repo",
        &identity_did,
        "main-rot1",
        &device_did2,
        &device_pk2,
        Some("device-phone"),
        passphrase,
        &kc,
    );

    // 8. Verify new attestation with new public key
    verify_with_keys(&new_attestation, &ed(&new_identity_pk))
        .await
        .expect("New attestation should verify with rotated key");
}

/// Chain verification: identity -> device1 -> device2, then rotate and re-verify chain.
#[tokio::test(flavor = "multi_thread")]
async fn test_attestation_chain_after_rotation() {
    let kc = IsolatedKeychainHandle::new();
    let (_dir, _repo) = auths_test_utils::git::init_test_repo();
    let repo_path = _dir.path().to_path_buf();
    let passphrase = "Test-P@ss12345";

    // Init identity
    let (identity_did, identity_alias) = init_identity(&repo_path, "chain-id", passphrase, &kc);
    let identity_pk = resolve_identity_public_key(&repo_path, &identity_did);

    // Create device1 and attestation: identity -> device1
    let (device1_did, device1_pk) =
        generate_device_keypair(&identity_did, "chain-device1", passphrase, &kc);
    let att1 = create_test_attestation(
        "test-repo",
        &identity_did,
        &identity_alias,
        &device1_did,
        &device1_pk,
        Some("chain-device1"),
        passphrase,
        &kc,
    );

    // Create device2 and attestation: device1 -> device2
    let (device2_did, device2_pk) =
        generate_device_keypair(&identity_did, "chain-device2", passphrase, &kc);

    let device1_did_str = device1_did.to_string();
    let att2 = create_test_attestation(
        "test-repo",
        &device1_did_str,
        "chain-device1",
        &device2_did,
        &device2_pk,
        Some("chain-device2"),
        passphrase,
        &kc,
    );

    // Verify 2-link chain
    let report = verify_chain(&[att1.clone(), att2], &ed(&identity_pk))
        .await
        .expect("Chain verify failed");
    assert!(report.is_valid(), "Chain should be valid");
    assert_eq!(report.chain.len(), 2);

    // Rotate identity key
    rotate_identity(&repo_path, "chain-id", "chain-id-rot1", passphrase, &kc);

    // Verify the first link still works with historical key
    let old_pk = resolve_identity_public_key_at_sequence(&repo_path, &identity_did, 0);
    verify_at_time(&att1, &ed(&old_pk), att1.timestamp.unwrap())
        .await
        .expect("First chain link should still verify with historical key");
}

/// Device authorization lifecycle: create -> verify valid -> mark revoked -> verify revoked.
#[tokio::test(flavor = "multi_thread")]
async fn test_verify_device_authorization_lifecycle() {
    let kc = IsolatedKeychainHandle::new();
    let (_dir, _repo) = auths_test_utils::git::init_test_repo();
    let repo_path = _dir.path().to_path_buf();
    let passphrase = "Test-P@ss12345";

    // Init identity
    let (identity_did, identity_alias) = init_identity(&repo_path, "authz-id", passphrase, &kc);
    let identity_pk = resolve_identity_public_key(&repo_path, &identity_did);

    // Create device and attestation
    let (device_did, device_pk) =
        generate_device_keypair(&identity_did, "authz-device", passphrase, &kc);
    let attestation = create_test_attestation(
        "test-repo",
        &identity_did,
        &identity_alias,
        &device_did,
        &device_pk,
        Some("authz-device"),
        passphrase,
        &kc,
    );

    // Verify device is authorized
    let report = verify_device_authorization(
        &identity_did,
        &device_did,
        std::slice::from_ref(&attestation),
        &ed(&identity_pk),
    )
    .await
    .expect("verify_device_authorization failed");
    assert!(report.is_valid(), "Device should be authorized");

    // Create a "revoked" version of the attestation
    let mut revoked_att = attestation;
    revoked_att.revoked_at = Some(Utc::now());

    let report = verify_device_authorization(
        &identity_did,
        &device_did,
        &[revoked_att],
        &ed(&identity_pk),
    )
    .await
    .expect("verify_device_authorization failed");
    assert!(
        !report.is_valid(),
        "Revoked device should not be authorized"
    );
    match report.status {
        VerificationStatus::Revoked { .. } => {}
        _ => panic!("Expected Revoked status, got {:?}", report.status),
    }
}

/// Multiple rotations: verify that the original attestation remains verifiable
/// through the entire key history.
#[tokio::test(flavor = "multi_thread")]
async fn test_multiple_rotations_maintain_verification() {
    let kc = IsolatedKeychainHandle::new();
    let (_dir, _repo) = auths_test_utils::git::init_test_repo();
    let repo_path = _dir.path().to_path_buf();
    let passphrase = "Test-P@ss12345";

    // Init identity
    let (identity_did, _identity_alias) = init_identity(&repo_path, "multi-rot", passphrase, &kc);
    let original_pk = resolve_identity_public_key(&repo_path, &identity_did);

    // Create attestation with initial key
    let (device_did, device_pk) =
        generate_device_keypair(&identity_did, "multi-rot-device", passphrase, &kc);
    let original_attestation = create_test_attestation(
        "test-repo",
        &identity_did,
        "multi-rot",
        &device_did,
        &device_pk,
        Some("multi-rot-device"),
        passphrase,
        &kc,
    );

    // Verify initial attestation
    verify_with_keys(&original_attestation, &ed(&original_pk))
        .await
        .expect("Original attestation should verify");

    // Rotate 3 times: multi-rot -> multi-rot2 -> multi-rot3 -> multi-rot4
    rotate_identity(&repo_path, "multi-rot", "multi-rot2", passphrase, &kc);
    rotate_identity(&repo_path, "multi-rot2", "multi-rot3", passphrase, &kc);
    rotate_identity(&repo_path, "multi-rot3", "multi-rot4", passphrase, &kc);

    // Verify original attestation still works with historical key (sequence 0)
    let historical_pk = resolve_identity_public_key_at_sequence(&repo_path, &identity_did, 0);
    assert_eq!(historical_pk, original_pk);
    verify_at_time(
        &original_attestation,
        &ed(&historical_pk),
        original_attestation.timestamp.unwrap(),
    )
    .await
    .expect("Original attestation should verify with historical key after 3 rotations");

    // Create new attestation with final rotated key
    let current_pk = resolve_identity_public_key(&repo_path, &identity_did);
    assert_ne!(
        current_pk, original_pk,
        "Key should have changed after rotations"
    );

    let (device_did2, device_pk2) =
        generate_device_keypair(&identity_did, "multi-rot-device2", passphrase, &kc);
    let new_attestation = create_test_attestation(
        "test-repo",
        &identity_did,
        "multi-rot4",
        &device_did2,
        &device_pk2,
        Some("multi-rot-device2"),
        passphrase,
        &kc,
    );

    // Verify new attestation with current key
    verify_with_keys(&new_attestation, &ed(&current_pk))
        .await
        .expect("New attestation should verify with current key");
}

/// Inception creates exactly one KEL event with the correct prefix.
#[test]
fn test_init_creates_keri_kel() {
    let kc = IsolatedKeychainHandle::new();
    let (_dir, _repo) = auths_test_utils::git::init_test_repo();
    let repo_path = _dir.path().to_path_buf();
    let passphrase = "Test-P@ss12345";

    let (identity_did, _alias) = init_identity(&repo_path, "kel-test", passphrase, &kc);

    // Extract prefix from DID
    let prefix = identity_did
        .strip_prefix("did:keri:")
        .expect("Should be a did:keri");

    // Read KEL from Git storage
    let repo = Repository::open(&repo_path).expect("Failed to open repo");
    let kel = GitKel::new(&repo, prefix);
    let events = kel.get_events().expect("Failed to read KEL events");

    // Assert exactly 1 event (inception)
    assert_eq!(events.len(), 1, "KEL should have exactly 1 inception event");
    assert!(
        matches!(events[0], Event::Icp(_)),
        "First event should be inception"
    );

    // Validate the KEL
    let state = validate_kel(&events).expect("KEL validation failed");
    assert_eq!(state.sequence, 0, "Inception should be sequence 0");
}

/// Rotation appends to the KEL with correct sequence numbers.
#[test]
fn test_rotation_appends_to_kel() {
    let kc = IsolatedKeychainHandle::new();
    let (_dir, _repo) = auths_test_utils::git::init_test_repo();
    let repo_path = _dir.path().to_path_buf();
    let passphrase = "Test-P@ss12345";

    let (identity_did, _alias) = init_identity(&repo_path, "kel-rot", passphrase, &kc);
    let prefix = identity_did
        .strip_prefix("did:keri:")
        .expect("Should be a did:keri");
    let repo = Repository::open(&repo_path).expect("Failed to open repo");

    // After init: 1 event
    let kel = GitKel::new(&repo, prefix);
    let events = kel.get_events().expect("Failed to read KEL");
    assert_eq!(events.len(), 1);

    // Rotate once
    rotate_identity(&repo_path, "kel-rot", "kel-rot2", passphrase, &kc);

    // Reopen to see updates
    let repo = Repository::open(&repo_path).expect("Failed to reopen repo");
    let kel = GitKel::new(&repo, prefix);
    let events = kel.get_events().expect("Failed to read KEL after rotation");
    assert_eq!(events.len(), 2, "KEL should have 2 events after 1 rotation");
    assert!(matches!(events[0], Event::Icp(_)));
    assert!(matches!(events[1], Event::Rot(_)));

    let state = validate_kel(&events).expect("KEL validation failed");
    assert_eq!(state.sequence, 1);

    // Rotate again
    rotate_identity(&repo_path, "kel-rot2", "kel-rot3", passphrase, &kc);

    let repo = Repository::open(&repo_path).expect("Failed to reopen repo");
    let kel = GitKel::new(&repo, prefix);
    let events = kel
        .get_events()
        .expect("Failed to read KEL after 2nd rotation");
    assert_eq!(
        events.len(),
        3,
        "KEL should have 3 events after 2 rotations"
    );

    // Validate sequence numbers: 0, 1, 2
    let state = validate_kel(&events).expect("KEL validation failed");
    assert_eq!(state.sequence, 2);

    for (i, event) in events.iter().enumerate() {
        assert_eq!(
            event.sequence().value(),
            i as u128,
            "Event {} should have sequence {}",
            i,
            i
        );
    }
}