acdp-client 0.18.0

Consumer client (RegistryClient, VerifiedContext, CrossRegistryResolver) for the Agent Context Distribution Protocol (ACDP)
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
//! Keyless-signed bodies, consumer side (RFC-ACDP-0021 §8, §11; 0.5.0
//! Draft).
//!
//! [`KeylessPolicy`] says which registries this consumer accepts as
//! attesters (§11). It exists in every build so that
//! [`VerificationPolicy`](crate::VerificationPolicy) has one shape; the
//! default accepts none, and without the `keyless` feature it is not
//! consulted at all: a keyless key id then fails closed in
//! [`VerifiedContext::fetch`](crate::VerifiedContext::fetch) like any key
//! the DID document does not list.
//!
//! With the `keyless` feature, `VerifiedContext` runs §8.1 in place of
//! RFC-ACDP-0001 §5.11 for a keyless key id, in this order (the first
//! failure decides, and its reason token rides on the error, see
//! [`KeylessReason::of`](acdp_types::keyless::KeylessReason::of)):
//!
//! 1. the attestation, fetched from the serving registry by
//!    `key_attestation.ctx_id`, matches `key_attestation.content_hash`,
//!    is signed under its registry's DID, carries a valid receipt and
//!    meets §5.3 (`attestation_invalid`);
//! 2. the attesting registry is accepted (`untrusted_attester`);
//! 3. `agent_id`, `key_id` and `algorithm` match it
//!    (`attestation_mismatch`);
//! 4. the body's receipt verifies, comes from the attester and names the
//!    attested fingerprint (`unplaceable`) — the receipt is required
//!    whatever [`ReceiptPolicy`](crate::ReceiptPolicy) says, because it
//!    is the only time that places a keyless signature;
//! 5. its `created_at` lies in the window (`outside_attestation_window`);
//! 6. the signature verifies under the attested key
//!    (`invalid_signature`);
//! 7. the attestation is not retracted (`attestation_withdrawn`);
//! 8. RFC-ACDP-0014 revocations of the attested fingerprint, gathered by
//!    `agent_id` under [`RevocationPolicy`](crate::RevocationPolicy)
//!    (`revoked`, or pre-compromise);
//! 9. the controller's current DID document lists the identity
//!    (currently authorized), does not (historically authorized), or
//!    cannot be fetched (`controller_unreachable`, transient).
//!
//! The outcome is one of the three existing
//! [`KeyAuthorization`](crate::KeyAuthorization) values or an error.
//!
//! **Known limitation.** Revocation discovery verifies the revocation
//! bodies it finds through RFC-ACDP-0001 §5.11, so a revocation signed
//! with a keyless key is never applied here, even one under an `org_wide`
//! attestation (§9.3 makes those producer-signed). Revocations signed by
//! a DID-document key of the controller, and registry-attested ones,
//! apply as usual.

use acdp_types::trust_list::PinState;
use chrono::{DateTime, Utc};

/// Which registries a consumer accepts as keyless attesters (§11).
///
/// A registry is accepted when its DID is in [`Self::attesters`], or when
/// [`Self::trust_lists`] is set and the keyless-signed body evaluates
/// `trusted` (RFC-ACDP-0020 §6.2) with the attesting registry as its
/// receipting registry. The default accepts none, so every keyless-signed
/// body is refused with `untrusted_attester` (`kl-006` A).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct KeylessPolicy {
    /// Attesting registries' `did:web` DIDs, compared byte for byte.
    pub attesters: Vec<String>,
    /// RFC-ACDP-0020 trust-list acceptance.
    pub trust_lists: Option<KeylessTrust>,
}

impl KeylessPolicy {
    /// Accept the registries `attesters` (their `did:web` DIDs).
    pub fn attesters<I, S>(attesters: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            attesters: attesters.into_iter().map(Into::into).collect(),
            trust_lists: None,
        }
    }

    /// Also accept a registry for a body the trust lists `trust` trust.
    pub fn with_trust_lists(mut self, trust: KeylessTrust) -> Self {
        self.trust_lists = Some(trust);
        self
    }
}

