dtg_credentials/authority.rs
1//! Verifying a chain of Verifiable Authority Credentials.
2//!
3//! # Why this module is the important one
4//!
5//! Issuing a VAC is a struct and a signature. The security of the whole credential is in
6//! *refusing* a chain that widens — because attenuation is only a narrowing if somebody
7//! walks it. A verifier that checks only the credential it was handed accepts a
8//! **self-issued grant of arbitrary authority**: anyone can mint a VAC naming any scope and
9//! any actions, and it will verify perfectly as a signed credential. What makes it
10//! worthless is that its chain does not reach the party governing the scope.
11//!
12//! So the rules below are not stylistic. Each of them closes a way to get authority you
13//! were not given:
14//!
15//! | Rule | What it stops |
16//! |---|---|
17//! | Chain must reach a root issued by the governing party | a self-issued grant |
18//! | No link may add an action absent from its parent | privilege escalation by re-issue |
19//! | No link may widen `scope` | authority earned in one room used in another |
20//! | No link may outlive its parent | an expiry escaped by re-delegation |
21//! | Each link's issuer must be its parent's subject | grafting someone else's grant onto your own |
22//! | The leaf's subject must be the presenter | a captured presentation replayed by whoever caught it |
23//! | Depth is bounded | a denial-of-service against the verifier, which walks every link |
24//! | Every link must carry `validUntil` | authority nobody can withdraw by waiting |
25//!
26//! # Bearer-side resolution
27//!
28//! The holder presents every link. This module **never dereferences**
29//! [`crate::AuthorityGrant::parent`] to fetch a credential it was not given, and
30//! [`verify_chain`] takes the chain as a slice for exactly that reason.
31//!
32//! Working Draft 02 made that structural rather than merely required: `parent` is a
33//! **digest**, and a digest names nothing that can be fetched. So verification cannot come
34//! to depend on availability, a verifier cannot be induced to make a request against an
35//! address the *holder* chooses, and nobody hosting an identifier learns when a credential
36//! is used. The digest also binds a link to the exact claims its issuer narrowed from,
37//! which an identifier could not do: a parent re-issued with different claims does not
38//! carry its old children with it.
39//!
40//! # A VAC is not a bearer credential
41//!
42//! [`verify_chain`] takes a `presenter` and requires the leaf to grant to it. That is the
43//! rule [PR #41](https://github.com/trustoverip/dtgwg-cred-spec/pull/41) states normatively
44//! — *a verifier MUST NOT accept a party as holding the authority a VAC confers unless that
45//! party demonstrates control of the verification method associated with the presented
46//! VAC's `credentialSubject.id`* — and it is why this module no longer has an `audience`.
47//!
48//! An earlier draft of the VAC carried an OPTIONAL `audience` naming the DID that had to
49//! present the credential, and this module compared it against `presenter`. Once the
50//! presenter must be the subject, that field can only name the same party (adding nothing)
51//! or a different one (satisfiable by nobody), so it was removed rather than kept as a
52//! weaker second check. The destination question it was sometimes read as answering —
53//! *where* may this be presented — is not the credential's to answer; it belongs to the
54//! trust task carrying the presentation, which binds its own recipient.
55//!
56//! **What `presenter` must be.** The identifier of a party whose key control the caller has
57//! already established for *this request* — the DID a transport authenticated, or one a
58//! signature over the request proved. Passing an identifier the caller merely read out of
59//! the request body reduces this check to a string comparison an attacker chooses both
60//! sides of.
61//!
62//! **Only the leaf's subject demonstrates anything.** The parties named in the links above
63//! it are not present and are asked for nothing. Requiring otherwise would defeat
64//! attenuation, whose whole purpose is that the party who attenuated is not in the loop
65//! when its agent acts.
66//!
67//! # Still ahead of this module
68//!
69//! Two changes to the VAC are in flight upstream and are **not** implemented here:
70//! revocation via `credentialStatus`, cascading to everything attenuated below
71//! ([PR #39](https://github.com/trustoverip/dtgwg-cred-spec/pull/39)); and a
72//! `maxAttenuation` ceiling bounding depth per-ancestor rather than only globally
73//! ([PR #40](https://github.com/trustoverip/dtgwg-cred-spec/pull/40)). Until they land, a
74//! caller wanting revocation must check [`crate::DTGCommon::credential_status`] itself.
75
76use chrono::{DateTime, Utc};
77
78use crate::{DTGCredential, DTGCredentialType};
79
80/// Maximum number of VACs in a chain, including the root.
81///
82/// Verification is linear in depth and runs on every presentation, so an unbounded chain is
83/// a denial-of-service surface. The known uses need far less — a person attenuating to an
84/// agent is depth 2, and an agent attenuating to a sub-agent is depth 3 — so a chain near
85/// this ceiling is a signal that authority is being re-delegated further than intended.
86pub const MAX_CHAIN_DEPTH: usize = 8;
87
88/// Why a chain was refused.
89///
90/// Each variant names a specific way of acquiring authority that was not granted, rather
91/// than collapsing into one "invalid" — a verifier's logs are where an escalation attempt
92/// becomes visible.
93#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
94pub enum AuthorityError {
95 /// The chain was empty. Nothing to verify.
96 #[error("authority chain is empty")]
97 EmptyChain,
98
99 /// A link's digest could not be computed, or one it carries could not be read.
100 ///
101 /// Distinct from [AuthorityError::BrokenLink]: a digest that cannot be *read* is not a
102 /// digest that disagrees, and a verifier that conflated the two would report a
103 /// malformed chain as a widening one.
104 #[error("digest error at index {index}: {reason}")]
105 Digest { index: usize, reason: String },
106
107 /// A link carried no `validUntil`, which a VAC MUST have.
108 #[error("VAC at index {index} carries no validUntil, which a VAC MUST have")]
109 NoExpiry { index: usize },
110
111 /// The chain is longer than [MAX_CHAIN_DEPTH].
112 #[error("authority chain is {found} deep, exceeding the maximum of {MAX_CHAIN_DEPTH}")]
113 TooDeep {
114 /// How many links were presented.
115 found: usize,
116 },
117
118 /// A credential in the chain was not an `AuthorityCredential`.
119 #[error("chain link {index} is a {found}, not an AuthorityCredential")]
120 NotAuthority {
121 /// Position in the chain, leaf first.
122 index: usize,
123 /// What was found instead.
124 found: String,
125 },
126
127 /// The chain root was not issued by the party governing the scope.
128 ///
129 /// This is the finding that matters most: a chain that does not reach the governing
130 /// party is a self-issued grant, however well-formed each link is.
131 #[error(
132 "chain root was issued by `{root_issuer}`, not by `{expected}` which governs the scope"
133 )]
134 RootNotGoverning {
135 /// Who actually issued the root.
136 root_issuer: String,
137 /// Who governs the scope being accessed.
138 expected: String,
139 },
140
141 /// A link's `parent` did not name the credential presented as its parent.
142 #[error("chain link {index} names parent `{named}`, but was presented after `{presented}`")]
143 BrokenLink {
144 /// Position in the chain, leaf first.
145 index: usize,
146 /// The `id` the link points at.
147 named: String,
148 /// The `id` of the credential actually presented as its parent.
149 presented: String,
150 },
151
152 /// A link was issued by someone other than its parent's subject.
153 ///
154 /// Only the party a grant was made to may attenuate it. Without this check a holder
155 /// could graft an unrelated grant onto their own chain.
156 #[error("chain link {index} was issued by `{issuer}`, but its parent granted to `{subject}`")]
157 IssuerNotParentSubject {
158 /// Position in the chain, leaf first.
159 index: usize,
160 /// Who issued the link.
161 issuer: String,
162 /// Who the parent granted to.
163 subject: String,
164 },
165
166 /// A link conferred an action its parent did not.
167 #[error("chain link {index} adds action `{action}`, which its parent does not confer")]
168 WidensActions {
169 /// Position in the chain, leaf first.
170 index: usize,
171 /// The action that was added.
172 action: String,
173 },
174
175 /// A link named a different scope from its parent.
176 #[error("chain link {index} has scope `{scope}`, its parent `{parent_scope}`")]
177 WidensScope {
178 /// Position in the chain, leaf first.
179 index: usize,
180 /// The link's scope.
181 scope: String,
182 /// The parent's scope.
183 parent_scope: String,
184 },
185
186 /// A link outlived its parent.
187 #[error("chain link {index} is valid until {until}, beyond its parent's {parent_until}")]
188 OutlivesParent {
189 /// Position in the chain, leaf first.
190 index: usize,
191 /// The link's expiry.
192 until: DateTime<Utc>,
193 /// The parent's expiry.
194 parent_until: DateTime<Utc>,
195 },
196
197 /// The requested scope is not the one the chain confers on.
198 #[error("chain confers on scope `{granted}`, but `{requested}` was requested")]
199 ScopeMismatch {
200 /// What the chain grants on.
201 granted: String,
202 /// What was asked for.
203 requested: String,
204 },
205
206 /// The chain does not confer the requested action.
207 #[error("chain does not confer action `{action}`")]
208 ActionNotGranted {
209 /// The action that was requested.
210 action: String,
211 },
212
213 /// The leaf grants to somebody other than the party presenting it.
214 ///
215 /// A VAC is evidence that authority was conferred on somebody. It is not evidence that
216 /// whoever handed it over is that somebody, and a verifier that conflated the two would
217 /// authorize every captured presentation.
218 #[error("the chain's leaf grants to `{subject}`, but it was presented by `{presenter}`")]
219 NotThePresenter {
220 /// Who the leaf grants to.
221 subject: String,
222 /// Who presented it.
223 presenter: String,
224 },
225
226 /// A link was outside its validity window at the time of the check.
227 #[error("chain link {index} is not valid at {at}")]
228 NotValidNow {
229 /// Position in the chain, leaf first.
230 index: usize,
231 /// The instant checked against.
232 at: DateTime<Utc>,
233 },
234
235 /// A link carried an empty `actions` list.
236 #[error("chain link {index} confers no actions")]
237 NoActions {
238 /// Position in the chain, leaf first.
239 index: usize,
240 },
241}
242
243/// What a verified chain permits.
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub struct VerifiedAuthority {
246 /// The party the leaf grants to — who may act.
247 pub subject: String,
248 /// The scope the chain confers on.
249 pub scope: String,
250 /// The actions the leaf confers, already narrowed by every link above it.
251 pub actions: Vec<String>,
252 /// The party governing the scope, which issued the chain root.
253 pub governing_party: String,
254}
255
256/// Verify a chain of VACs and return what it permits.
257///
258/// `chain` is **leaf first**: `chain[0]` is the credential being presented, and the last
259/// element must be the root issued by `governing_party`. Every link the holder relies on
260/// must be present — this function never fetches one (see the module docs).
261///
262/// The signature on each credential is *not* checked here. Verify those first, with
263/// [crate::DTGCredential] and the data-integrity suite; this function answers the separate
264/// question of whether a set of cryptographically valid credentials adds up to the
265/// authority claimed. Both checks are required and neither substitutes for the other.
266///
267/// Returns [VerifiedAuthority] describing what the chain actually permits, which is never
268/// more than the root conferred.
269pub fn verify_chain(
270 chain: &[DTGCredential],
271 governing_party: &str,
272 requested_scope: &str,
273 requested_action: &str,
274 presenter: &str,
275 at: DateTime<Utc>,
276) -> Result<VerifiedAuthority, AuthorityError> {
277 if chain.is_empty() {
278 return Err(AuthorityError::EmptyChain);
279 }
280 if chain.len() > MAX_CHAIN_DEPTH {
281 return Err(AuthorityError::TooDeep { found: chain.len() });
282 }
283
284 // Every link must be a VAC carrying a grant.
285 for (index, link) in chain.iter().enumerate() {
286 if !matches!(link.type_(), DTGCredentialType::Authority) {
287 return Err(AuthorityError::NotAuthority {
288 index,
289 found: link.type_().to_string(),
290 });
291 }
292 let grant = link
293 .credential()
294 .authority()
295 .ok_or_else(|| AuthorityError::NotAuthority {
296 index,
297 found: "AuthorityCredential without an authority grant".to_string(),
298 })?;
299 if grant.actions.is_empty() {
300 return Err(AuthorityError::NoActions { index });
301 }
302 // Validity window, checked per link: a chain is only as live as its shortest-lived
303 // member, and an expired parent does not become live again because its child says so.
304 let c = link.credential();
305 if c.valid_from() > at {
306 return Err(AuthorityError::NotValidNow { index, at });
307 }
308 // `validUntil` is REQUIRED on a VAC, not merely recommended. Nothing about the
309 // subject's current standing is consulted here, so a VAC that never expires is
310 // authority nobody can withdraw by waiting — and a verifier that accepted one
311 // would be honouring exactly that.
312 let Some(until) = c.valid_until() else {
313 return Err(AuthorityError::NoExpiry { index });
314 };
315 if until < at {
316 return Err(AuthorityError::NotValidNow { index, at });
317 }
318 }
319
320 // Key control at invocation: the leaf must grant to whoever is presenting it.
321 //
322 // Without this a presentation is a bearer object — it names what may be done, not who
323 // is doing it — so anyone who observes one inherits everything it confers. The check is
324 // only as good as `presenter`: see the module docs on what a caller must have
325 // established before passing one.
326 let leaf = &chain[0];
327 let leaf_grant = leaf.credential().authority().expect("checked above");
328 let leaf_subject = leaf.credential().subject();
329 if leaf_subject != presenter {
330 return Err(AuthorityError::NotThePresenter {
331 subject: leaf_subject.to_string(),
332 presenter: presenter.to_string(),
333 });
334 }
335
336 // Walk leaf -> root. Each step checks the link against the credential above it.
337 for index in 0..chain.len() - 1 {
338 let link = &chain[index];
339 let parent = &chain[index + 1];
340 let grant = link.credential().authority().expect("checked above");
341 let parent_grant = parent.credential().authority().expect("checked above");
342
343 // The link must point at the credential presented as its parent. Without this a
344 // holder could interleave links from unrelated chains.
345 //
346 // `parent` is a digest, not an identifier, so this is a hash comparison over the
347 // parent's claims — and the specification requires comparing decoded digest bytes
348 // rather than encoded strings, since one digest has more than one spelling.
349 let presented_digest = parent
350 .digest_multibase()
351 .map_err(|e| AuthorityError::Digest {
352 index: index + 1,
353 reason: e.to_string(),
354 })?;
355 match &grant.parent {
356 Some(named) => {
357 let matches = crate::digests_match(named, &presented_digest).map_err(|e| {
358 AuthorityError::Digest {
359 index,
360 reason: e.to_string(),
361 }
362 })?;
363 if !matches {
364 return Err(AuthorityError::BrokenLink {
365 index,
366 named: named.clone(),
367 presented: presented_digest,
368 });
369 }
370 }
371 None => {
372 // A link with no `parent` claims to be a root, but something was presented
373 // above it.
374 return Err(AuthorityError::BrokenLink {
375 index,
376 named: "<none — link claims to be a root>".to_string(),
377 presented: presented_digest,
378 });
379 }
380 }
381
382 // Only the party a grant was made to may attenuate it.
383 if link.credential().issuer() != parent.credential().subject() {
384 return Err(AuthorityError::IssuerNotParentSubject {
385 index,
386 issuer: link.credential().issuer().to_string(),
387 subject: parent.credential().subject().to_string(),
388 });
389 }
390
391 // Narrowing, on all three axes.
392 if grant.scope != parent_grant.scope {
393 return Err(AuthorityError::WidensScope {
394 index,
395 scope: grant.scope.clone(),
396 parent_scope: parent_grant.scope.clone(),
397 });
398 }
399 for action in &grant.actions {
400 if !parent_grant.actions.contains(action) {
401 return Err(AuthorityError::WidensActions {
402 index,
403 action: action.clone(),
404 });
405 }
406 }
407 // Both are present: the loop above rejected any link without one.
408 if let (Some(until), Some(parent_until)) = (
409 link.credential().valid_until(),
410 parent.credential().valid_until(),
411 ) && until > parent_until
412 {
413 return Err(AuthorityError::OutlivesParent {
414 index,
415 until,
416 parent_until,
417 });
418 }
419 }
420
421 // The root must be the governing party's, and must claim to be a root.
422 let root = chain.last().expect("non-empty");
423 let root_grant = root.credential().authority().expect("checked above");
424 if root.credential().issuer() != governing_party {
425 return Err(AuthorityError::RootNotGoverning {
426 root_issuer: root.credential().issuer().to_string(),
427 expected: governing_party.to_string(),
428 });
429 }
430 if root_grant.parent.is_some() {
431 // The chain was truncated: its "root" points at something not presented.
432 return Err(AuthorityError::BrokenLink {
433 index: chain.len() - 1,
434 named: root_grant.parent.clone().unwrap_or_default(),
435 presented: "<nothing — chain ends here>".to_string(),
436 });
437 }
438
439 // Finally, what was asked for.
440 if leaf_grant.scope != requested_scope {
441 return Err(AuthorityError::ScopeMismatch {
442 granted: leaf_grant.scope.clone(),
443 requested: requested_scope.to_string(),
444 });
445 }
446 if !leaf_grant.actions.iter().any(|a| a == requested_action) {
447 return Err(AuthorityError::ActionNotGranted {
448 action: requested_action.to_string(),
449 });
450 }
451
452 Ok(VerifiedAuthority {
453 subject: leaf.credential().subject().to_string(),
454 scope: leaf_grant.scope.clone(),
455 actions: leaf_grant.actions.clone(),
456 governing_party: governing_party.to_string(),
457 })
458}