Skip to main content

adk_server/awp/
tiers.rs

1//! Trust tiers from verified credentials (spec 3.5 §7.3, A-I6; AWP 2.0 §6).
2//!
3//! [`EdgeTiers`] runs every configured [`CredentialVerifier`] on a request and assigns the
4//! highest tier its verified credentials earn:
5//!
6//! | Credential | Verifier | Requester id | Tier |
7//! |---|---|---|---|
8//! | Web Bot Auth signature | [`WebBotAuthTrustAssigner`] | `wba:{directory origin}#{thumbprint}` | `known`; `verified` when the directory is on the owner's verified list |
9//! | OAuth client-credentials token | [`OAuthClientCredentials`] | `oauth:{issuer}#{client id}` | `known`, or the tier its scopes grant |
10//! | Client certificate from the listener | [`MtlsCredentials`] | `mtls:{base64url SHA-256 of the DER}` | `known`; `verified` for an issuer on the verified list |
11//! | Owner-issued API key | [`ApiKeyCredentials`] | `key:{key id}` | `known` |
12//! | Any of the above on an owner allowlist | [`TrustRules`] | — | the rule's tier, such as `partner` |
13//!
14//! Claims — `User-Agent`, `X-AWP-Channel`, any self-declared header — never raise a tier; they
15//! become a `claimed_agent` label for analytics. A presented credential that fails a check is
16//! refused with `unauthorized` (AWP 2.0 §6.4); one that cannot be checked, such as a signature
17//! whose key directory is unreachable, earns `public`. Paired devices — `internal` in AWP 1.x —
18//! are never recognised at the public edge.
19//!
20//! Limits key on the verified requester id, else a digest of the presented credential, else
21//! the peer address ([`EdgeCaller::limit_key`]).
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::net::SocketAddr;
25use std::sync::Arc;
26
27use adk_auth::sso::TokenValidator;
28use adk_auth::web_bot_auth::{
29    HttpSignatureVerifier, RequestHead, SIGNATURE_AGENT, SIGNATURE_INPUT,
30};
31use adk_awp::v2::tier::{TierAssigner, TierAssignment, claimed_agent};
32use async_trait::async_trait;
33use awp_types::{IdentityMethod, RequesterId, TrustRule, TrustRules, TrustTier};
34use axum::extract::ConnectInfo;
35use axum::http::request::Parts;
36use axum::http::{HeaderMap, header};
37use base64::Engine as _;
38use base64::engine::general_purpose::URL_SAFE_NO_PAD;
39use sha2::{Digest as _, Sha256};
40
41/// The caller of one edge request, as [`EdgeTiers`] assessed it (spec 3.5 §7.3).
42///
43/// The edge stores it in the request's extensions, so every binding sees one assessment.
44#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub struct EdgeCaller {
47    /// The caller's tier.
48    pub tier: TrustTier,
49    /// The verified requester id, from `known` up.
50    pub requester: Option<RequesterId>,
51    /// What limits key on: `id:{requester}`, `cred:{digest}` or `ip:{peer address}`.
52    pub limit_key: String,
53    /// The rate class of the owner's rule that matched, if any.
54    pub rate_class: Option<String>,
55    /// What the request claims to be, for analytics only.
56    pub claimed_agent: Option<String>,
57    /// The visitor a public caller converses as: the id its `AWP-Subject` token or visitor
58    /// cookie carries, else a new random one the edge hands back in `AWP-Subject`. `None`
59    /// for a verified requester, who converses as itself.
60    pub visitor: Option<adk_core::subject::VisitorId>,
61}
62
63impl EdgeCaller {
64    /// A `public` caller limited by `limit_key`.
65    pub fn public(limit_key: impl Into<String>) -> Self {
66        Self {
67            tier: TrustTier::Public,
68            requester: None,
69            limit_key: limit_key.into(),
70            rate_class: None,
71            claimed_agent: None,
72            visitor: None,
73        }
74    }
75
76    /// The tier assignment the `/awp/v2/` routes read.
77    pub fn assignment(&self) -> TierAssignment {
78        match &self.requester {
79            Some(requester) if self.tier > TrustTier::Public => {
80                TierAssignment::verified(self.tier, requester.clone())
81            }
82            _ => TierAssignment::public(),
83        }
84    }
85}
86
87/// A presented credential that failed a check (AWP 2.0 §6.4): the request is refused with
88/// `unauthorized`.
89#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
90#[error("{method:?} credential failed verification: {reason}")]
91pub struct EdgeRefusal {
92    /// The identity method whose credential failed.
93    pub method: IdentityMethod,
94    /// Why, for logs; never sent to the requester.
95    pub reason: String,
96}
97
98/// A credential a verifier proved (spec 3.5 §7.3).
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct VerifiedCredential {
101    /// The requester id.
102    pub requester: RequesterId,
103    /// Who vouches for it — a key directory origin, an OAuth issuer, a certificate issuer —
104    /// matched against the owner's verified list.
105    pub issuer: String,
106    /// A tier the credential itself grants, such as an OAuth scope mapped to `partner`.
107    pub granted: Option<TrustTier>,
108}
109
110/// What a [`CredentialVerifier`] found on a request.
111#[derive(Debug, Clone, PartialEq, Eq)]
112#[non_exhaustive]
113pub enum CredentialCheck {
114    /// The request presents no credential of this kind.
115    Absent,
116    /// The credential verified.
117    Verified(VerifiedCredential),
118    /// The credential could not be checked, for example because its key directory is
119    /// unreachable; the request stays `public` and limits key on `digest`.
120    Unverifiable {
121        /// A digest of the presented credential.
122        digest: String,
123        /// Why, for logs.
124        reason: String,
125    },
126    /// The credential failed a check; the request is refused.
127    Failed {
128        /// Why, for logs.
129        reason: String,
130    },
131}
132
133/// Verifies one kind of credential (spec 3.5 §7.3).
134///
135/// # Example
136///
137/// ```rust
138/// use adk_server::awp::tiers::{CredentialCheck, CredentialVerifier, VerifiedCredential};
139/// use awp_types::{IdentityMethod, RequesterId};
140///
141/// /// Trusts a header set by a gateway that already authenticated the caller.
142/// struct GatewayHeader;
143///
144/// #[async_trait::async_trait]
145/// impl CredentialVerifier for GatewayHeader {
146///     fn method(&self) -> IdentityMethod {
147///         IdentityMethod::ApiKey
148///     }
149///
150///     async fn verify(&self, head: &axum::http::request::Parts) -> CredentialCheck {
151///         match head.headers.get("x-gateway-client").and_then(|value| value.to_str().ok()) {
152///             None => CredentialCheck::Absent,
153///             Some(id) => CredentialCheck::Verified(VerifiedCredential {
154///                 requester: RequesterId::api_key(id),
155///                 issuer: "gateway".into(),
156///                 granted: None,
157///             }),
158///         }
159///     }
160/// }
161/// ```
162#[async_trait]
163pub trait CredentialVerifier: Send + Sync {
164    /// The identity method this verifier accepts, published in the trust rules.
165    fn method(&self) -> IdentityMethod;
166
167    /// Checks the request's credential of this kind.
168    async fn verify(&self, head: &Parts) -> CredentialCheck;
169}
170
171fn digest(parts: &[&str]) -> String {
172    let mut hasher = Sha256::new();
173    for part in parts {
174        hasher.update(part.as_bytes());
175        hasher.update([0x1f]);
176    }
177    hex::encode(&hasher.finalize()[..16])
178}
179
180fn header_str(headers: &HeaderMap, name: impl axum::http::header::AsHeaderName) -> &str {
181    headers.get(name).and_then(|value| value.to_str().ok()).unwrap_or("")
182}
183
184// --- Web Bot Auth --------------------------------------------------------------------------
185
186/// Web Bot Auth at the edge: `known` for a verified signature, `verified` when its key
187/// directory is on the owner's verified list, and an owner rule's tier, such as `partner`
188/// (spec 3.5 §7.3; AWP 2.0 §6.3).
189///
190/// It is a [`CredentialVerifier`] inside [`EdgeTiers`] and, alone, a [`TierAssigner`]. The
191/// [`HttpSignatureVerifier`] requires the draft's covered components, `created` and `expires`
192/// within its skew (60 s by default), and caches directories for their HTTP cache lifetime.
193///
194/// # Example
195///
196/// ```rust
197/// use std::sync::Arc;
198///
199/// use adk_auth::web_bot_auth::{HttpSignatureVerifier, InMemoryKeyDirectorySource};
200/// use adk_server::awp::tiers::WebBotAuthTrustAssigner;
201///
202/// let verifier = HttpSignatureVerifier::builder(Arc::new(InMemoryKeyDirectorySource::new())).build();
203/// let assigner = WebBotAuthTrustAssigner::new(verifier).verified_directory("https://bots.example.com");
204/// # let _ = assigner;
205/// ```
206pub struct WebBotAuthTrustAssigner {
207    verifier: HttpSignatureVerifier,
208    verified: BTreeSet<String>,
209    rules: TrustRules,
210    default_scheme: String,
211}
212
213impl std::fmt::Debug for WebBotAuthTrustAssigner {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        f.debug_struct("WebBotAuthTrustAssigner")
216            .field("verified", &self.verified)
217            .finish_non_exhaustive()
218    }
219}
220
221impl WebBotAuthTrustAssigner {
222    /// An assigner over `verifier`, with no verified directories and no rules.
223    pub fn new(verifier: HttpSignatureVerifier) -> Self {
224        Self {
225            verifier,
226            verified: BTreeSet::new(),
227            rules: TrustRules::default(),
228            default_scheme: "https".to_owned(),
229        }
230    }
231
232    /// Adds a key directory origin to the owner's verified list.
233    #[must_use]
234    pub fn verified_directory(mut self, origin: impl Into<String>) -> Self {
235        self.verified.insert(origin.into());
236        self
237    }
238
239    /// Sets the owner's rules, used when the assigner runs alone.
240    #[must_use]
241    pub fn rules(mut self, rules: TrustRules) -> Self {
242        self.rules = rules;
243        self
244    }
245
246    /// The scheme of an origin-form request URI, `https` by default; set `http` behind a
247    /// plain-text listener in tests.
248    #[must_use]
249    pub fn default_scheme(mut self, scheme: impl Into<String>) -> Self {
250        self.default_scheme = scheme.into();
251        self
252    }
253}
254
255#[async_trait]
256impl CredentialVerifier for WebBotAuthTrustAssigner {
257    fn method(&self) -> IdentityMethod {
258        IdentityMethod::WebBotAuth
259    }
260
261    async fn verify(&self, head: &Parts) -> CredentialCheck {
262        let request = RequestHead::new(&head.method, &head.uri, &head.headers)
263            .with_default_scheme(&self.default_scheme);
264        match self.verifier.verify(request).await {
265            Ok(None) => CredentialCheck::Absent,
266            Ok(Some(requester)) => {
267                let tier = self.verified.contains(&requester.directory_origin);
268                CredentialCheck::Verified(VerifiedCredential {
269                    requester: RequesterId::new(requester.id),
270                    issuer: requester.directory_origin,
271                    granted: tier.then_some(TrustTier::Verified),
272                })
273            }
274            Err(error) if error.is_unverified() => CredentialCheck::Unverifiable {
275                digest: digest(&[
276                    "wba",
277                    header_str(&head.headers, SIGNATURE_AGENT),
278                    header_str(&head.headers, SIGNATURE_INPUT),
279                ]),
280                reason: error.to_string(),
281            },
282            Err(error) => CredentialCheck::Failed { reason: error.to_string() },
283        }
284    }
285}
286
287#[async_trait]
288impl TierAssigner for WebBotAuthTrustAssigner {
289    async fn assign(&self, head: &Parts) -> TierAssignment {
290        match CredentialVerifier::verify(self, head).await {
291            CredentialCheck::Verified(credential) => {
292                let tier = credential
293                    .granted
294                    .unwrap_or(TrustTier::Known)
295                    .max(self.rules.tier_for(&credential.requester));
296                TierAssignment::verified(tier, credential.requester)
297            }
298            _ => TierAssignment::public(),
299        }
300    }
301}
302
303// --- OAuth client credentials --------------------------------------------------------------
304
305/// OAuth 2.0 client-credentials tokens through `adk-auth`'s validators: `known`, or the tier
306/// the token's scopes grant (spec 3.5 §7.3; AWP 2.0 §6.2).
307///
308/// A bearer token from an issuer with no validator, or one that fails validation, is refused.
309/// The client id is the token's `client_id` claim, else `azp`, else `sub`.
310///
311/// # Example
312///
313/// ```rust,ignore
314/// use adk_auth::sso::JwtValidator;
315/// use adk_server::awp::tiers::OAuthClientCredentials;
316/// use awp_types::TrustTier;
317///
318/// let validator = JwtValidator::builder()
319///     .issuer("https://auth.partner.example")
320///     .audience("https://agent.example")
321///     .jwks_uri("https://auth.partner.example/.well-known/jwks.json")
322///     .build()?;
323/// let oauth = OAuthClientCredentials::new()
324///     .validator(std::sync::Arc::new(validator))
325///     .scope_tier("awp:partner", TrustTier::Partner);
326/// ```
327#[derive(Default)]
328pub struct OAuthClientCredentials {
329    validators: BTreeMap<String, Arc<dyn TokenValidator>>,
330    scope_tiers: BTreeMap<String, TrustTier>,
331}
332
333impl std::fmt::Debug for OAuthClientCredentials {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.debug_struct("OAuthClientCredentials")
336            .field("issuers", &self.validators.keys().collect::<Vec<_>>())
337            .field("scope_tiers", &self.scope_tiers)
338            .finish()
339    }
340}
341
342impl OAuthClientCredentials {
343    /// Accepts no issuer until [`validator`](Self::validator) adds one.
344    pub fn new() -> Self {
345        Self::default()
346    }
347
348    /// Accepts tokens `validator` validates, for its issuer.
349    #[must_use]
350    pub fn validator(mut self, validator: Arc<dyn TokenValidator>) -> Self {
351        self.validators.insert(validator.issuer().to_owned(), validator);
352        self
353    }
354
355    /// Grants `tier` to tokens carrying `scope`.
356    #[must_use]
357    pub fn scope_tier(mut self, scope: impl Into<String>, tier: TrustTier) -> Self {
358        self.scope_tiers.insert(scope.into(), tier);
359        self
360    }
361
362    /// The unverified `iss` of a JWT, to choose its validator.
363    fn issuer_of(token: &str) -> Option<String> {
364        let payload = token.split('.').nth(1)?;
365        let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?;
366        let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
367        claims.get("iss")?.as_str().map(str::to_owned)
368    }
369}
370
371#[async_trait]
372impl CredentialVerifier for OAuthClientCredentials {
373    fn method(&self) -> IdentityMethod {
374        IdentityMethod::Oauth2ClientCredentials
375    }
376
377    async fn verify(&self, head: &Parts) -> CredentialCheck {
378        let Some(token) = header_str(&head.headers, header::AUTHORIZATION)
379            .strip_prefix("Bearer ")
380            .map(str::trim)
381            .filter(|token| !token.is_empty())
382        else {
383            return CredentialCheck::Absent;
384        };
385        let Some(validator) = Self::issuer_of(token).and_then(|iss| self.validators.get(&iss))
386        else {
387            return CredentialCheck::Failed {
388                reason: "the bearer token's issuer is not one the site trusts".to_owned(),
389            };
390        };
391        match validator.validate(token).await {
392            Ok(claims) => {
393                let client = claims
394                    .get_custom::<String>("client_id")
395                    .or_else(|| claims.get_custom::<String>("azp"))
396                    .unwrap_or_else(|| claims.sub.clone());
397                let granted = claims
398                    .scopes()
399                    .iter()
400                    .filter_map(|scope| self.scope_tiers.get(scope).copied())
401                    .max();
402                CredentialCheck::Verified(VerifiedCredential {
403                    requester: RequesterId::oauth_client(&claims.iss, &client),
404                    issuer: claims.iss,
405                    granted,
406                })
407            }
408            Err(error) => CredentialCheck::Failed { reason: error.to_string() },
409        }
410    }
411}
412
413// --- mTLS ----------------------------------------------------------------------------------
414
415/// The client certificate a TLS listener verified, inserted into the request's extensions
416/// by the listener (spec 3.5 §7.3; AWP 2.0 §6.2).
417///
418/// The edge reads it; it never parses or verifies certificates itself.
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub struct ClientCertificate {
421    /// The certificate, DER-encoded.
422    pub der: Vec<u8>,
423    /// The issuer's distinguished name, matched against the owner's verified list.
424    pub issuer: Option<String>,
425}
426
427/// Mutual TLS where the listener provides a client certificate: `known`, `verified` for an
428/// issuer on the owner's verified list (spec 3.5 §7.3).
429///
430/// # Example
431///
432/// ```rust
433/// use adk_server::awp::tiers::MtlsCredentials;
434///
435/// let mtls = MtlsCredentials::new().trusted_issuer("CN=Partner CA");
436/// # let _ = mtls;
437/// ```
438#[derive(Debug, Clone, Default)]
439pub struct MtlsCredentials {
440    trusted: BTreeSet<String>,
441}
442
443impl MtlsCredentials {
444    /// Accepts every certificate the listener verified.
445    pub fn new() -> Self {
446        Self::default()
447    }
448
449    /// Accepts only certificates from these issuers; others are refused.
450    #[must_use]
451    pub fn trusted_issuer(mut self, issuer: impl Into<String>) -> Self {
452        self.trusted.insert(issuer.into());
453        self
454    }
455}
456
457#[async_trait]
458impl CredentialVerifier for MtlsCredentials {
459    fn method(&self) -> IdentityMethod {
460        IdentityMethod::Mtls
461    }
462
463    async fn verify(&self, head: &Parts) -> CredentialCheck {
464        let Some(certificate) = head.extensions.get::<ClientCertificate>() else {
465            return CredentialCheck::Absent;
466        };
467        let issuer = certificate.issuer.clone().unwrap_or_default();
468        if !self.trusted.is_empty() && !self.trusted.contains(&issuer) {
469            return CredentialCheck::Failed {
470                reason: "the client certificate's issuer is not trusted".to_owned(),
471            };
472        }
473        let thumbprint = URL_SAFE_NO_PAD.encode(Sha256::digest(&certificate.der));
474        CredentialCheck::Verified(VerifiedCredential {
475            requester: RequesterId::mtls(&thumbprint),
476            issuer,
477            granted: None,
478        })
479    }
480}
481
482// --- API keys ------------------------------------------------------------------------------
483
484/// The authorization scheme of an owner-issued API key: `Authorization: ApiKey {id}:{secret}`.
485pub const API_KEY_SCHEME: &str = "ApiKey";
486
487/// API keys the owner issued: `known` (spec 3.5 §7.3). Only SHA-256 digests of the secrets
488/// are held.
489///
490/// # Example
491///
492/// ```rust
493/// use adk_server::awp::tiers::ApiKeyCredentials;
494///
495/// let keys = ApiKeyCredentials::new().key_secret("buyer-7", "s3cr3t-value");
496/// # let _ = keys;
497/// ```
498#[derive(Debug, Clone, Default)]
499pub struct ApiKeyCredentials {
500    digests: BTreeMap<String, [u8; 32]>,
501}
502
503impl ApiKeyCredentials {
504    /// Accepts no key until one is added.
505    pub fn new() -> Self {
506        Self::default()
507    }
508
509    /// Accepts key `id` whose secret has SHA-256 `digest`.
510    #[must_use]
511    pub fn key(mut self, id: impl Into<String>, digest: [u8; 32]) -> Self {
512        self.digests.insert(id.into(), digest);
513        self
514    }
515
516    /// Accepts key `id` with `secret`, keeping only its digest.
517    #[must_use]
518    pub fn key_secret(self, id: impl Into<String>, secret: &str) -> Self {
519        self.key(id, Sha256::digest(secret.as_bytes()).into())
520    }
521}
522
523#[async_trait]
524impl CredentialVerifier for ApiKeyCredentials {
525    fn method(&self) -> IdentityMethod {
526        IdentityMethod::ApiKey
527    }
528
529    async fn verify(&self, head: &Parts) -> CredentialCheck {
530        let value = header_str(&head.headers, header::AUTHORIZATION);
531        let Some(key) = value
532            .strip_prefix(API_KEY_SCHEME)
533            .and_then(|rest| rest.strip_prefix(' '))
534            .map(str::trim)
535        else {
536            return CredentialCheck::Absent;
537        };
538        let Some((id, secret)) = key.split_once(':') else {
539            return CredentialCheck::Failed { reason: "an API key is `{id}:{secret}`".to_owned() };
540        };
541        let presented: [u8; 32] = Sha256::digest(secret.as_bytes()).into();
542        let matches = self.digests.get(id).is_some_and(|expected| {
543            expected.iter().zip(presented.iter()).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
544        });
545        if matches {
546            CredentialCheck::Verified(VerifiedCredential {
547                requester: RequesterId::api_key(id),
548                issuer: "owner".to_owned(),
549                granted: None,
550            })
551        } else {
552            CredentialCheck::Failed { reason: format!("API key `{id}` is not valid") }
553        }
554    }
555}
556
557// --- The edge's assigner -------------------------------------------------------------------
558
559/// Assigns each request's tier from its verified credentials and the owner's rules (spec 3.5
560/// §7.3, A-I6; AWP 2.0 §6.5).
561///
562/// The tier of a verified requester is the highest of `known`, what its credential grants,
563/// `verified` when its issuer is on the owner's verified list, and the highest owner rule its
564/// id matches. Published rules appear at `GET /awp/v2/trust`; private rules, such as a partner
565/// allowlist, apply without being published.
566///
567/// # Example
568///
569/// ```rust
570/// use adk_server::awp::tiers::{ApiKeyCredentials, EdgeTiers};
571/// use awp_types::{TrustRule, TrustTier};
572///
573/// let tiers = EdgeTiers::builder()
574///     .verifier(ApiKeyCredentials::new().key_secret("partner-1", "secret"))
575///     .private_rule(TrustRule {
576///         subject: "key:partner-1".into(),
577///         tier: TrustTier::Partner,
578///         rate_class: None,
579///         note: None,
580///     })
581///     .build();
582/// assert!(tiers.published_rules().rules.is_empty());
583/// ```
584pub struct EdgeTiers {
585    verifiers: Vec<Arc<dyn CredentialVerifier>>,
586    rules: TrustRules,
587    published: TrustRules,
588    verified_issuers: BTreeSet<String>,
589}
590
591impl std::fmt::Debug for EdgeTiers {
592    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
593        f.debug_struct("EdgeTiers")
594            .field("accepts", &self.published.accepts)
595            .field("rules", &self.rules.rules.len())
596            .finish_non_exhaustive()
597    }
598}
599
600/// Builder for [`EdgeTiers`].
601#[derive(Default)]
602pub struct EdgeTiersBuilder {
603    verifiers: Vec<Arc<dyn CredentialVerifier>>,
604    public_rules: Vec<TrustRule>,
605    private_rules: Vec<TrustRule>,
606    rate_classes: BTreeMap<String, awp_types::RateClass>,
607    verified_issuers: BTreeSet<String>,
608}
609
610impl EdgeTiersBuilder {
611    /// Adds a credential verifier.
612    #[must_use]
613    pub fn verifier(mut self, verifier: impl CredentialVerifier + 'static) -> Self {
614        self.verifiers.push(Arc::new(verifier));
615        self
616    }
617
618    /// Adds a shared credential verifier.
619    #[must_use]
620    pub fn shared_verifier(mut self, verifier: Arc<dyn CredentialVerifier>) -> Self {
621        self.verifiers.push(verifier);
622        self
623    }
624
625    /// Adds a published owner rule.
626    #[must_use]
627    pub fn rule(mut self, rule: TrustRule) -> Self {
628        self.public_rules.push(rule);
629        self
630    }
631
632    /// Adds an owner rule that applies without being published, such as a partner allowlist.
633    #[must_use]
634    pub fn private_rule(mut self, rule: TrustRule) -> Self {
635        self.private_rules.push(rule);
636        self
637    }
638
639    /// Defines a rate class rules and capabilities name.
640    #[must_use]
641    pub fn rate_class(mut self, name: impl Into<String>, class: awp_types::RateClass) -> Self {
642        self.rate_classes.insert(name.into(), class);
643        self
644    }
645
646    /// Adds an issuer — key directory origin, OAuth issuer, certificate issuer — to the owner's
647    /// verified list.
648    #[must_use]
649    pub fn verified_issuer(mut self, issuer: impl Into<String>) -> Self {
650        self.verified_issuers.insert(issuer.into());
651        self
652    }
653
654    /// Builds the assigner.
655    pub fn build(self) -> EdgeTiers {
656        let mut accepts: Vec<IdentityMethod> =
657            self.verifiers.iter().map(|verifier| verifier.method()).collect();
658        accepts.sort();
659        accepts.dedup();
660        let published = TrustRules {
661            accepts: accepts.clone(),
662            rules: self.public_rules.clone(),
663            rate_classes: self.rate_classes.clone(),
664        };
665        let mut rules = published.clone();
666        rules.rules.extend(self.private_rules);
667        EdgeTiers {
668            verifiers: self.verifiers,
669            rules,
670            published,
671            verified_issuers: self.verified_issuers,
672        }
673    }
674}
675
676impl EdgeTiers {
677    /// Starts a builder with no verifiers: every caller is `public` until one is added.
678    pub fn builder() -> EdgeTiersBuilder {
679        EdgeTiersBuilder::default()
680    }
681
682    /// The rules served at `GET /awp/v2/trust`.
683    pub fn published_rules(&self) -> &TrustRules {
684        &self.published
685    }
686
687    /// The rules applied, published and private.
688    pub fn rules(&self) -> &TrustRules {
689        &self.rules
690    }
691
692    /// The rate class of the highest rule `requester` matches.
693    fn rate_class_for(&self, requester: &RequesterId) -> Option<String> {
694        self.rules
695            .rules
696            .iter()
697            .filter(|rule| rule.matches(requester))
698            .max_by_key(|rule| rule.tier)
699            .and_then(|rule| rule.rate_class.clone())
700    }
701
702    /// Assesses a request: its tier, requester and limit key, or the refusal of a credential
703    /// that failed a check (AWP 2.0 §6.4).
704    ///
705    /// # Errors
706    ///
707    /// [`EdgeRefusal`] when a presented credential fails verification.
708    pub async fn assess(&self, head: &Parts) -> Result<EdgeCaller, EdgeRefusal> {
709        let mut best: Option<(TrustTier, RequesterId)> = None;
710        let mut unverifiable: Option<String> = None;
711        for verifier in &self.verifiers {
712            match verifier.verify(head).await {
713                CredentialCheck::Absent => {}
714                CredentialCheck::Failed { reason } => {
715                    tracing::info!(
716                        awp.identity = ?verifier.method(),
717                        reason = %reason,
718                        "awp.request.refused: a credential failed verification"
719                    );
720                    return Err(EdgeRefusal { method: verifier.method(), reason });
721                }
722                CredentialCheck::Unverifiable { digest, reason } => {
723                    tracing::info!(
724                        awp.identity = ?verifier.method(),
725                        reason = %reason,
726                        "awp request credential could not be verified; serving as public"
727                    );
728                    unverifiable.get_or_insert(digest);
729                }
730                CredentialCheck::Verified(credential) => {
731                    let mut tier = credential.granted.unwrap_or(TrustTier::Known);
732                    if self.verified_issuers.contains(&credential.issuer) {
733                        tier = tier.max(TrustTier::Verified);
734                    }
735                    tier = tier.max(self.rules.tier_for(&credential.requester));
736                    if best.as_ref().is_none_or(|(current, _)| tier > *current) {
737                        best = Some((tier, credential.requester));
738                    }
739                }
740            }
741        }
742        let claimed = claimed_agent(&head.headers);
743        Ok(match best {
744            Some((tier, requester)) => {
745                tracing::debug!(awp.requester = %requester.as_str(), awp.tier = %tier, "awp.request.verified");
746                EdgeCaller {
747                    tier,
748                    rate_class: self.rate_class_for(&requester),
749                    limit_key: format!("id:{}", requester.as_str()),
750                    requester: Some(requester),
751                    claimed_agent: claimed,
752                    visitor: None,
753                }
754            }
755            None => {
756                let limit_key = match unverifiable {
757                    Some(digest) => format!("cred:{digest}"),
758                    None => head.extensions.get::<ConnectInfo<SocketAddr>>().map_or_else(
759                        || "ip:unknown".to_owned(),
760                        |info| format!("ip:{}", info.0.ip()),
761                    ),
762                };
763                EdgeCaller { claimed_agent: claimed, ..EdgeCaller::public(limit_key) }
764            }
765        })
766    }
767}
768
769#[async_trait]
770impl TierAssigner for EdgeTiers {
771    /// Reads the edge's assessment from the request's extensions, else assesses the request;
772    /// a refused credential is `public` here, as the edge refuses the request before any route.
773    async fn assign(&self, head: &Parts) -> TierAssignment {
774        if let Some(caller) = head.extensions.get::<EdgeCaller>() {
775            return caller.assignment();
776        }
777        match self.assess(head).await {
778            Ok(caller) => caller.assignment(),
779            Err(_) => TierAssignment::public(),
780        }
781    }
782}