/// The RFC-ACDP-0020 inputs for §11 trust-list acceptance: the pins'
/// §5.4 state at `t` (from [`TrustLists::select`](crate::trust::TrustLists::select))
/// and, when fetched, the attesting registry's advertised profiles (C).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeylessTrust {
    /// The pin states at `t`.
    pub pins: Vec<PinState>,
    /// The evaluation time.
    pub t: DateTime<Utc>,
    /// The attesting registry's capabilities `profiles`, if fetched.
    pub capabilities: Option<Vec<String>>,
}

impl KeylessTrust {
    /// The state of `lists` at `t`.
    pub fn at(
        lists: &crate::trust::TrustLists,
        t: DateTime<Utc>,
        capabilities: Option<Vec<String>>,
    ) -> Self {
        Self {
            pins: lists.select(t),
            t,
            capabilities,
        }
    }
}

#[cfg(feature = "keyless")]
pub(crate) use verify::verify;

#[cfg(feature = "keyless")]
mod verify {
    use super::KeylessPolicy;
    use crate::receipt::{verify_receipt_placed, PlacedReceipt};
    use crate::registry::RegistryClient;
    use crate::verified::{KeyAuthorization, KeyPhases, RevocationPolicy};
    use acdp_did::web::WebResolver;
    use acdp_primitives::error::AcdpError;
    use acdp_types::body::{Body, FullContext};
    use acdp_types::keyless::{
        classify, decide_until_identity, IdentityNow, KeyAttestation, KeyAttestationRef,
        KeylessFacts, KeylessReason, KeylessStatus, ListedIdentities, ReceiptFacts,
    };
    use acdp_types::primitives::CtxId;
    use acdp_types::trust_list::{evaluate, ReceiptInput, TrustOutcome, TrustSubject};
    use acdp_verify::Verifier;
    use std::time::Instant;

    /// A verified attestation (§8.1 step 1).
    struct Attestation {
        metadata: KeyAttestation,
        /// The attesting registry's DID (the attestation's `agent_id`).
        registry: String,
        retracted: bool,
    }

    fn invalid(e: impl std::fmt::Display) -> AcdpError {
        KeylessReason::AttestationInvalid.error(e)
    }

    /// §8.1 step 1. Transient failures propagate unchanged (retry later);
    /// every other failure is `attestation_invalid`.
    async fn attestation(
        client: &RegistryClient,
        resolver: &WebResolver,
        reference: &KeyAttestationRef,
        serving_authority: &str,
        since: Instant,
    ) -> Result<Attestation, AcdpError> {
        // §6.3 step 2: a registry accepts only attestations it minted, so
        // the attestation of a body it serves is its own.
        if reference.ctx_id.authority() != serving_authority {
            return Err(invalid(format!(
                "key_attestation.ctx_id '{}' is not on the serving registry '{serving_authority}'",
                reference.ctx_id
            )));
        }
        let ctx = match client.retrieve(&reference.ctx_id).await {
            Ok(ctx) => ctx,
            Err(e) if e.is_transient() => return Err(e),
            Err(e) => return Err(invalid(format!("fetching the attestation: {e}"))),
        };
        let checked = check_attestation(resolver, &ctx, reference, serving_authority, since).await;
        match checked {
            Ok(metadata) => Ok(Attestation {
                metadata,
                registry: ctx.body.agent_id.as_str().to_owned(),
                retracted: ctx.registry_state.status.is_retracted(),
            }),
            Err(e) if e.is_transient() => Err(e),
            Err(e) => Err(invalid(e)),
        }
    }

    async fn check_attestation(
        resolver: &WebResolver,
        ctx: &FullContext,
        reference: &KeyAttestationRef,
        serving_authority: &str,
        since: Instant,
    ) -> Result<KeyAttestation, AcdpError> {
        acdp_verify::verify_ctx_id_binding(ctx.body.ctx_id.as_str(), reference.ctx_id.as_str())?;
        acdp_verify::verify_context_hash(ctx)?;
        if ctx.body.content_hash != reference.content_hash {
            return Err(AcdpError::HashMismatch {
                stored: reference.content_hash.clone(),
                recomputed: ctx.body.content_hash.clone(),
            });
        }
        acdp_validation::validate_body(&ctx.body)?;
        let metadata = KeyAttestation::from_body(&ctx.body)?;
        let verifier = Verifier::new(resolver).fresh_since(since);
        verifier.verify_body_signature(&ctx.body).await?;
        let receipt = ctx.registry_receipt.as_ref().ok_or_else(|| {
            AcdpError::InvalidReceipt("the attestation carries no receipt".into())
        })?;
        let registry_fp = acdp_crypto::fingerprint::fingerprint_for_key_id_since(
            &ctx.body.signature.key_id,
            &ctx.body.signature.algorithm,
            resolver,
            since,
        )
        .await?;
        verify_receipt_placed(
            receipt,
            &reference.ctx_id,
            &ctx.body,
            &ctx.body.content_hash,
            &registry_fp,
            serving_authority,
            resolver,
            since,
        )
        .await?;
        Ok(metadata)
    }

