auths-core 0.1.1

Core cryptography and keychain integration 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
//! Trust resolution logic for verifying identity root keys.
//!
//! This module provides the core trust decision engine that determines
//! whether to trust a presented identity based on the configured policy.

use auths_verifier::PublicKeyHex;

use super::continuity::{KelContinuityChecker, RotationProof};
use super::pinned::{PinnedIdentity, PinnedIdentityStore, TrustLevel};
use super::policy::TrustPolicy;
use crate::error::TrustError;
use chrono::{DateTime, Utc};

/// What the trust engine decided.
#[derive(Debug)]
pub enum TrustDecision {
    /// Key matches existing pin. Proceed.
    Trusted {
        /// The pinned identity.
        pin: PinnedIdentity,
    },

    /// No pin exists. Caller must decide based on policy.
    FirstUse {
        /// The DID encountered for the first time.
        did: String,
        /// The presented public key.
        presented_pk: Vec<u8>,
    },

    /// Key differs from pin, but a valid forward-chain rotation connects them.
    ///
    /// The continuity checker has verified unbroken hash linkage from
    /// pinned tip to current tip, and the resulting key matches presented_pk.
    RotationVerified {
        /// The previous pinned identity.
        old_pin: PinnedIdentity,
        /// Proof of key rotation.
        proof: RotationProof,
    },

    /// Key differs from pin with no valid rotation chain.
    ///
    /// Either no KEL was available, the pinned tip is not an ancestor of the
    /// current tip, or the chain leads to a different key.
    Conflict {
        /// The new pinned identity.
        pin: PinnedIdentity,
        /// The presented public key.
        presented_pk: Vec<u8>,
    },
}

/// Check trust for a presented identity.
///
/// The `continuity_checker` parameter is optional. If `None`, any key mismatch
/// against an existing pin is treated as a hard conflict (no rotation can be
/// verified without KEL access). Pass `Some(&checker)` when the caller has
/// repository access and can verify rotation chains.
///
/// # Arguments
///
/// * `store` - The pin store to look up existing pins
/// * `did` - The DID of the identity being verified
/// * `presented_pk` - The raw public key bytes presented for verification
/// * `continuity_checker` - Optional KEL continuity checker for rotation verification
///
/// # Returns
///
/// A [`TrustDecision`] indicating what action to take.
pub fn check_trust(
    store: &PinnedIdentityStore,
    did: &str,
    presented_pk: &[u8],
    continuity_checker: Option<&dyn KelContinuityChecker>,
) -> Result<TrustDecision, TrustError> {
    let pin = store.lookup(did)?;

    let Some(pin) = pin else {
        return Ok(TrustDecision::FirstUse {
            did: did.to_string(),
            presented_pk: presented_pk.to_vec(),
        });
    };

    // Compare on decoded bytes, not hex strings
    if pin.key_matches(presented_pk)? {
        return Ok(TrustDecision::Trusted { pin });
    }

    // Key differs — attempt rotation continuity check if we have a checker and a tip
    if let (Some(checker), Some(pinned_tip)) = (continuity_checker, &pin.kel_tip_said) {
        match checker.verify_rotation_continuity(did, pinned_tip, presented_pk)? {
            Some(proof) => {
                return Ok(TrustDecision::RotationVerified {
                    old_pin: pin,
                    proof,
                });
            }
            None => {
                // Checker ran but couldn't prove continuity — fall through to conflict
            }
        }
    }

    Ok(TrustDecision::Conflict {
        pin,
        presented_pk: presented_pk.to_vec(),
    })
}

