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
//! KERI identity initialization wrapper.
//!
//! This module provides a high-level wrapper around the KERI inception
//! functionality, handling key storage and identity registration.

use std::sync::Arc;

use crate::keri::inception::create_keri_identity_with_curve;
use git2::Repository;
use std::path::Path;

use crate::error::InitError;

use crate::keri::{
    CesrKey, Event, IcpEvent, KeriSequence, Prefix, Said, Threshold, VersionString,
    finalize_icp_event, serialize_for_signing,
};
use crate::storage::identity::IdentityStorage;
use crate::storage::registry::RegistryBackend;
use crate::witness_config::WitnessConfig;

use auths_core::{
    crypto::said::compute_next_commitment,
    crypto::signer::encrypt_keypair,
    signing::PassphraseProvider,
    storage::keychain::{IdentityDID, KeyAlias, KeyRole, KeyStorage},
};

/// Initializes a new KERI identity and stores the keypairs with committed rotation support.
///
/// Args:
/// * `repo_path` - Path to the Git repository.
/// * `local_key_alias` - Alias for storing the key in the keychain.
/// * `metadata` - Optional metadata to associate with the identity.
/// * `passphrase_provider` - Provider for key encryption passphrase.
/// * `identity_storage` - Storage backend for persisting the identity.
/// * `keychain` - Key storage backend.
///
/// Usage:
/// ```ignore
/// let (did, alias) = initialize_keri_identity(&path, "my-key", None, &provider, &storage, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn initialize_keri_identity(
    repo_path: &Path,
    local_key_alias: &KeyAlias,
    metadata: Option<serde_json::Value>,
    passphrase_provider: &dyn PassphraseProvider,
    identity_storage: &dyn IdentityStorage,
    keychain: &(dyn KeyStorage + Send + Sync),
    now: chrono::DateTime<chrono::Utc>,
    curve: auths_crypto::CurveType,
) -> Result<(IdentityDID, KeyAlias), InitError> {
    let repo = Repository::open(repo_path)?;
    let result = create_keri_identity_with_curve(&repo, None, now, curve)
        .map_err(|e| InitError::Keri(e.to_string()))?;
    #[allow(clippy::disallowed_methods)]
    // INVARIANT: create_keri_identity returns a valid did:keri: DID
    let controller_did = IdentityDID::new_unchecked(result.did());

    let is_hardware_backend = keychain.is_hardware_backend();

    if is_hardware_backend {
        // Hardware backends generate keys internally — no passphrase needed,
        // Touch ID / HSM PIN replaces the passphrase
        keychain.store_key(
            local_key_alias,
            &controller_did,
            KeyRole::Primary,
            &[], // ignored by hardware backends
        )?;
        let next_alias = KeyAlias::new_unchecked(format!("{}--next-0", local_key_alias));
        keychain.store_key(
            &next_alias,
            &controller_did,
            KeyRole::NextRotation,
            &[], // ignored by hardware backends
        )?;
    } else {
        let passphrase = passphrase_provider
            .get_passphrase(&format!("Enter passphrase for key '{}':", local_key_alias))?;

        // pass the curve-tagged PKCS8 blob through unchanged. The old
        // extract-seed + encode_seed_as_pkcs8 pattern silently wrapped P-256
        // scalars in an Ed25519 OID.
        let encrypted_current =
            encrypt_keypair(result.current_keypair_pkcs8.as_ref(), &passphrase)?;
        let encrypted_next = encrypt_keypair(result.next_keypair_pkcs8.as_ref(), &passphrase)?;

        keychain.store_key(
            local_key_alias,
            &controller_did,
            KeyRole::Primary,
            &encrypted_current,
        )?;
        let next_alias = KeyAlias::new_unchecked(format!("{}--next-0", local_key_alias));
        keychain.store_key(
            &next_alias,
            &controller_did,
            KeyRole::NextRotation,
            &encrypted_next,
        )?;
    }

    identity_storage.create_identity(controller_did.as_str(), metadata)?;

    Ok((controller_did, local_key_alias.clone()))
}