    /// §11: does the consumer accept `registry` as the attester of `body`?
    fn accepted(
        policy: &KeylessPolicy,
        registry: &str,
        body: &Body,
        placed: Option<&PlacedReceipt>,
    ) -> bool {
        if policy.attesters.iter().any(|a| a == registry) {
            return true;
        }
        let (Some(trust), Some(placed)) = (&policy.trust_lists, placed) else {
            return false;
        };
        if placed.receipt.registry_did != registry {
            return false;
        }
        let ty = serde_json::to_value(&body.context_type)
            .ok()
            .and_then(|v| v.as_str().map(str::to_owned))
            .unwrap_or_default();
        let receipt = ReceiptInput {
            registry_did: placed.receipt.registry_did.clone(),
            registry_key_fingerprint: placed.registry_key_fingerprint.clone(),
        };
        let node = evaluate(
            &TrustSubject::of(body, &ty),
            &trust.pins,
            trust.t,
            Some(&receipt),
            trust.capabilities.as_deref(),
        );
        node.outcome == TrustOutcome::Trusted
    }

    /// §8.1 step 9 against a document fetched for this verification.
    async fn identity_now(
        resolver: &WebResolver,
        attestation: &KeyAttestation,
        since: Instant,
    ) -> IdentityNow {
        let listed = |doc: &acdp_did::DidDocument| {
            ListedIdentities::of(doc)
                .find(&attestation.identity)
                .is_some()
        };
        match resolver
            .resolve_until(&attestation.controller, since, listed)
            .await
        {
            Ok(r) if listed(&r.document) => IdentityNow::Listed,
            // Absence is final only against a fresh document.
            Ok(r) if r.fresh => IdentityNow::NotListed,
            Ok(_) | Err(_) => IdentityNow::Unreachable,
        }
    }

    fn refusal(reason: KeylessReason, body: &Body, att: &KeyAttestation) -> AcdpError {
        let key_id = &body.signature.key_id;
        let detail = match reason {
            KeylessReason::UntrustedAttester => format!(
                "the attesting registry of '{key_id}' is not an accepted attester \
                 (RFC-ACDP-0021 §11; configure VerificationPolicy.keyless)"
            ),
            KeylessReason::AttestationMismatch => format!(
                "agent_id, key_id or algorithm differ from the attestation of '{}'",
                att.key_id
            ),
            KeylessReason::Unplaceable => "no verified receipt from the attesting registry \
                 names the attested key (RFC-ACDP-0021 §8.1 step 4)"
                .to_string(),
            KeylessReason::OutsideAttestationWindow => format!(
                "the receipt places the signature outside [{}, {})",
                acdp_primitives::time::fmt_rfc3339_ms(att.not_before),
                acdp_primitives::time::fmt_rfc3339_ms(att.not_after)
            ),
            KeylessReason::InvalidSignature => {
                format!("the signature does not verify under the key attested for '{key_id}'")
            }
            KeylessReason::AttestationWithdrawn => {
                "the attesting registry retracted the attestation (RFC-ACDP-0021 §9.2)".to_string()
            }
            KeylessReason::ControllerUnreachable => format!(
                "the DID document of '{}' could not be fetched fresh",
                att.controller
            ),
            other => format!("keyless verification refused: {other}"),
        };
        reason.error(detail)
    }

