Skip to main content

bynk_check/
actors.rs

1//! v0.45 actor contracts (the actors-foundations slice).
2//!
3//! An `actor` declaration is a nominal *boundary contract* (ADR Q1): a closed,
4//! compiler-known authentication `Scheme` plus an optional sealed identity. A
5//! handler consumes an actor on its `by` clause; the boundary verifies the
6//! scheme and mints the identity before the body runs (two-phase, fail-closed —
7//! ADR Q5/Q2).
8//!
9//! This module holds the compiler-known parts: the closed scheme set, the
10//! prelude actors, the per-protocol default actors, and the admissible-scheme
11//! sets. Foundations admits only the two zero-crypto schemes (`None`,
12//! `Internal`); `Bearer`/`Signature` are reserved-and-rejected.
13
14use std::collections::{BTreeSet, HashMap};
15
16use bynk_syntax::ast::{
17    BinOp, ByClause, Expr, ExprKind, Handler, HandlerKind, ServiceProtocol, TypeRef, UnaryOp,
18};
19use bynk_syntax::span::Span;
20
21/// P6.49 (design/tracks/the-ir.md §6b), following P6.27's `ExprId` precedent:
22/// every reader in this module — [`bearer_seam_for`], [`oidc_seam_for`],
23/// [`signature_seam_for`], [`sum_members_for`], [`caller_binder_for`] — is
24/// already parameterised by `&HashMap<String, ActorDecl>`. `bynk-emit` clones
25/// and forwards this table (`project.rs`'s `EmitProjectCtx::actors`,
26/// `emitter/workers.rs`/`workers_entry.rs`'s own `actors` parameters) without
27/// ever reading an `ActorDecl` field itself — P6.34 investigated and declined
28/// resolving it earlier, since `bynk-emit`'s own `lower_actor_seam_ir` needs
29/// the raw declarations to do its own resolution; this re-export changes the
30/// import path, not that data flow.
31pub use bynk_syntax::ast::ActorDecl;
32
33/// The authentication scheme — a closed, compiler-known set (ADR Q1). Sealed
34/// now, openable later by widening this enum.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Scheme {
37    /// Anonymous — no verification; identity is `()`. (`Visitor`.)
38    None,
39    /// In-system / platform trust — the channel itself is the assertion
40    /// (service-binding / platform dispatch). Admitted in Foundations.
41    Internal,
42    /// Bearer token — compiler-generated JWT/HS256 verification (ADR 0085).
43    Bearer,
44    /// Request signature — HMAC-SHA256 over the body (ADR 0089).
45    Signature,
46    /// OIDC/JWKS — compiler-generated verification of an asymmetrically-signed
47    /// (RS256/ES256) JWT against a provider's published JWKS, checking
48    /// `iss`/`aud`/`exp`/`nbf` and minting the identity from `sub` (ADR 0175).
49    /// The first scheme opened via the "user-configured verifier" route: the
50    /// trust root is the provider's public key set (a URL), so the declaration
51    /// carries **no inline secret** — only public trust parameters.
52    Oidc,
53    /// I3 (#1971, interop track D2): a caller that is not Bynk, declared by the
54    /// context it calls (`auth = Foreign(secret = "LEGACY_CALL_KEY")`). It signs
55    /// a call like a Bynk caller does (`bynk_check::wire_format`), naming
56    /// itself by the actor's name, under the declared secret. Admitted on
57    /// `call` only, and resolves to its own actor, never to `Caller`.
58    Foreign,
59    /// #3386: a signed, expiring session cookie that Bynk both issues and
60    /// verifies (HMAC-SHA-256 over a compact JWS). A browser credential, so
61    /// HTTP only; single-actor only in the first slice (like `Oidc`).
62    SignedCookie,
63}
64
65impl Scheme {
66    /// Classify a scheme name written in `auth = <Scheme>`. `None` means the
67    /// name is not one of the compiler-known schemes.
68    pub fn from_name(s: &str) -> Option<Scheme> {
69        Some(match s {
70            "None" => Scheme::None,
71            "Internal" => Scheme::Internal,
72            "Bearer" => Scheme::Bearer,
73            "Signature" => Scheme::Signature,
74            "Oidc" => Scheme::Oidc,
75            "Foreign" => Scheme::Foreign,
76            "SignedCookie" => Scheme::SignedCookie,
77            _ => return None,
78        })
79    }
80
81    /// The schemes the compiler can emit verification for. v0.45 admitted the
82    /// two zero-crypto schemes (`None`/`Internal`); v0.47 added `Bearer`
83    /// (JWT/HS256); v0.51 added `Signature` (HMAC over the body); v0.151 adds
84    /// `Oidc` (JWKS/RS256+ES256). All five schemes are now admitted.
85    pub fn admitted(self) -> bool {
86        matches!(
87            self,
88            Scheme::None
89                | Scheme::Internal
90                | Scheme::Bearer
91                | Scheme::Signature
92                | Scheme::Oidc
93                | Scheme::Foreign
94                | Scheme::SignedCookie
95        )
96    }
97
98    pub fn as_str(self) -> &'static str {
99        match self {
100            Scheme::None => "None",
101            Scheme::Internal => "Internal",
102            Scheme::Bearer => "Bearer",
103            Scheme::Signature => "Signature",
104            Scheme::Oidc => "Oidc",
105            Scheme::Foreign => "Foreign",
106            Scheme::SignedCookie => "SignedCookie",
107        }
108    }
109}
110
111/// The identity a verified actor yields (ADR Q2). In Foundations this is `()`
112/// for trivial actors, the built-in sealed `CallerId` for the cross-context
113/// `Internal` channel (Q7, folded in), or a context-owned declared type.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum Identity {
116    /// `()` — `None` actors and platform-tag `Internal` actors.
117    Unit,
118    /// The built-in sealed calling-context identity (Q7). Minted at the
119    /// service-binding seam; read-only and never re-checked.
120    CallerId,
121    /// A context-owned declared type named in `identity = <T>`.
122    Declared(String),
123}
124
125/// The built-in sealed identity type for the cross-context calling principal.
126pub const CALLER_ID: &str = "CallerId";
127
128/// The first-party record `Sender` yields (#3328): `{ address: String, dmarc:
129/// DmarcVerdict }`, exported by `bynk.cloudflare`.
130pub const SENDER_IDENTITY: &str = "SenderIdentity";
131
132/// A resolved actor contract: its scheme and the identity it yields.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Contract {
135    pub scheme: Scheme,
136    pub identity: Identity,
137}
138
139/// The prelude actors — compiler-known boundary contracts available without a
140/// declaration. They back the per-protocol defaults and let public HTTP routes
141/// write `by v: Visitor` without ceremony.
142pub fn prelude_actor(name: &str) -> Option<Contract> {
143    Some(match name {
144        // Anonymous public surface — the only safe HTTP actor in Foundations.
145        "Visitor" => Contract {
146            scheme: Scheme::None,
147            identity: Identity::Unit,
148        },
149        // Platform schedulers / producers — Internal, carrying no useful
150        // identity payload (a bare tag).
151        "Scheduler" | "Producer" => Contract {
152            scheme: Scheme::Internal,
153            identity: Identity::Unit,
154        },
155        // #3328 (DECISION E): the inbound-mail sender — Internal (the platform
156        // delivers and authenticates the mail before the handler runs),
157        // yielding the first-party `SenderIdentity` (envelope address plus the
158        // DMARC verdict) when a handler binds it with `by s: Sender`.
159        "Sender" => Contract {
160            scheme: Scheme::Internal,
161            identity: Identity::Declared(SENDER_IDENTITY.to_string()),
162        },
163        // The cross-context calling principal — Internal, yielding the sealed
164        // `CallerId` (Q7).
165        "Caller" => Contract {
166            scheme: Scheme::Internal,
167            identity: Identity::CallerId,
168        },
169        _ => return None,
170    })
171}
172
173/// The default actor a handler inherits when it omits `by`, by protocol (ADR
174/// Q5). HTTP and WebSocket have no safe default — `by` is required there — and
175/// neither has `call` (#3891, superseding ADR 0082's `Caller` default).
176pub fn default_actor(protocol: &ServiceProtocol) -> Option<&'static str> {
177    match protocol {
178        ServiceProtocol::Cron => Some("Scheduler"),
179        ServiceProtocol::Queue { .. } => Some("Producer"),
180        // #3328 (DECISION E): inbound mail's default actor is the envelope
181        // sender, carrying its address and the platform's DMARC verdict.
182        ServiceProtocol::Email { .. } => Some("Sender"),
183        // Events track, slice 0 (spine #936): delivery is runtime-triggered,
184        // not an external caller — like `Queue`'s "Producer", the default
185        // actor names the event's originating publisher.
186        ServiceProtocol::Events { .. } => Some("Publisher"),
187        // v0.103: like HTTP, a WebSocket upgrade has no safe default actor —
188        // `by` is mandatory on `on open` (edge auth before accept, D-A).
189        ServiceProtocol::Call | ServiceProtocol::Http | ServiceProtocol::WebSocket { .. } => None,
190    }
191}
192
193/// v0.47: the data the emitter needs to lower a Bearer verification seam for a
194/// handler — the `by` binder (v0.50: `None` for the binder-less verify-and-
195/// discard form), the signing-secret env name, and the identity type to
196/// construct from the JWT `sub` claim. Resolved only for a handler whose `by`
197/// clause names a local Bearer actor; the checker guarantees the secret is
198/// present and the identity is a string-constructible local type.
199#[derive(Debug, Clone)]
200pub struct BearerSeam {
201    /// The identity binder, or `None` for `by <BearerActor>` (verify the token,
202    /// don't capture the identity). When `None` the seam still verifies fail-
203    /// closed but mints no identity and threads nothing into `deps`.
204    pub binder: Option<String>,
205    pub secret: String,
206    pub identity_type: String,
207    /// v0.53: the authorisation invariant when the `by` actor is a refinement
208    /// (`actor Admin = User where <pred>`). The seam verifies the scheme (401),
209    /// then checks this predicate against the verified claims (403 fail-closed),
210    /// then mints the (base) identity. `None` for a plain Bearer actor.
211    pub authorization: Option<ClaimPredicate>,
212}
213
214/// Resolve a handler's Bearer seam, if its `by` clause names a local Bearer
215/// actor — or a **refinement** of one (v0.53), following the refinement to its
216/// base for the scheme/secret/identity and carrying the authorisation
217/// predicate. Returns `None` for non-Bearer handlers (prelude actors are never
218/// Bearer) — those emit unchanged.
219/// #706: whether a `by` clause names a **Bearer**-secured actor (following a
220/// refinement to its base). The routes for which `by Nobody` can drive the auth
221/// seam to a `401` — an unsecured (`Visitor`/`None`) or `Signature`/`Oidc` route
222/// has no Bearer seam the test driver knows how to leave unauthenticated, so
223/// `by Nobody` there is rejected (`bynk.test.nobody_needs_secured_route`). The
224/// scheme check mirrors [`bearer_seam_for`].
225pub fn by_clause_is_bearer(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
226    let Some(named) = actors.get(&by.primary().name) else {
227        return false;
228    };
229    let base = match &named.refinement {
230        Some(r) => match actors.get(&r.base.name) {
231            Some(b) => b,
232            None => return false,
233        },
234        None => named,
235    };
236    base.auth
237        .as_ref()
238        .and_then(|a| Scheme::from_name(a.name.as_str()))
239        == Some(Scheme::Bearer)
240}
241
242/// #3052: whether a `by` clause names a single local `Oidc` actor (an `Oidc`
243/// actor is never a sum member or a refinement base), so the `system` driver
244/// can mint a token for it and its seam refuses a bad one.
245pub fn by_clause_is_oidc(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
246    !by.is_sum()
247        && actors
248            .get(&by.primary().name)
249            .and_then(|a| a.auth.as_ref())
250            .and_then(|a| Scheme::from_name(a.name.as_str()))
251            == Some(Scheme::Oidc)
252}
253
254/// Whether a route's seam refuses a forged or expired credential as a `401`: a `Bearer` route's
255/// token, or (#3386) a `SignedCookie` route's cookie.
256pub fn route_refuses_bad_token(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
257    route_has_bearer_seam(by, actors) || by_clause_is_signed_cookie(by, actors)
258}
259
260/// #3386: whether a `by` clause names a single local `SignedCookie` actor (never a sum member), so
261/// the `system` driver can mint a session cookie for it and its seam refuses a bad one.
262pub fn by_clause_is_signed_cookie(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
263    !by.is_sum()
264        && actors
265            .get(&by.primary().name)
266            .and_then(|a| a.auth.as_ref())
267            .and_then(|a| Scheme::from_name(a.name.as_str()))
268            == Some(Scheme::SignedCookie)
269}
270
271pub fn bearer_seam_for(
272    handler: &Handler,
273    actors: &HashMap<String, ActorDecl>,
274) -> Option<BearerSeam> {
275    let by = handler.by_clause.as_ref()?;
276    let named = actors.get(&by.primary().name)?;
277    // Follow a refinement to its base; carry the authorisation predicate. The
278    // checker guarantees a refinement's base is Bearer and its predicate parses.
279    let (base, authorization) = match &named.refinement {
280        Some(r) => (
281            actors.get(&r.base.name)?,
282            parse_claim_predicate(&r.predicate).ok(),
283        ),
284        None => (named, None),
285    };
286    if Scheme::from_name(base.auth.as_ref()?.name.as_str()) != Some(Scheme::Bearer) {
287        return None;
288    }
289    let secret = base.scheme_arg("secret")?.value.as_str()?.to_string();
290    let TypeRef::Named(id) = base.identity.as_ref()? else {
291        return None;
292    };
293    Some(BearerSeam {
294        binder: by.binder.as_ref().map(|b| b.name.clone()),
295        secret,
296        identity_type: id.name.clone(),
297        authorization,
298    })
299}
300
301/// The cookie name a `SignedCookie` actor issues and reads when `cookie` is not given.
302pub const SIGNED_COOKIE_DEFAULT_NAME: &str = "__Host-session";
303
304/// #3386: the data the emitter needs to lower a `SignedCookie` verification seam:
305/// the `by` binder, the actor's name (the cookie's `aud`), the cookie's name, the
306/// signing and previous-key env names, the `ttl` in seconds and the identity type
307/// minted from the verified `sub`. Resolved only for a handler whose `by` clause
308/// names a single local `SignedCookie` actor (it is never a sum member or a
309/// refinement base); the checker guarantees the secret and `ttl` are present and
310/// the identity is a string-constructible local type.
311#[derive(Debug, Clone)]
312pub struct SignedCookieSeam {
313    /// The identity binder, or `None` for `by <Actor>` (verify, capture nothing).
314    pub binder: Option<String>,
315    /// The declaring actor's name: the cookie's `aud`.
316    pub actor: String,
317    /// The cookie's name.
318    pub cookie: String,
319    /// The env var holding the signing key.
320    pub secret: String,
321    /// The env var holding the key being rotated out, when declared.
322    pub previous: Option<String>,
323    /// How long an issued cookie is valid, in seconds.
324    pub ttl_secs: i64,
325    /// The context-owned, string-constructible identity type minted from `sub`.
326    pub identity_type: String,
327    /// The cookie's `SameSite`: `Lax` (the default), `Strict` or `Unrestricted`.
328    pub same_site: String,
329}
330
331/// Resolve a handler's `SignedCookie` seam, if its `by` clause names a single
332/// local `SignedCookie` actor.
333pub fn signed_cookie_seam_for(
334    handler: &Handler,
335    actors: &HashMap<String, ActorDecl>,
336) -> Option<SignedCookieSeam> {
337    let by = handler.by_clause.as_ref()?;
338    if by.is_sum() {
339        return None;
340    }
341    let actor = actors.get(&by.primary().name)?;
342    signed_cookie_seam_of(actor, by.binder.as_ref().map(|b| b.name.clone()))
343}
344
345/// The seam of one `SignedCookie` actor declaration (shared by the handler
346/// resolver and by an actor's `issue`/`expire` members).
347pub fn signed_cookie_seam_of(
348    actor: &ActorDecl,
349    binder: Option<String>,
350) -> Option<SignedCookieSeam> {
351    if Scheme::from_name(actor.auth.as_ref()?.name.as_str()) != Some(Scheme::SignedCookie) {
352        return None;
353    }
354    let secret = actor.scheme_arg("secret")?.value.as_str()?.to_string();
355    let ttl_ms = actor.scheme_arg("ttl")?.value.as_duration_millis()?;
356    let TypeRef::Named(id) = actor.identity.as_ref()? else {
357        return None;
358    };
359    Some(SignedCookieSeam {
360        binder,
361        actor: actor.name.name.clone(),
362        cookie: actor
363            .scheme_arg("cookie")
364            .and_then(|a| a.value.as_str())
365            .unwrap_or(SIGNED_COOKIE_DEFAULT_NAME)
366            .to_string(),
367        secret,
368        previous: actor
369            .scheme_arg("previous")
370            .and_then(|a| a.value.as_str())
371            .map(str::to_string),
372        ttl_secs: ttl_ms / 1000,
373        identity_type: id.name.clone(),
374        same_site: actor
375            .scheme_arg("sameSite")
376            .and_then(|a| a.value.as_ident())
377            .unwrap_or("Lax")
378            .to_string(),
379    })
380}
381
382/// v0.151: the data the emitter needs to lower an OIDC/JWKS verification seam —
383/// the `by` binder (or `None` for the verify-and-discard form), the public
384/// trust parameters (`issuer`, `audience`, `jwks` URL), and the identity type
385/// to construct from the verified `sub` claim. Resolved only for a handler
386/// whose `by` clause names a local `Oidc` actor. Unlike Bearer/Signature, the
387/// seam carries **no secret env name** — the trust root is the provider's
388/// published public key set (`jwks`).
389#[derive(Debug, Clone)]
390pub struct OidcSeam {
391    /// The identity binder, or `None` for `by <OidcActor>` (verify, don't
392    /// capture the identity). When `None` the seam still verifies fail-closed
393    /// but mints no identity and threads nothing into `deps`.
394    pub binder: Option<String>,
395    /// The expected `iss` claim (and the provider whose JWKS anchors trust).
396    pub issuer: String,
397    /// The expected `aud` claim (this API's audience identifier).
398    pub audience: String,
399    /// The JWKS endpoint URL the verifier fetches signing keys from.
400    pub jwks: String,
401    /// The context-owned, string-constructible identity type minted from `sub`.
402    pub identity_type: String,
403    /// #2380 (L5): the environment variable whose JSON, when set, overrides
404    /// `issuer`/`audience`/`jwks` at run time.
405    pub trust_from: Option<String>,
406}
407
408/// Resolve a handler's OIDC seam, if its `by` clause names a single local
409/// `Oidc` actor. Returns `None` for non-Oidc handlers, for a multi-actor `by`
410/// clause (Oidc is single-actor this slice), and for a refinement (refinement
411/// over Oidc is a later slice) — those follow the existing seam paths. The
412/// checker guarantees `issuer`/`audience`/`jwks` are present and the identity
413/// is a string-constructible local type.
414pub fn oidc_seam_for(handler: &Handler, actors: &HashMap<String, ActorDecl>) -> Option<OidcSeam> {
415    let by = handler.by_clause.as_ref()?;
416    if by.is_sum() {
417        return None;
418    }
419    let actor = actors.get(&by.primary().name)?;
420    // A refinement's `auth` is `None`; it falls through here and follows the
421    // Bearer refinement path (or is rejected). An Oidc base is not narrowed.
422    if Scheme::from_name(actor.auth.as_ref()?.name.as_str()) != Some(Scheme::Oidc) {
423        return None;
424    }
425    let issuer = actor.scheme_arg("issuer")?.value.as_str()?.to_string();
426    let audience = actor.scheme_arg("audience")?.value.as_str()?.to_string();
427    let jwks = actor.scheme_arg("jwks")?.value.as_str()?.to_string();
428    let TypeRef::Named(id) = actor.identity.as_ref()? else {
429        return None;
430    };
431    Some(OidcSeam {
432        binder: by.binder.as_ref().map(|b| b.name.clone()),
433        issuer,
434        audience,
435        jwks,
436        identity_type: id.name.clone(),
437        trust_from: actor
438            .scheme_arg("trustFrom")
439            .and_then(|a| a.value.as_str())
440            .map(str::to_string),
441    })
442}
443
444/// v0.54: the binder of a cross-context `on call … by c: Caller` handler that
445/// captures a live `CallerId` (the calling context's name, Q7). `None` unless
446/// the handler binds an identity whose contract is `CallerId` — i.e. the
447/// `Caller` prelude actor (the only source of `CallerId`). A binder-less
448/// `on call` (or one inheriting the `Caller` default) captures nothing and is
449/// unaffected.
450pub fn caller_binder_for(handler: &Handler, actors: &HashMap<String, ActorDecl>) -> Option<String> {
451    // `CallerId` is a cross-context `on call` concept; the checker rejects a
452    // `Caller` actor on other protocols (`scheme_not_admissible`), but guard here
453    // too so the caller seam is never emitted off the call path.
454    if !matches!(handler.kind, HandlerKind::Call) {
455        return None;
456    }
457    let by = handler.by_clause.as_ref()?;
458    // I3 (#1971): a sum (`by who: Caller | Legacy`) binds the resolved actor,
459    // not a `CallerId`, even when `Caller` is its first member
460    // ([`call_admission_for`]).
461    if by.is_sum() {
462        return None;
463    }
464    let binder = by.binder.as_ref()?;
465    let name = &by.primary().name;
466    // `CallerId` is yielded only by the `Caller` prelude actor; a local actor
467    // never declares it. A binder that collides with a param is suppressed
468    // upstream, mirroring the other seams.
469    // #3890: a refinement over `Caller` yields the same `CallerId`.
470    let is_caller = (!actors.contains_key(name)
471        && prelude_actor(name).map(|c| c.identity) == Some(Identity::CallerId)
472        || actors
473            .get(name)
474            .is_some_and(|d| caller_refinement(d, actors).is_some()))
475        && !handler.params.iter().any(|p| p.name.name == binder.name);
476    is_caller.then(|| binder.name.clone())
477}
478
479/// #3328: the binder of a `from email` handler that captures the minted
480/// `SenderIdentity` — `by s: Sender`, or `None` for a binder-less handler or a
481/// handler that inherits the default (which captures nothing). `Sender` is a
482/// prelude actor (a local actor of the same name is its own), and is admissible
483/// only on `from email`, so the handler kind decides.
484pub fn sender_binder_for(handler: &Handler, actors: &HashMap<String, ActorDecl>) -> Option<String> {
485    if !matches!(handler.kind, HandlerKind::Message) {
486        return None;
487    }
488    let by = handler.by_clause.as_ref()?;
489    if by.is_sum() {
490        return None;
491    }
492    let binder = by.binder.as_ref()?;
493    let name = &by.primary().name;
494    (name == "Sender"
495        && !actors.contains_key(name)
496        && !handler.params.iter().any(|p| p.name.name == binder.name))
497    .then(|| binder.name.clone())
498}
499
500/// I3 (#1971): a declared foreign caller, as a `call` handler admits it: the
501/// actor's name, which the caller sends as `X-Bynk-Caller`, and the secret
502/// the callee verifies its signature under.
503#[derive(Debug, Clone, PartialEq, Eq)]
504pub struct ForeignCaller {
505    pub actor: String,
506    pub secret: String,
507    /// The foreign Worker's name, when the declaration gives one
508    /// (`worker = "ledger-svc"`), so `bynk deploy`'s hand-off can name it.
509    pub worker: Option<String>,
510}
511
512/// I3 (#1971): the foreign caller an actor declaration describes, if it is a
513/// `Foreign`-scheme actor with a `secret`.
514pub fn foreign_caller_of(decl: &ActorDecl) -> Option<ForeignCaller> {
515    (Scheme::from_name(decl.auth.as_ref()?.name.as_str())? == Scheme::Foreign).then_some(())?;
516    Some(ForeignCaller {
517        actor: decl.name.name.clone(),
518        secret: decl.scheme_arg("secret")?.value.as_str()?.to_string(),
519        worker: decl
520            .scheme_arg("worker")
521            .and_then(|a| a.value.as_str())
522            .map(str::to_string),
523    })
524}
525
526/// I3 (#1971): which verified callers an `on call` handler admits. Every call
527/// is authenticated before it reaches a handler (`wire_format`); this is what
528/// the handler then admits, in its `by` clause's order. A Bynk context is
529/// admitted by `Caller` (the default with no `by`) or a local `Internal`
530/// actor; a foreign caller only by its own `Foreign` actor, never by `Caller`.
531#[derive(Debug, Clone, PartialEq, Eq)]
532pub struct CallAdmission {
533    /// Whether a Bynk context is admitted.
534    pub contexts: bool,
535    /// #3890: when contexts are admitted only by a refinement over `Caller`
536    /// (`actor Admin = Caller where IsContext(…)`), its predicate. `None` with
537    /// `contexts` set admits every context. A handler has at most one
538    /// `Internal` member, so one predicate is enough.
539    pub caller_predicate: Option<CallerPredicate>,
540    /// The foreign callers admitted, in `by` order.
541    pub foreign: Vec<ForeignCaller>,
542    /// For a sum, the members in `by` order: `None` for the member that
543    /// admits a context (`Caller`), the foreign caller otherwise. The body's
544    /// `match` reads the resolved one.
545    pub sum: Option<Vec<CallSumMember>>,
546}
547
548/// I3 (#1971): one member of a `call` handler's actor sum.
549#[derive(Debug, Clone, PartialEq, Eq)]
550pub enum CallSumMember {
551    /// `Caller`: a Bynk context, with its name as the identity.
552    Caller,
553    /// A declared foreign caller, with no identity beyond its actor.
554    Foreign(ForeignCaller),
555    /// #3890: a refinement over `Caller`: a Bynk context the predicate admits,
556    /// with its name as the identity, tagged by the refinement's name.
557    Refined(String, CallerPredicate),
558}
559
560impl CallSumMember {
561    /// The member's tag, the actor's name.
562    pub fn actor_name(&self) -> &str {
563        match self {
564            CallSumMember::Caller => "Caller",
565            CallSumMember::Foreign(f) => &f.actor,
566            CallSumMember::Refined(name, _) => name,
567        }
568    }
569}
570
571impl CallAdmission {
572    /// #3890: the tag the resolved `Internal` member carries in a sum: the
573    /// refinement's name, or `Caller`.
574    pub fn internal_tag(&self) -> &str {
575        self.sum
576            .iter()
577            .flatten()
578            .find_map(|m| match m {
579                CallSumMember::Refined(name, _) => Some(name.as_str()),
580                _ => None,
581            })
582            .unwrap_or("Caller")
583    }
584}
585
586/// I3 (#1971): what an `on call` handler admits. `None` off the call path.
587pub fn call_admission_for(
588    handler: &Handler,
589    actors: &HashMap<String, ActorDecl>,
590) -> Option<CallAdmission> {
591    if !matches!(handler.kind, HandlerKind::Call) {
592        return None;
593    }
594    let Some(by) = handler.by_clause.as_ref() else {
595        return Some(CallAdmission {
596            contexts: true,
597            caller_predicate: None,
598            foreign: Vec::new(),
599            sum: None,
600        });
601    };
602    let mut admission = CallAdmission {
603        contexts: false,
604        caller_predicate: None,
605        foreign: Vec::new(),
606        sum: None,
607    };
608    let mut members = Vec::new();
609    for actor in &by.actors {
610        match actors.get(&actor.name) {
611            // Classified by scheme, not by whether the declaration is whole:
612            // a malformed `Foreign` actor (the checker reports it) admits
613            // nobody, rather than falling through to admit contexts.
614            Some(decl)
615                if decl.auth.as_ref().and_then(|a| Scheme::from_name(&a.name))
616                    == Some(Scheme::Foreign) =>
617            {
618                if let Some(f) = foreign_caller_of(decl) {
619                    admission.foreign.push(f.clone());
620                    members.push(CallSumMember::Foreign(f));
621                }
622            }
623            // #3890: a refinement over `Caller` admits the contexts its
624            // predicate admits.
625            Some(decl) if caller_refinement(decl, actors).is_some() => {
626                let pred = caller_refinement(decl, actors).expect("checked above");
627                admission.contexts = true;
628                admission.caller_predicate = Some(pred.clone());
629                members.push(CallSumMember::Refined(actor.name.clone(), pred));
630            }
631            Some(_) => {
632                admission.contexts = true;
633                members.push(CallSumMember::Caller);
634            }
635            None => {
636                admission.contexts = true;
637                members.push(CallSumMember::Caller);
638            }
639        }
640    }
641    if by.is_sum() {
642        admission.sum = Some(members);
643    }
644    Some(admission)
645}
646
647/// v0.51: the data the emitter needs to lower a Signature verification seam —
648/// the signing-secret env name, the signature header, and an optional
649/// timestamp header + tolerance window for replay defence. Resolved only for a
650/// handler whose `by` clause names a local Signature actor.
651#[derive(Debug, Clone)]
652pub struct SignatureSeam {
653    pub secret: String,
654    pub header: String,
655    pub timestamp_header: Option<String>,
656    pub tolerance_secs: Option<i64>,
657}
658
659/// Resolve a handler's Signature seam, if its `by` clause names a local
660/// Signature actor. The checker guarantees `secret` and `header` are present.
661pub fn signature_seam_for(
662    handler: &Handler,
663    actors: &HashMap<String, ActorDecl>,
664) -> Option<SignatureSeam> {
665    signature_seam_for_by(handler.by_clause.as_ref()?, actors)
666}
667
668/// #2155: the `Signature` seam a `by` clause's route is signed with at the
669/// `system` tier — its one actor's, or an actor sum's first `Signature`
670/// member's (what `by Forged`/`by Stale` sign as). `None` when it has none,
671/// and for a sum with an open member ([`sum_has_open_member`]), whose seam
672/// never refuses a bad signature.
673pub fn signature_seam_of_route(
674    by: &ByClause,
675    actors: &HashMap<String, ActorDecl>,
676) -> Option<SignatureSeam> {
677    if !by.is_sum() {
678        return signature_seam_for_by(by, actors);
679    }
680    if sum_has_open_member(by, actors) {
681        return None;
682    }
683    by.actors.iter().find_map(|a| {
684        let decl = actors.get(&a.name)?;
685        (Scheme::from_name(decl.auth.as_ref()?.name.as_str()) == Some(Scheme::Signature))
686            .then(|| signature_seam_from_decl(decl))
687            .flatten()
688    })
689}
690
691/// #2864: whether a `by` clause's route has a `Bearer` seam the `system`
692/// driver can forge or expire a token for — a lone Bearer actor (or a
693/// refinement of one), or an actor sum with a Bearer member and no open
694/// member ([`sum_has_open_member`]), whose seam never refuses a bad token.
695pub fn route_has_bearer_seam(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
696    if !by.is_sum() {
697        return by_clause_is_bearer(by, actors);
698    }
699    if sum_has_open_member(by, actors) {
700        return false;
701    }
702    by.actors.iter().any(|a| {
703        actors
704            .get(&a.name)
705            .and_then(|d| d.auth.as_ref())
706            .and_then(|auth| Scheme::from_name(auth.name.as_str()))
707            == Some(Scheme::Bearer)
708    })
709}
710
711/// #2155: whether a `by` clause's route has a credential seam the `system`
712/// driver can leave out (`by Nobody`): a Bearer actor (or a refinement of
713/// one), an `Oidc` actor (#3052), a `Signature` actor, or an actor sum with such a member and no open
714/// member ([`sum_has_open_member`]).
715pub fn route_is_secured(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
716    if !by.is_sum() {
717        return by_clause_is_bearer(by, actors)
718            || by_clause_is_oidc(by, actors)
719            || by_clause_is_signed_cookie(by, actors)
720            || signature_seam_for_by(by, actors).is_some();
721    }
722    if sum_has_open_member(by, actors) {
723        return false;
724    }
725    by.actors.iter().any(|a| {
726        actors
727            .get(&a.name)
728            .and_then(|d| d.auth.as_ref())
729            .and_then(|auth| Scheme::from_name(auth.name.as_str()))
730            .is_some_and(|s| matches!(s, Scheme::Bearer | Scheme::Signature))
731    })
732}
733
734/// #2155: whether an actor sum has an *open* member — `Visitor`, or a
735/// declared actor with no auth scheme. The sum's seam resolves a request with
736/// a missing or bad credential as that member, so it never answers `401`:
737/// `by Nobody`, `by Forged` and `by Stale` have nothing to drive there.
738pub fn sum_has_open_member(by: &ByClause, actors: &HashMap<String, ActorDecl>) -> bool {
739    by.actors.iter().any(|a| match actors.get(&a.name) {
740        // A refinement narrows a secured base, so it is never open.
741        Some(decl) if decl.refinement.is_some() => false,
742        Some(decl) => decl
743            .auth
744            .as_ref()
745            .and_then(|auth| Scheme::from_name(auth.name.as_str()))
746            .is_none_or(|s| s == Scheme::None),
747        None => prelude_actor(&a.name).is_some_and(|c| c.scheme == Scheme::None),
748    })
749}
750
751/// #2135: [`signature_seam_for`] from the `by` clause alone — the seam of
752/// its primary actor, when that is a local Signature actor.
753pub fn signature_seam_for_by(
754    by: &ByClause,
755    actors: &HashMap<String, ActorDecl>,
756) -> Option<SignatureSeam> {
757    let actor = actors.get(&by.primary().name)?;
758    if Scheme::from_name(actor.auth.as_ref()?.name.as_str()) != Some(Scheme::Signature) {
759        return None;
760    }
761    signature_seam_from_decl(actor)
762}
763
764/// The Signature seam data carried by an actor declaration (its keyed config).
765/// Shared by the single-actor `signature_seam_for` and the multi-actor
766/// `sum_members_for`.
767fn signature_seam_from_decl(actor: &ActorDecl) -> Option<SignatureSeam> {
768    Some(SignatureSeam {
769        secret: actor.scheme_arg("secret")?.value.as_str()?.to_string(),
770        header: actor.scheme_arg("header")?.value.as_str()?.to_string(),
771        timestamp_header: actor
772            .scheme_arg("timestamp")
773            .and_then(|a| a.value.as_str())
774            .map(str::to_string),
775        tolerance_secs: actor.scheme_arg("tolerance").and_then(|a| a.value.as_int()),
776    })
777}
778
779/// v0.52: one resolved member of a multi-actor sum — the seam the emitter tries
780/// at that position in the first-wins order. `actor_name` is the variant tag the
781/// body matches on.
782#[derive(Debug, Clone)]
783pub struct SumMember {
784    pub actor_name: String,
785    pub seam: SumMemberSeam,
786}
787
788/// The verification a sum member contributes. `None` (a catch-all such as
789/// `Visitor`) always resolves, so it terminates the order.
790#[derive(Debug, Clone)]
791pub enum SumMemberSeam {
792    None,
793    Bearer {
794        secret: String,
795        identity_type: String,
796    },
797    Signature(SignatureSeam),
798}
799
800impl SumMember {
801    /// Whether resolving this member needs the raw request body read.
802    pub fn needs_body(&self) -> bool {
803        matches!(self.seam, SumMemberSeam::Signature(_))
804    }
805    /// The member's identity type name, if it mints one (Bearer). `None`/
806    /// Signature members carry a unit identity.
807    pub fn identity_type(&self) -> Option<&str> {
808        match &self.seam {
809            SumMemberSeam::Bearer { identity_type, .. } => Some(identity_type),
810            _ => None,
811        }
812    }
813}
814
815/// v0.52: resolve a handler's `by` clause into ordered sum members, if it names
816/// more than one actor. `None` for a single-actor handler (those keep the
817/// existing seam paths). The checker has already validated peer/scheme/
818/// reachability rules; this lowers the verified members for emission.
819pub fn sum_members_for(
820    handler: &Handler,
821    actors: &HashMap<String, ActorDecl>,
822) -> Option<Vec<SumMember>> {
823    let by = handler.by_clause.as_ref()?;
824    if !by.is_sum() {
825        return None;
826    }
827    let mut members = Vec::new();
828    for actor_ref in &by.actors {
829        let seam = if let Some(decl) = actors.get(&actor_ref.name) {
830            match Scheme::from_name(decl.auth.as_ref()?.name.as_str())? {
831                Scheme::None => SumMemberSeam::None,
832                Scheme::Bearer => {
833                    let secret = decl.scheme_arg("secret")?.value.as_str()?.to_string();
834                    let TypeRef::Named(id) = decl.identity.as_ref()? else {
835                        return None;
836                    };
837                    SumMemberSeam::Bearer {
838                        secret,
839                        identity_type: id.name.clone(),
840                    }
841                }
842                Scheme::Signature => SumMemberSeam::Signature(signature_seam_from_decl(decl)?),
843                // v0.151: `Oidc` is single-actor only this slice — the checker
844                // rejects it as a sum member (`bynk.actor.oidc_not_in_sum`), so
845                // a well-formed program never reaches here with an Oidc peer.
846                // Return `None` (fail closed → no sum emission) defensively.
847                Scheme::Oidc => return None,
848                // I3: a `Foreign` sum is a `call` sum (`call_admission_for`).
849                Scheme::Internal | Scheme::Foreign => return None,
850                // #3386: `SignedCookie` is single-actor only in its first slice
851                // (`bynk.actor.signed_cookie_not_in_sum`), so a well-formed
852                // program never reaches here with one; fail closed.
853                Scheme::SignedCookie => return None,
854            }
855        } else {
856            // A prelude actor: only `Visitor` (scheme `None`) is an HTTP peer.
857            match prelude_actor(&actor_ref.name) {
858                Some(c) if c.scheme == Scheme::None => SumMemberSeam::None,
859                _ => return None,
860            }
861        };
862        members.push(SumMember {
863            actor_name: actor_ref.name.clone(),
864            seam,
865        });
866    }
867    Some(members)
868}
869
870/// Whether `scheme` is admissible on `protocol` (the admissible-scheme-per-
871/// protocol check). HTTP admits `None` (public routes) and `Bearer` (an
872/// `Authorization` header is an HTTP concept); the internal protocols
873/// (call/cron/queue) admit `Internal`. `Signature` is still reserved.
874pub fn scheme_admissible(protocol: &ServiceProtocol, scheme: Scheme) -> bool {
875    match protocol {
876        ServiceProtocol::Http => {
877            matches!(
878                scheme,
879                Scheme::None
880                    | Scheme::Bearer
881                    | Scheme::Signature
882                    | Scheme::Oidc
883                    | Scheme::SignedCookie
884            )
885        }
886        // v0.103 (D-B): a WebSocket upgrade authenticates via `None` (anonymous)
887        // or `Bearer` — but the token is read from the `Sec-WebSocket-Protocol`
888        // subprotocol, since a browser `WebSocket` cannot set an `Authorization`
889        // header. `Signature` is rejected at the WS boundary: HMAC-over-body has
890        // no body on a handshake.
891        ServiceProtocol::WebSocket { .. } => {
892            matches!(scheme, Scheme::None | Scheme::Bearer)
893        }
894        // Events track, slice 0 (spine #936): delivery is an internal,
895        // runtime-triggered invocation, like `Call`/`Cron`/`Queue` — no
896        // external network request, so no external auth scheme applies.
897        // I3 (#1971): a `call` also admits a declared foreign caller.
898        ServiceProtocol::Call => matches!(scheme, Scheme::Internal | Scheme::Foreign),
899        ServiceProtocol::Cron | ServiceProtocol::Queue { .. } | ServiceProtocol::Events { .. } => {
900            matches!(scheme, Scheme::Internal)
901        }
902        // #3328: the platform delivers inbound mail, so the only admitted
903        // scheme is the platform's own (`Internal`), as `Sender` is. A
904        // DMARC-refusing scheme could follow (DECISION E).
905        ServiceProtocol::Email { .. } => matches!(scheme, Scheme::Internal),
906    }
907}
908
909/// v0.53: the closed claim-predicate vocabulary for a refinement actor's `where`
910/// clause (`actor Admin = User where hasClaim("admin")`). Claims are untyped
911/// JSON, so the predicate is a closed set — `hasClaim`/`claimEquals` composed
912/// with `&&`/`||`/`!` — checked against the *verified* JWT claims at the
913/// boundary. A general typed-claims expression surface is a later slice.
914#[derive(Debug, Clone)]
915pub enum ClaimPredicate {
916    /// `hasClaim("name")` — the claim is present and truthy.
917    HasClaim(String),
918    /// `claimEquals("name", "value")` — the claim string-equals `value`.
919    ClaimEquals(String, String),
920    And(Box<ClaimPredicate>, Box<ClaimPredicate>),
921    Or(Box<ClaimPredicate>, Box<ClaimPredicate>),
922    Not(Box<ClaimPredicate>),
923}
924
925fn claim_str_lit(e: &Expr) -> Option<String> {
926    match &e.kind {
927        ExprKind::StrLit(s) => Some(s.clone()),
928        _ => None,
929    }
930}
931
932/// Recognise the closed claim-predicate vocabulary in a refinement `where`
933/// expression. `Err(span)` points at the first sub-expression outside the set
934/// (for `bynk.actor.refinement_predicate_unsupported`).
935pub fn parse_claim_predicate(e: &Expr) -> Result<ClaimPredicate, Span> {
936    match &e.kind {
937        ExprKind::Paren(inner) => parse_claim_predicate(inner),
938        ExprKind::BinOp(BinOp::And, l, r) => Ok(ClaimPredicate::And(
939            Box::new(parse_claim_predicate(l)?),
940            Box::new(parse_claim_predicate(r)?),
941        )),
942        ExprKind::BinOp(BinOp::Or, l, r) => Ok(ClaimPredicate::Or(
943            Box::new(parse_claim_predicate(l)?),
944            Box::new(parse_claim_predicate(r)?),
945        )),
946        ExprKind::UnaryOp(UnaryOp::Not, inner) => {
947            Ok(ClaimPredicate::Not(Box::new(parse_claim_predicate(inner)?)))
948        }
949        ExprKind::Call {
950            name,
951            type_args,
952            args,
953            ..
954        } if type_args.is_empty() => match (name.name.as_str(), args.as_slice()) {
955            ("hasClaim", [a]) => claim_str_lit(a).map(ClaimPredicate::HasClaim).ok_or(a.span),
956            ("claimEquals", [a, b]) => match (claim_str_lit(a), claim_str_lit(b)) {
957                (Some(n), Some(v)) => Ok(ClaimPredicate::ClaimEquals(n, v)),
958                (None, _) => Err(a.span),
959                (_, None) => Err(b.span),
960            },
961            _ => Err(name.span),
962        },
963        _ => Err(e.span),
964    }
965}
966
967/// #3890: the closed predicate vocabulary for a refinement over `Caller`
968/// (`actor Admin = Caller where IsContext(shop.admin)`). `IsContext` is a
969/// fixed, compiler-known check (capitalised, as `Matches` and `NonEmpty` are),
970/// decided at compile time against the project's call graph, and again at run
971/// time on the caller the signature proved. The combinators are the claim
972/// predicates', so `!IsContext(shop.legacy)` reads as a deny-list.
973#[derive(Debug, Clone, PartialEq, Eq)]
974pub enum CallerPredicate {
975    /// `IsContext(a.b, c.d)` — the calling context is one of the named ones.
976    IsContext(Vec<String>),
977    And(Box<CallerPredicate>, Box<CallerPredicate>),
978    Or(Box<CallerPredicate>, Box<CallerPredicate>),
979    Not(Box<CallerPredicate>),
980}
981
982impl CallerPredicate {
983    /// Whether the named calling context passes the predicate.
984    pub fn admits(&self, context: &str) -> bool {
985        match self {
986            CallerPredicate::IsContext(names) => names.iter().any(|n| n == context),
987            CallerPredicate::And(l, r) => l.admits(context) && r.admits(context),
988            CallerPredicate::Or(l, r) => l.admits(context) || r.admits(context),
989            CallerPredicate::Not(inner) => !inner.admits(context),
990        }
991    }
992
993    /// Every context name the predicate mentions, in source order.
994    pub fn mentioned(&self) -> Vec<&str> {
995        match self {
996            CallerPredicate::IsContext(names) => names.iter().map(String::as_str).collect(),
997            CallerPredicate::And(l, r) | CallerPredicate::Or(l, r) => {
998                let mut out = l.mentioned();
999                out.extend(r.mentioned());
1000                out
1001            }
1002            CallerPredicate::Not(inner) => inner.mentioned(),
1003        }
1004    }
1005}
1006
1007/// A qualified name written as an expression: `shop.admin` is a field access
1008/// on an identifier.
1009pub fn dotted_name(e: &Expr) -> Option<String> {
1010    match &e.kind {
1011        ExprKind::Ident(id) => Some(id.name.clone()),
1012        ExprKind::FieldAccess { receiver, field } => {
1013            Some(format!("{}.{}", dotted_name(receiver)?, field.name))
1014        }
1015        _ => None,
1016    }
1017}
1018
1019/// Recognise the `Caller` predicate vocabulary in a refinement `where`
1020/// expression. `Err(span)` points at the first sub-expression outside it (for
1021/// `bynk.actor.refinement_predicate_unsupported`).
1022pub fn parse_caller_predicate(e: &Expr) -> Result<CallerPredicate, Span> {
1023    match &e.kind {
1024        ExprKind::Paren(inner) => parse_caller_predicate(inner),
1025        ExprKind::BinOp(BinOp::And, l, r) => Ok(CallerPredicate::And(
1026            Box::new(parse_caller_predicate(l)?),
1027            Box::new(parse_caller_predicate(r)?),
1028        )),
1029        ExprKind::BinOp(BinOp::Or, l, r) => Ok(CallerPredicate::Or(
1030            Box::new(parse_caller_predicate(l)?),
1031            Box::new(parse_caller_predicate(r)?),
1032        )),
1033        ExprKind::UnaryOp(UnaryOp::Not, inner) => Ok(CallerPredicate::Not(Box::new(
1034            parse_caller_predicate(inner)?,
1035        ))),
1036        ExprKind::Call {
1037            name,
1038            type_args,
1039            args,
1040            ..
1041        } if type_args.is_empty() && name.name == "IsContext" && !args.is_empty() => args
1042            .iter()
1043            .map(|a| dotted_name(a).ok_or(a.span))
1044            .collect::<Result<Vec<_>, _>>()
1045            .map(CallerPredicate::IsContext),
1046        ExprKind::Call { name, .. } => Err(name.span),
1047        _ => Err(e.span),
1048    }
1049}
1050
1051/// #3890: the predicate of a refinement over the prelude `Caller` actor, or
1052/// `None` for any other actor (a malformed predicate reads as `None` too: the
1053/// checker reports it).
1054pub fn caller_refinement(
1055    decl: &ActorDecl,
1056    actors: &HashMap<String, ActorDecl>,
1057) -> Option<CallerPredicate> {
1058    let r = decl.refinement.as_ref()?;
1059    if r.base.name != "Caller" || actors.contains_key("Caller") {
1060        return None;
1061    }
1062    parse_caller_predicate(&r.predicate).ok()
1063}
1064
1065fn js_str_escape(s: &str) -> String {
1066    s.replace('\\', "\\\\").replace('"', "\\\"")
1067}
1068
1069/// #2019: what a witness claim set requires of one claim. Each need is the
1070/// exact set of claim values that meets it, so two needs merge exactly when
1071/// their sets intersect. The excluded strings carried by `Truthy`, `Falsy`
1072/// and `NotEquals` come from negated `claimEquals`.
1073#[derive(Debug, Clone, PartialEq, Eq)]
1074enum ClaimNeed {
1075    /// String-equal to the value (`claimEquals`).
1076    Equals(String),
1077    /// Present and truthy (`hasClaim`), and none of these strings.
1078    Truthy(BTreeSet<String>),
1079    /// Absent or falsy (`!hasClaim`), and none of these strings.
1080    Falsy(BTreeSet<String>),
1081    /// Anything but these strings (`!claimEquals`), absent included.
1082    NotEquals(BTreeSet<String>),
1083}
1084
1085type ClaimSet = std::collections::BTreeMap<String, ClaimNeed>;
1086
1087/// The intersection of two needs on one claim, or `None` when it is empty.
1088fn merge_need(a: &ClaimNeed, b: &ClaimNeed) -> Option<ClaimNeed> {
1089    use ClaimNeed::*;
1090    let union = |x: &BTreeSet<String>, y: &BTreeSet<String>| x.union(y).cloned().collect();
1091    Some(match (a, b) {
1092        (Equals(x), Equals(y)) => (x == y).then(|| Equals(x.clone()))?,
1093        // A non-empty string is truthy; the empty string is falsy.
1094        (Equals(v), Truthy(not)) | (Truthy(not), Equals(v)) => {
1095            (!v.is_empty() && !not.contains(v)).then(|| Equals(v.clone()))?
1096        }
1097        (Equals(v), Falsy(not)) | (Falsy(not), Equals(v)) => {
1098            (v.is_empty() && !not.contains(v)).then(|| Equals(v.clone()))?
1099        }
1100        (Equals(v), NotEquals(not)) | (NotEquals(not), Equals(v)) => {
1101            (!not.contains(v)).then(|| Equals(v.clone()))?
1102        }
1103        (Truthy(_), Falsy(_)) | (Falsy(_), Truthy(_)) => return None,
1104        (Truthy(x), Truthy(y) | NotEquals(y)) | (NotEquals(y), Truthy(x)) => Truthy(union(x, y)),
1105        (Falsy(x), Falsy(y) | NotEquals(y)) | (NotEquals(y), Falsy(x)) => Falsy(union(x, y)),
1106        (NotEquals(x), NotEquals(y)) => NotEquals(union(x, y)),
1107    })
1108}
1109
1110/// Merge two claim sets, or `None` when they contradict.
1111fn merge_claims(a: &ClaimSet, b: &ClaimSet) -> Option<ClaimSet> {
1112    let mut out = a.clone();
1113    for (name, need) in b {
1114        let merged = match out.get(name) {
1115            None => need.clone(),
1116            Some(have) => merge_need(have, need)?,
1117        };
1118        out.insert(name.clone(), merged);
1119    }
1120    Some(out)
1121}
1122
1123/// Every claim set satisfying `pred` (when `want` is true) or falsifying it,
1124/// one per way the `||`/`&&` alternatives can be met. The closed predicate
1125/// vocabulary keeps this small.
1126fn claim_witnesses(pred: &ClaimPredicate, want: bool) -> Vec<ClaimSet> {
1127    let one = |name: &str, need: ClaimNeed| vec![ClaimSet::from([(name.to_string(), need)])];
1128    let both = |l: Vec<ClaimSet>, r: Vec<ClaimSet>| {
1129        l.iter()
1130            .flat_map(|a| r.iter().filter_map(move |b| merge_claims(a, b)))
1131            .collect()
1132    };
1133    let either = |mut l: Vec<ClaimSet>, r: Vec<ClaimSet>| {
1134        l.extend(r);
1135        l
1136    };
1137    match (pred, want) {
1138        (ClaimPredicate::HasClaim(n), true) => one(n, ClaimNeed::Truthy(BTreeSet::new())),
1139        (ClaimPredicate::ClaimEquals(n, v), true) => one(n, ClaimNeed::Equals(v.clone())),
1140        (ClaimPredicate::HasClaim(n), false) => one(n, ClaimNeed::Falsy(BTreeSet::new())),
1141        (ClaimPredicate::ClaimEquals(n, v), false) => {
1142            one(n, ClaimNeed::NotEquals(BTreeSet::from([v.clone()])))
1143        }
1144        (ClaimPredicate::And(l, r), true) | (ClaimPredicate::Or(l, r), false) => {
1145            both(claim_witnesses(l, want), claim_witnesses(r, want))
1146        }
1147        (ClaimPredicate::Or(l, r), true) | (ClaimPredicate::And(l, r), false) => {
1148            either(claim_witnesses(l, want), claim_witnesses(r, want))
1149        }
1150        (ClaimPredicate::Not(inner), _) => claim_witnesses(inner, !want),
1151    }
1152}
1153
1154/// #2019: a JavaScript object literal of JWT claims that satisfies a
1155/// refinement actor's predicate, for the `system`-tier test driver to sign
1156/// next to `sub` when a case acts as that refinement (`by Admin("root")`):
1157/// `hasClaim("admin")` → `{ "admin": true }`, `claimEquals("role", "ops")` →
1158/// `{ "role": "ops" }`. The Worker's seam then checks the predicate against
1159/// the verified claims exactly as it would a real token's. A `Truthy` need
1160/// signs `true`: a boolean is never `===` a string, so it also lies outside
1161/// every excluded value. An absent claim meets `Falsy` and `NotEquals`, so
1162/// those sign nothing. The search is exact over the closed vocabulary, so
1163/// `None` means no claim set satisfies the predicate
1164/// (`hasClaim("a") && !hasClaim("a")`).
1165pub fn claim_witness_js(pred: &ClaimPredicate) -> Option<String> {
1166    let entries = claim_witness(pred)?
1167        .into_iter()
1168        .map(|(name, value)| {
1169            let value = match value {
1170                WitnessValue::True => "true".to_string(),
1171                WitnessValue::Str(v) => format!("\"{}\"", js_str_escape(&v)),
1172            };
1173            format!("\"{}\": {value}", js_str_escape(&name))
1174        })
1175        .collect::<Vec<_>>();
1176    Some(if entries.is_empty() {
1177        "{}".to_string()
1178    } else {
1179        format!("{{ {} }}", entries.join(", "))
1180    })
1181}
1182
1183/// The value a witness claim is signed with.
1184#[derive(Debug, Clone, PartialEq, Eq)]
1185pub enum WitnessValue {
1186    /// The JSON boolean `true` (`hasClaim`).
1187    True,
1188    /// A JSON string (`claimEquals`).
1189    Str(String),
1190}
1191
1192/// The claims, by name, that satisfy `pred` — the data behind
1193/// [`claim_witness_js`], shared with `bynk token` so a hand-minted token
1194/// carries exactly the claims the `system` harness signs. `None` when no
1195/// claim set satisfies the predicate.
1196pub fn claim_witness(pred: &ClaimPredicate) -> Option<Vec<(String, WitnessValue)>> {
1197    let set = claim_witnesses(pred, true).into_iter().next()?;
1198    Some(
1199        set.into_iter()
1200            .filter_map(|(name, need)| {
1201                let value = match need {
1202                    ClaimNeed::Truthy(_) => WitnessValue::True,
1203                    ClaimNeed::Equals(v) => WitnessValue::Str(v),
1204                    ClaimNeed::Falsy(_) | ClaimNeed::NotEquals(_) => return None,
1205                };
1206                Some((name, value))
1207            })
1208            .collect(),
1209    )
1210}
1211
1212#[cfg(test)]
1213mod claim_witness_tests {
1214    use super::{ClaimPredicate as P, claim_witness_js};
1215
1216    fn has(n: &str) -> Box<P> {
1217        Box::new(P::HasClaim(n.to_string()))
1218    }
1219    fn eq(n: &str, v: &str) -> Box<P> {
1220        Box::new(P::ClaimEquals(n.to_string(), v.to_string()))
1221    }
1222
1223    #[test]
1224    fn a_single_claim_is_signed() {
1225        assert_eq!(
1226            claim_witness_js(&has("admin")).as_deref(),
1227            Some("{ \"admin\": true }")
1228        );
1229        assert_eq!(
1230            claim_witness_js(&eq("role", "ops")).as_deref(),
1231            Some("{ \"role\": \"ops\" }")
1232        );
1233    }
1234
1235    #[test]
1236    fn a_conjunction_signs_both_and_a_disjunction_its_first_arm() {
1237        assert_eq!(
1238            claim_witness_js(&P::And(has("a"), eq("role", "ops"))).as_deref(),
1239            Some("{ \"a\": true, \"role\": \"ops\" }")
1240        );
1241        assert_eq!(
1242            claim_witness_js(&P::Or(has("a"), has("b"))).as_deref(),
1243            Some("{ \"a\": true }")
1244        );
1245    }
1246
1247    #[test]
1248    fn a_negation_leaves_the_claim_out_and_steers_the_disjunction() {
1249        assert_eq!(
1250            claim_witness_js(&P::Not(has("banned"))).as_deref(),
1251            Some("{}")
1252        );
1253        // `(a || b) && !a` is met only by `b`.
1254        assert_eq!(
1255            claim_witness_js(&P::And(
1256                Box::new(P::Or(has("a"), has("b"))),
1257                Box::new(P::Not(has("a")))
1258            ))
1259            .as_deref(),
1260            Some("{ \"b\": true }")
1261        );
1262        // `!(a && b)` is met by leaving `a` out.
1263        assert_eq!(
1264            claim_witness_js(&P::Not(Box::new(P::And(has("a"), has("b"))))).as_deref(),
1265            Some("{}")
1266        );
1267    }
1268
1269    #[test]
1270    fn a_negated_equality_excludes_one_value_only() {
1271        let not = |p: Box<P>| Box::new(P::Not(p));
1272        // `hasClaim("role") && !claimEquals("role", "banned")`: any truthy
1273        // non-"banned" value; `true` is never `===` a string.
1274        assert_eq!(
1275            claim_witness_js(&P::And(has("role"), not(eq("role", "banned")))).as_deref(),
1276            Some("{ \"role\": true }")
1277        );
1278        // `claimEquals("role", "ops") && !claimEquals("role", "admin")`.
1279        assert_eq!(
1280            claim_witness_js(&P::And(eq("role", "ops"), not(eq("role", "admin")))).as_deref(),
1281            Some("{ \"role\": \"ops\" }")
1282        );
1283        // `!claimEquals("role", "banned")` alone: leave the claim out.
1284        assert_eq!(
1285            claim_witness_js(&P::Not(eq("role", "banned"))).as_deref(),
1286            Some("{}")
1287        );
1288        // `!claimEquals("r", "x") && !hasClaim("r")`: absent meets both.
1289        assert_eq!(
1290            claim_witness_js(&P::And(not(eq("r", "x")), not(has("r")))).as_deref(),
1291            Some("{}")
1292        );
1293    }
1294
1295    #[test]
1296    fn an_excluded_value_still_contradicts_its_own_equality() {
1297        let not = |p: Box<P>| Box::new(P::Not(p));
1298        // `hasClaim("r") && !claimEquals("r", "x") && claimEquals("r", "x")`.
1299        assert_eq!(
1300            claim_witness_js(&P::And(
1301                Box::new(P::And(has("r"), not(eq("r", "x")))),
1302                eq("r", "x")
1303            )),
1304            None
1305        );
1306        // An empty string is falsy, so it cannot meet `hasClaim`.
1307        assert_eq!(claim_witness_js(&P::And(has("r"), eq("r", ""))), None);
1308        assert_eq!(
1309            claim_witness_js(&P::And(not(has("r")), eq("r", ""))).as_deref(),
1310            Some("{ \"r\": \"\" }")
1311        );
1312    }
1313
1314    #[test]
1315    fn a_contradiction_has_no_witness() {
1316        assert_eq!(
1317            claim_witness_js(&P::And(has("a"), Box::new(P::Not(has("a"))))),
1318            None
1319        );
1320        assert_eq!(claim_witness_js(&P::And(eq("r", "x"), eq("r", "y"))), None);
1321    }
1322}
1323
1324// ---- call-site principals (1A.33) --------------------------------------------
1325
1326/// A reserved bad-credential principal (`by Forged`, …): it names no actor and takes no
1327/// identity, and the `system` driver presents a credential the seam must refuse.
1328///
1329/// #2135, #2864: `Forged` (a wrong secret), `Stale` (a timestamp past the tolerance) and
1330/// `Expired` (a Bearer or `Oidc` token whose `exp` has passed). #3052: `WrongIssuer` and
1331/// `WrongAudience` (an `Oidc` token for another issuer or audience). #3225:
1332/// `WrongAlgorithm` and `NoSubject` (an `Oidc` token under a refused algorithm, or with no
1333/// usable `sub`).
1334#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1335pub enum BadCredential {
1336    Forged,
1337    Stale,
1338    Expired,
1339    WrongIssuer,
1340    WrongAudience,
1341    WrongAlgorithm,
1342    NoSubject,
1343}
1344
1345impl BadCredential {
1346    /// Every bad-credential principal.
1347    pub const ALL: [BadCredential; 7] = [
1348        BadCredential::Forged,
1349        BadCredential::Stale,
1350        BadCredential::Expired,
1351        BadCredential::WrongIssuer,
1352        BadCredential::WrongAudience,
1353        BadCredential::WrongAlgorithm,
1354        BadCredential::NoSubject,
1355    ];
1356
1357    /// The name written after `by`.
1358    pub const fn name(self) -> &'static str {
1359        match self {
1360            BadCredential::Forged => "Forged",
1361            BadCredential::Stale => "Stale",
1362            BadCredential::Expired => "Expired",
1363            BadCredential::WrongIssuer => "WrongIssuer",
1364            BadCredential::WrongAudience => "WrongAudience",
1365            BadCredential::WrongAlgorithm => "WrongAlgorithm",
1366            BadCredential::NoSubject => "NoSubject",
1367        }
1368    }
1369
1370    /// The `system` test driver that presents this credential.
1371    pub const fn driver(self) -> &'static str {
1372        match self {
1373            BadCredential::Forged => "forged",
1374            BadCredential::Stale => "stale",
1375            BadCredential::Expired => "expired",
1376            BadCredential::WrongIssuer => "wrongissuer",
1377            BadCredential::WrongAudience => "wrongaudience",
1378            BadCredential::WrongAlgorithm => "wrongalgorithm",
1379            BadCredential::NoSubject => "nosubject",
1380        }
1381    }
1382
1383    /// Whether only an `Oidc` seam can refuse this credential.
1384    pub const fn oidc_only(self) -> bool {
1385        matches!(
1386            self,
1387            BadCredential::WrongIssuer
1388                | BadCredential::WrongAudience
1389                | BadCredential::WrongAlgorithm
1390                | BadCredential::NoSubject
1391        )
1392    }
1393}
1394
1395/// What a call-site principal (`by <Name>[(<identity>)]`) is: an actor, the reserved
1396/// no-credential principal `Nobody` (#706), or a reserved bad credential. The one
1397/// classification of those reserved names; the checker records it on the clause
1398/// ([`crate::checker::Callee::Principal`]) and every reader, checker and emitter, reads it.
1399#[derive(Debug, Clone, PartialEq, Eq)]
1400pub enum CallSitePrincipal {
1401    /// An actor, by name (a declared actor of the target, or a prelude actor).
1402    Actor(String),
1403    /// `by Nobody`: no credential at all, so the auth seam answers `401`.
1404    Nobody,
1405    BadCredential(BadCredential),
1406}
1407
1408impl CallSitePrincipal {
1409    /// Classify the name written after `by`.
1410    pub fn of(name: &str) -> CallSitePrincipal {
1411        if name == "Nobody" {
1412            return CallSitePrincipal::Nobody;
1413        }
1414        BadCredential::ALL
1415            .into_iter()
1416            .find(|b| b.name() == name)
1417            .map_or_else(
1418                || CallSitePrincipal::Actor(name.to_string()),
1419                CallSitePrincipal::BadCredential,
1420            )
1421    }
1422
1423    /// Whether the principal drives the auth seam with no usable credential
1424    /// (`Nobody` or a bad credential), which makes an address's outcome an `HttpOutcome`.
1425    pub fn is_reserved(&self) -> bool {
1426        !matches!(self, CallSitePrincipal::Actor(_))
1427    }
1428}
1429
1430#[cfg(test)]
1431mod call_site_principal_tests {
1432    use super::*;
1433
1434    #[test]
1435    fn nobody_is_its_own_principal() {
1436        assert_eq!(CallSitePrincipal::of("Nobody"), CallSitePrincipal::Nobody);
1437        assert!(CallSitePrincipal::Nobody.is_reserved());
1438    }
1439
1440    #[test]
1441    fn each_bad_credential_classifies_and_names_its_driver() {
1442        let drivers = [
1443            ("Forged", "forged"),
1444            ("Stale", "stale"),
1445            ("Expired", "expired"),
1446            ("WrongIssuer", "wrongissuer"),
1447            ("WrongAudience", "wrongaudience"),
1448            ("WrongAlgorithm", "wrongalgorithm"),
1449            ("NoSubject", "nosubject"),
1450        ];
1451        assert_eq!(drivers.len(), BadCredential::ALL.len());
1452        for (name, driver) in drivers {
1453            let CallSitePrincipal::BadCredential(b) = CallSitePrincipal::of(name) else {
1454                panic!("{name} is a bad credential")
1455            };
1456            assert_eq!((b.name(), b.driver()), (name, driver));
1457            assert!(CallSitePrincipal::BadCredential(b).is_reserved());
1458        }
1459    }
1460
1461    #[test]
1462    fn only_the_oidc_credentials_are_oidc_only() {
1463        let oidc: Vec<_> = BadCredential::ALL
1464            .into_iter()
1465            .filter(|b| b.oidc_only())
1466            .map(BadCredential::name)
1467            .collect();
1468        assert_eq!(
1469            oidc,
1470            [
1471                "WrongIssuer",
1472                "WrongAudience",
1473                "WrongAlgorithm",
1474                "NoSubject"
1475            ]
1476        );
1477    }
1478
1479    /// An ordinary actor (declared or prelude, including one whose name merely contains a
1480    /// reserved word) is an actor, not a reserved principal.
1481    #[test]
1482    fn an_ordinary_actor_is_not_reserved() {
1483        for name in [
1484            "Visitor",
1485            "Caller",
1486            "User",
1487            "NobodyElse",
1488            "forged",
1489            "Stale2",
1490            "",
1491        ] {
1492            let p = CallSitePrincipal::of(name);
1493            assert_eq!(p, CallSitePrincipal::Actor(name.to_string()), "{name}");
1494            assert!(!p.is_reserved());
1495        }
1496    }
1497}