/// Initializes a new KERI identity using the packed registry backend.
///
/// Creates a KERI inception event, appends it to the provided backend, and
/// stores the encrypted keypairs in the keychain.
///
/// Args:
/// * `backend` - The registry backend to store the KERI inception event.
/// * `local_key_alias` - Alias for storing the key in the keychain.
/// * `passphrase_provider` - Provider for key encryption passphrase.
/// * `keychain` - Key storage backend.
/// * `witness_config` - Optional witness configuration.
///
/// Usage:
/// ```ignore
/// let (did, alias) = initialize_registry_identity(Arc::new(my_backend), "my-key", &provider, &keychain, None)?;
/// ```
pub fn initialize_registry_identity(
    backend: Arc<dyn RegistryBackend + Send + Sync>,
    local_key_alias: &KeyAlias,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
    witness_config: Option<&WitnessConfig>,
    curve: auths_crypto::CurveType,
) -> Result<(IdentityDID, KeyAlias), InitError> {
    backend
        .init_if_needed()
        .map_err(|e| InitError::Registry(e.to_string()))?;

    if keychain.is_hardware_backend() {
        return initialize_hardware_registry_identity(
            backend,
            local_key_alias,
            passphrase_provider,
            keychain,
            witness_config,
            curve,
        );
    }

    let current = crate::keri::inception::generate_keypair_for_init(curve)
        .map_err(|e| InitError::Crypto(e.to_string()))?;
    let next = crate::keri::inception::generate_keypair_for_init(curve)
        .map_err(|e| InitError::Crypto(e.to_string()))?;

    let current_pub_encoded = current.cesr_encoded.clone();
    let next_commitment = compute_next_commitment(&next.verkey());

    let (bt, b) = match witness_config {
        Some(cfg) if cfg.is_enabled() => (
            Threshold::Simple(cfg.threshold as u64),
            cfg.aids().cloned().collect(),
        ),
        _ => (Threshold::Simple(0), vec![]),
    };

    let icp = IcpEvent {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: Prefix::default(),
        s: KeriSequence::new(0),
        kt: Threshold::Simple(1),
        k: vec![CesrKey::new_unchecked(current_pub_encoded)],
        nt: Threshold::Simple(1),
        n: vec![next_commitment],
        bt,
        b,
        c: vec![],
        a: vec![],
    };

    let finalized = finalize_icp_event(icp).map_err(|e| InitError::Keri(e.to_string()))?;
    let prefix = finalized.i.clone();

    let canonical = serialize_for_signing(&Event::Icp(finalized.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let sig_bytes =
        crate::keri::inception::sign_with_pkcs8_for_init(curve, &current.pkcs8, &canonical)
            .map_err(|e| InitError::Crypto(e.to_string()))?;
    let attachment = auths_keri::serialize_attachment(&[auths_keri::IndexedSignature {
        index: 0,
        prior_index: None,
        sig: sig_bytes,
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    backend
        .append_signed_event(&prefix, &Event::Icp(finalized), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: prefix is from finalize_icp_event, guaranteed valid did:keri format
    let controller_did = IdentityDID::new_unchecked(format!("did:keri:{}", prefix));

    let passphrase = passphrase_provider
        .get_passphrase(&format!("Enter passphrase for key '{}':", local_key_alias))?;

    let encrypted_current = encrypt_keypair(current.pkcs8.as_ref(), &passphrase)?;
    let encrypted_next = encrypt_keypair(next.pkcs8.as_ref(), &passphrase)?;

    keychain.store_key(
        local_key_alias,
        &controller_did,
        KeyRole::Primary,
        &encrypted_current,
    )?;
    let next_alias = KeyAlias::new_unchecked(format!("{}--next-0", local_key_alias));
    keychain.store_key(
        &next_alias,
        &controller_did,
        KeyRole::NextRotation,
        &encrypted_next,
    )?;

    Ok((controller_did, local_key_alias.clone()))
}

/// Initializes a KERI identity whose keys live in a hardware backend (Secure Enclave).
///
/// Hardware keys cannot be generated in software and imported — the backend
/// generates them internally. The inception therefore runs in the opposite
/// order from the software path: generate the hardware keys first, read their
/// public halves back, incept the KEL with the *hardware* current key, sign
/// the inception event through the hardware, and finally rebind the stored
/// keys to the derived identity prefix.
///
/// Args:
/// * `backend` — The registry backend to store the KERI inception event.
/// * `local_key_alias` — Alias for the primary signing key.
/// * `passphrase_provider` — Unused by hardware signing, threaded for the trait API.
/// * `keychain` — Hardware key storage backend.
/// * `witness_config` — Optional witness configuration.
/// * `curve` — Must be P-256 (the only curve hardware backends support).
///
/// Usage:
/// ```ignore
/// let (did, alias) = initialize_hardware_registry_identity(
///     backend, &alias, &provider, keychain, None, CurveType::P256,
/// )?;
/// ```
fn initialize_hardware_registry_identity(
    backend: Arc<dyn RegistryBackend + Send + Sync>,
    local_key_alias: &KeyAlias,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
    witness_config: Option<&WitnessConfig>,
    curve: auths_crypto::CurveType,
) -> Result<(IdentityDID, KeyAlias), InitError> {
    if curve != auths_crypto::CurveType::P256 {
        return Err(InitError::Crypto(format!(
            "hardware-backed inception supports P-256 only, got {curve:?}"
        )));
    }

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: rebound to the real did:keri prefix before this function returns
    let placeholder = IdentityDID::new_unchecked("did:keri:pending");
    let next_alias = KeyAlias::new_unchecked(format!("{}--next-0", local_key_alias));

    keychain.store_key(local_key_alias, &placeholder, KeyRole::Primary, &[])?;
    keychain.store_key(&next_alias, &placeholder, KeyRole::NextRotation, &[])?;

    let _ = passphrase_provider;
    let current_pub = keychain.export_public_key(local_key_alias)?;
    let next_pub = keychain.export_public_key(&next_alias)?;

    let current_norm = auths_crypto::normalize_verkey(&current_pub, curve)
        .map_err(|e| InitError::Crypto(format!("hardware current key: {e}")))?;
    let next_norm = auths_crypto::normalize_verkey(&next_pub, curve)
        .map_err(|e| InitError::Crypto(format!("hardware next key: {e}")))?;
    let current_verkey = auths_keri::KeriPublicKey::from_verkey_bytes(&current_norm, curve)
        .map_err(|e| InitError::Crypto(format!("hardware current key: {e}")))?;
    let next_verkey = auths_keri::KeriPublicKey::from_verkey_bytes(&next_norm, curve)
        .map_err(|e| InitError::Crypto(format!("hardware next key: {e}")))?;
    let current_cesr = current_verkey
        .to_qb64()
        .map_err(|e| InitError::Crypto(e.to_string()))?;

    let (bt, b) = match witness_config {
        Some(cfg) if cfg.is_enabled() => (
            Threshold::Simple(cfg.threshold as u64),
            cfg.aids().cloned().collect(),
        ),
        _ => (Threshold::Simple(0), vec![]),
    };

    let icp = IcpEvent {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: Prefix::default(),
        s: KeriSequence::new(0),
        kt: Threshold::Simple(1),
        k: vec![CesrKey::new_unchecked(current_cesr)],
        nt: Threshold::Simple(1),
        n: vec![compute_next_commitment(&next_verkey)],
        bt,
        b,
        c: vec![],
        a: vec![],
    };

    let finalized = finalize_icp_event(icp).map_err(|e| InitError::Keri(e.to_string()))?;
    let prefix = finalized.i.clone();

    let canonical = serialize_for_signing(&Event::Icp(finalized.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let sig_bytes = keychain.sign_raw(local_key_alias, &canonical)?;
    let attachment = auths_keri::serialize_attachment(&[auths_keri::IndexedSignature {
        index: 0,
        prior_index: None,
        sig: sig_bytes,
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    backend
        .append_signed_event(&prefix, &Event::Icp(finalized), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: prefix is from finalize_icp_event, guaranteed valid did:keri format
    let controller_did = IdentityDID::new_unchecked(format!("did:keri:{}", prefix));

    keychain.rebind_identity(local_key_alias, &controller_did)?;
    keychain.rebind_identity(&next_alias, &controller_did)?;

    Ok((controller_did, local_key_alias.clone()))
}

/// Initialize a multi-key KERI identity.
///
/// Stores current keys at `{alias}--{idx}` and next keys at
/// `{alias}--next-0-{idx}` for `idx` in `0..curves.len()`.
///
/// Args:
/// * `backend` — The registry backend to store the KERI inception event.
/// * `local_key_alias` — Base alias for storing keys in the keychain.
/// * `passphrase_provider` — Provider for key encryption passphrase.
/// * `keychain` — Key storage backend.
/// * `witness_config` — Optional witness configuration.
/// * `curves` — Non-empty slice of curve choices, one per device slot.
/// * `kt` — Signing threshold. Validated against `curves.len()`.
/// * `nt` — Rotation threshold. Validated against `curves.len()`.
// INVARIANT: all eight parameters are load-bearing inputs for multi-device
// inception — grouping them into a config struct would trade argument count
// for an additional type that adds no safety (every field would still be
// required). Accept the clippy limit here.
#[allow(clippy::too_many_arguments)]
pub fn initialize_registry_identity_multi(
    backend: Arc<dyn RegistryBackend + Send + Sync>,
    local_key_alias: &KeyAlias,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
    witness_config: Option<&WitnessConfig>,
    curves: &[auths_crypto::CurveType],
    kt: Threshold,
    nt: Threshold,
) -> Result<(IdentityDID, KeyAlias), InitError> {
    if curves.is_empty() {
        return Err(InitError::Crypto(
            "initialize_registry_identity_multi requires at least one curve".to_string(),
        ));
    }
    crate::keri::inception::validate_threshold_for_key_count(&kt, curves.len())
        .map_err(|e| InitError::Crypto(e.to_string()))?;
    crate::keri::inception::validate_threshold_for_key_count(&nt, curves.len())
        .map_err(|e| InitError::Crypto(e.to_string()))?;

    backend
        .init_if_needed()
        .map_err(|e| InitError::Registry(e.to_string()))?;

    let current_kps = crate::keri::inception::generate_keypairs_for_init(curves)
        .map_err(|e| InitError::Crypto(e.to_string()))?;
    let next_kps = crate::keri::inception::generate_keypairs_for_init(curves)
        .map_err(|e| InitError::Crypto(e.to_string()))?;

    let k: Vec<CesrKey> = current_kps
        .iter()
        .map(|kp| CesrKey::new_unchecked(kp.cesr_encoded.clone()))
        .collect();
    let n: Vec<Said> = next_kps
        .iter()
        .map(|kp| compute_next_commitment(&kp.verkey()))
        .collect();

    let (bt, b) = match witness_config {
        Some(cfg) if cfg.is_enabled() => (
            Threshold::Simple(cfg.threshold as u64),
            cfg.aids().cloned().collect(),
        ),
        _ => (Threshold::Simple(0), vec![]),
    };

    let icp = IcpEvent {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: Prefix::default(),
        s: KeriSequence::new(0),
        kt,
        k,
        nt,
        n,
        bt,
        b,
        c: vec![],
        a: vec![],
    };

    let finalized = finalize_icp_event(icp).map_err(|e| InitError::Keri(e.to_string()))?;
    let prefix = finalized.i.clone();

    // Sign with index 0's current key — single-slot signature. The
    // aggregation module adds additional sigs when `kt` is multi-slot.
    let canonical = serialize_for_signing(&Event::Icp(finalized.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let sig_bytes = crate::keri::inception::sign_with_pkcs8_for_init(
        curves[0],
        &current_kps[0].pkcs8,
        &canonical,
    )
    .map_err(|e| InitError::Crypto(e.to_string()))?;
    let attachment = auths_keri::serialize_attachment(&[auths_keri::IndexedSignature {
        index: 0,
        prior_index: None,
        sig: sig_bytes,
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    backend
        .append_signed_event(&prefix, &Event::Icp(finalized), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: prefix is from finalize_icp_event, guaranteed valid did:keri format.
    let controller_did = IdentityDID::new_unchecked(format!("did:keri:{}", prefix));

    let is_hardware_backend = keychain.is_hardware_backend();

    // Store each current + next keypair under {alias}--{idx} / {alias}--next-0-{idx}.
    for (idx, (cur, nxt)) in current_kps.iter().zip(next_kps.iter()).enumerate() {
        let cur_alias = KeyAlias::new_unchecked(format!("{}--{}", local_key_alias, idx));
        let nxt_alias = KeyAlias::new_unchecked(format!("{}--next-0-{}", local_key_alias, idx));

        if is_hardware_backend {
            keychain.store_key(&cur_alias, &controller_did, KeyRole::Primary, &[])?;
            keychain.store_key(&nxt_alias, &controller_did, KeyRole::NextRotation, &[])?;
        } else {
            let passphrase = passphrase_provider
                .get_passphrase(&format!("Enter passphrase for key '{}':", local_key_alias))?;
            let encrypted_current = encrypt_keypair(cur.pkcs8.as_ref(), &passphrase)?;
            let encrypted_next = encrypt_keypair(nxt.pkcs8.as_ref(), &passphrase)?;
            keychain.store_key(
                &cur_alias,
                &controller_did,
                KeyRole::Primary,
                &encrypted_current,
            )?;
            keychain.store_key(
                &nxt_alias,
                &controller_did,
                KeyRole::NextRotation,
                &encrypted_next,
            )?;
        }
    }

    Ok((controller_did, local_key_alias.clone()))
}