/// Apply the trust policy to a [`TrustDecision`] to get a final resolved key.
///
/// Resolution order for `Explicit` policy:
/// 1. Pinned identity store (only existing pins)
/// 2. Reject unknown identities
///
/// Resolution order for `Tofu` policy:
/// 1. Pinned identity store
/// 2. Interactive prompt → pin on accept
///
/// # Arguments
///
/// * `decision` - The trust decision from [`check_trust`]
/// * `policy` - The trust policy to apply
/// * `store` - The pin store for saving new pins
/// * `interactive_prompt` - Optional function to prompt user for TOFU acceptance
///
/// # Returns
///
/// `Ok(public_key_bytes)` if trusted, `Err` if rejected.
pub fn resolve_trust(
    now: DateTime<Utc>,
    decision: TrustDecision,
    policy: &TrustPolicy,
    store: &PinnedIdentityStore,
    interactive_prompt: Option<&dyn Fn(&str) -> bool>,
) -> Result<Vec<u8>, TrustError> {
    match decision {
        TrustDecision::Trusted { pin } => pin.public_key_bytes(),

        TrustDecision::FirstUse { did, presented_pk } => match policy {
            TrustPolicy::Tofu => {
                let prompt = interactive_prompt.ok_or_else(|| {
                    TrustError::PolicyRejected(
                        "TOFU requires interactive prompt but none available. \
                         Use --trust explicit with a roots file for non-interactive use."
                            .into(),
                    )
                })?;
                let pk_hex = hex::encode(&presented_pk);
                let msg = format!(
                    "Unknown identity: {}\n  Key: {}...\n  Trust this identity?",
                    did,
                    &pk_hex[..16.min(pk_hex.len())]
                );
                if prompt(&msg) {
                    let curve = auths_crypto::did_key_decode(&did)
                        .map(|d| d.curve())
                        .unwrap_or_default();
                    let pin = PinnedIdentity {
                        did,
                        #[allow(clippy::disallowed_methods)] // INVARIANT: hex::encode on line 151 guarantees valid hex output
                        public_key_hex: PublicKeyHex::new_unchecked(pk_hex),
                        curve,
                        kel_tip_said: None,
                        kel_sequence: None,
                        first_seen: now,
                        origin: "tofu".into(),
                        trust_level: TrustLevel::Tofu,
                    };
                    store.pin(pin)?;
                    Ok(presented_pk)
                } else {
                    Err(TrustError::PolicyRejected(
                        "Identity rejected by user.".into(),
                    ))
                }
            }
            TrustPolicy::Explicit => {
                let pk_hex = hex::encode(&presented_pk);
                Err(TrustError::PolicyRejected(format!(
                    "Unknown identity '{}' and trust policy is 'explicit'.\n\
                     Options:\n  \
                     1. Add to .auths/roots.json in the repository\n  \
                     2. Pin manually: auths trust pin {} --key {}\n  \
                     3. Provide --signer-key {} to bypass trust resolution",
                    did, did, pk_hex, pk_hex
                )))
            }
        },

        TrustDecision::RotationVerified { old_pin, proof } => {
            let updated = PinnedIdentity {
                did: old_pin.did,
                #[allow(clippy::disallowed_methods)] // INVARIANT: hex::encode always produces valid lowercase hex
                public_key_hex: PublicKeyHex::new_unchecked(hex::encode(&proof.new_public_key)),
                curve: proof.new_curve,
                kel_tip_said: Some(proof.new_kel_tip),
                kel_sequence: Some(proof.new_sequence),
                first_seen: old_pin.first_seen,
                origin: old_pin.origin,
                trust_level: old_pin.trust_level,
            };
            store.update(updated)?;
            Ok(proof.new_public_key)
        }

        TrustDecision::Conflict { pin, presented_pk } => {
            let pinned_hex = pin.public_key_hex.as_str();
            let presented_hex = hex::encode(&presented_pk);
            Err(TrustError::PolicyRejected(format!(
                "TRUST CONFLICT for {}\n  \
                 Pinned key:    {}...\n  \
                 Presented key: {}...\n  \
                 No valid rotation chain connects these keys.\n  \
                 This could indicate an attack or a KEL that was not available.\n\n  \
                 If you trust this new key, remove the old pin first:\n    \
                 auths trust remove {}",
                pin.did,
                &pinned_hex[..16.min(pinned_hex.len())],
                &presented_hex[..16.min(presented_hex.len())],
                pin.did
            )))
        }
    }
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;

    fn make_test_pin() -> PinnedIdentity {
        PinnedIdentity {
            did: "did:keri:ETest123".to_string(),
            public_key_hex: PublicKeyHex::new_unchecked(
                "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
            ),
            curve: auths_crypto::CurveType::Ed25519,
            kel_tip_said: Some("ETip".to_string()),
            kel_sequence: Some(0),
            first_seen: Utc::now(),
            origin: "test".to_string(),
            trust_level: TrustLevel::Tofu,
        }
    }

    fn temp_store() -> (tempfile::TempDir, PinnedIdentityStore) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known_identities.json");
        let store = PinnedIdentityStore::new(path);
        (dir, store)
    }

    #[test]
    fn test_check_trust_first_use() {
        let (_dir, store) = temp_store();
        let pk: Vec<u8> = (1..=32).collect();

        let decision = check_trust(&store, "did:keri:ENew", &pk, None).unwrap();
        assert!(matches!(decision, TrustDecision::FirstUse { .. }));
    }

    #[test]
    fn test_check_trust_trusted() {
        let (_dir, store) = temp_store();
        let pin = make_test_pin();
        store.pin(pin.clone()).unwrap();

        let pk: Vec<u8> = (1..=32).collect();
        let decision = check_trust(&store, &pin.did, &pk, None).unwrap();
        assert!(matches!(decision, TrustDecision::Trusted { .. }));
    }

    #[test]
    fn test_check_trust_conflict() {
        let (_dir, store) = temp_store();
        let pin = make_test_pin();
        store.pin(pin.clone()).unwrap();

        let wrong_pk: Vec<u8> = vec![0xFF; 32];
        let decision = check_trust(&store, &pin.did, &wrong_pk, None).unwrap();
        assert!(matches!(decision, TrustDecision::Conflict { .. }));
    }

    #[test]
    fn test_resolve_trust_trusted() {
        let (_dir, store) = temp_store();
        let pin = make_test_pin();
        store.pin(pin.clone()).unwrap();

        let decision = TrustDecision::Trusted { pin };
        let result = resolve_trust(Utc::now(), decision, &TrustPolicy::Tofu, &store, None).unwrap();
        assert_eq!(result.len(), 32);
    }

    #[test]
    fn test_resolve_trust_first_use_tofu_accepted() {
        let (_dir, store) = temp_store();
        let pk: Vec<u8> = (1..=32).collect();

        let decision = TrustDecision::FirstUse {
            did: "did:keri:ENew".to_string(),
            presented_pk: pk.clone(),
        };

        let accept_all = |_: &str| true;
        let result = resolve_trust(
            Utc::now(),
            decision,
            &TrustPolicy::Tofu,
            &store,
            Some(&accept_all),
        )
        .unwrap();

        assert_eq!(result, pk);
        // Should be pinned now
        assert!(store.lookup("did:keri:ENew").unwrap().is_some());
    }

    #[test]
    fn test_resolve_trust_first_use_tofu_rejected() {
        let (_dir, store) = temp_store();
        let pk: Vec<u8> = (1..=32).collect();

        let decision = TrustDecision::FirstUse {
            did: "did:keri:ENew".to_string(),
            presented_pk: pk,
        };

        let reject_all = |_: &str| false;
        let result = resolve_trust(
            Utc::now(),
            decision,
            &TrustPolicy::Tofu,
            &store,
            Some(&reject_all),
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("rejected"));
    }

    #[test]
    fn test_resolve_trust_first_use_explicit_fails() {
        let (_dir, store) = temp_store();
        let pk: Vec<u8> = (1..=32).collect();

        let decision = TrustDecision::FirstUse {
            did: "did:keri:ENew".to_string(),
            presented_pk: pk,
        };

        let result = resolve_trust(Utc::now(), decision, &TrustPolicy::Explicit, &store, None);

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("explicit"));
        assert!(err.contains("roots.json"));
    }

    #[test]
    fn test_resolve_trust_conflict_fails() {
        let (_dir, store) = temp_store();
        let pin = make_test_pin();
        let wrong_pk: Vec<u8> = vec![0xFF; 32];

        let decision = TrustDecision::Conflict {
            pin,
            presented_pk: wrong_pk,
        };

        let result = resolve_trust(Utc::now(), decision, &TrustPolicy::Tofu, &store, None);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("TRUST CONFLICT"));
    }

    #[test]
    fn test_resolve_trust_rotation_verified() {
        let (_dir, store) = temp_store();
        let mut pin = make_test_pin();
        pin.kel_sequence = Some(0);
        store.pin(pin.clone()).unwrap();

        let new_pk: Vec<u8> = vec![0xAA; 32];
        let proof = RotationProof {
            new_public_key: new_pk.clone(),
            new_curve: auths_crypto::CurveType::Ed25519,
            new_kel_tip: "ENewTip".to_string(),
            new_sequence: 1,
        };

        let decision = TrustDecision::RotationVerified {
            old_pin: pin.clone(),
            proof,
        };

        let result = resolve_trust(Utc::now(), decision, &TrustPolicy::Tofu, &store, None).unwrap();
        assert_eq!(result, new_pk);

        // Pin should be updated
        let updated = store.lookup(&pin.did).unwrap().unwrap();
        assert_eq!(updated.kel_sequence, Some(1));
        assert_eq!(updated.kel_tip_said, Some("ENewTip".to_string()));
    }
}