    /// RFC-ACDP-0021 §8.1 for a keyless-signed body whose content hash
    /// the caller has already recomputed.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn verify(
        client: &RegistryClient,
        resolver: &WebResolver,
        ctx: &FullContext,
        expected_ctx_id: &CtxId,
        serving_authority: &str,
        policy: &KeylessPolicy,
        revocations: &RevocationPolicy,
        since: Instant,
    ) -> Result<KeyPhases, AcdpError> {
        let body = &ctx.body;
        let reference = body.key_attestation()?.ok_or_else(|| {
            KeylessReason::AttestationMissing.error(format!(
                "signature.key_id '{}' is a keyless key id but the body has no key_attestation",
                body.signature.key_id
            ))
        })?;

        // Step 1 decides alone: nothing below can be evaluated without it.
        let att = attestation(client, resolver, &reference, serving_authority, since).await?;
        let meta = &att.metadata;

        // Step 4's receipt is verified up front: step 2's trust-list path
        // reads the receipting registry from it. The order of the
        // decisions is still §8.1's (`classify`).
        let placed = match &ctx.registry_receipt {
            None => None,
            Some(value) => Some(
                verify_receipt_placed(
                    value,
                    expected_ctx_id,
                    body,
                    &body.content_hash,
                    &meta.key_fingerprint,
                    serving_authority,
                    resolver,
                    since,
                )
                .await,
            ),
        };
        let placed_ok = placed.as_ref().and_then(|p| p.as_ref().ok());
        let receipt = placed.as_ref().map(|p| match p {
            Ok(p) => ReceiptFacts {
                verified: true,
                registry_is_attester: p.receipt.registry_did == att.registry,
                fingerprint_matches: p.receipt.key_fingerprint == meta.key_fingerprint,
                created_at: p.receipt.created_at,
            },
            Err(_) => ReceiptFacts {
                verified: false,
                registry_is_attester: false,
                fingerprint_matches: false,
                created_at: meta.not_before,
            },
        });

        // Step 8's input: revocations of the attested fingerprint,
        // discovered by agent_id (§9.3), placed by the receipt.
        let gathered =
            crate::revocation_verdict::gather(client, resolver, &body.agent_id, revocations).await;
        let assessment = crate::revocation_verdict::decide(
            gathered,
            Some(&meta.key_fingerprint),
            placed_ok.map(|p| (p.receipt.created_at, p.key_status)),
            revocations.accept_historical_receipt_key_for_pre_t,
        );
        let compromised_since = match &assessment.verdict {
            crate::RevocationVerdict::Revoked { boundary, .. } => vec![*boundary],
            _ => Vec::new(),
        };

        let facts = KeylessFacts {
            attestation_valid: true,
            attester_accepted: accepted(policy, &att.registry, body, placed_ok),
            bindings_ok: meta.binds(&body.agent_id, &body.signature),
            receipt,
            not_before: meta.not_before,
            not_after: meta.not_after,
            signature_valid: meta
                .public_key_jwk
                .verify(
                    &body.signature.algorithm,
                    &body.signature.value,
                    body.content_hash.as_str(),
                )
                .is_ok(),
            retracted: att.retracted,
            compromised_since,
        };

        // Step 9 only when steps 1–8 leave it to decide.
        let now = match decide_until_identity(&facts) {
            Ok(None) => identity_now(resolver, meta, since).await,
            _ => IdentityNow::Unreachable,
        };
        let status = match classify(&facts, now) {
            Ok(status) => status,
            // The revocation refusal keeps its typed form.
            Err(KeylessReason::Revoked) => {
                return Err(match assessment.enforce() {
                    Err(e) => e,
                    Ok(_) => refusal(KeylessReason::Revoked, body, meta),
                })
            }
            Err(reason) => return Err(refusal(reason, body, meta)),
        };
        // An unfinished discovery fails closed under its policy, and the
        // strict receipt-key profile can still refuse a pre-compromise
        // placement.
        let revocation = assessment.enforce()?;
        let placed = placed_ok.expect("classify accepted only with a verified receipt");
        Ok(KeyPhases {
            key_status: match status {
                KeylessStatus::CurrentlyAuthorized => KeyAuthorization::CurrentlyAuthorized,
                KeylessStatus::HistoricallyAuthorized => KeyAuthorization::HistoricallyAuthorized,
                KeylessStatus::HistoricallyAuthorizedPreCompromise => {
                    KeyAuthorization::HistoricallyAuthorizedPreCompromise
                }
            },
            verified_receipt: Some(placed.receipt.clone()),
            receipt_key_status: Some(placed.key_status),
            receipt_registry_key_fingerprint: Some(placed.registry_key_fingerprint.clone()),
            receipt_verdict: Some(Ok(())),
            revocation,
        })
    }
}