# Rust SDK

The public API of `sdks/rust`, with its doc comments. Guide: [docs/sdk/rust.md](https://docs.allowedby.com/sdk/rust).

370 public declarations, 370 with a doc comment.

## `allowedby`

`sdks/rust/src/lib.rs`

```rust
pub const SPEC_VERSION: &str = "0.2.14"
```

The spec set this SDK implements.

```rust
pub struct AllowedByContext(pub std::sync::Arc<Context>)
```

The verified context, for handlers: `AllowedByContext(ctx)`. With the `axum` feature it is an axum extractor,
with `actix` an actix-web extractor. A handler on a route outside the map gets a `500` (a configuration
error: that route is not protected); use `Option<AllowedByContext>` there with axum, and
`allowedby::actix::OptionalContext` with actix-web (whose `Option` hides a refusal).

## `allowedby::b64`

`sdks/rust/src/b64.rs`

```rust
pub fn b64u(data: &[u8]) -> String
```

base64url without padding.

```rust
pub fn b64u_dec(s: &str) -> Option<Vec<u8>>
```

Strict base64url decoding: alphabet `[A-Za-z0-9_-]`, no padding, canonical trailing bits. `None` otherwise.

```rust
pub fn b64(data: &[u8]) -> String
```

Standard base64 with padding.

```rust
pub fn b64_dec(s: &str) -> Option<Vec<u8>>
```

Strict standard base64: length a multiple of 4, `=` only as final padding, canonical trailing bits.

## `allowedby::caps`

`sdks/rust/src/caps.rs`

```rust
pub fn constraints_ok(c: &Map<String, Value>) -> bool
```

ABY-3 §2 grammar for the values that end up in the text the person signs (Python `core.constraints_ok`).

```rust
pub fn scope_ok(pattern: &str, resource: &str) -> bool
```

`scope` pattern against a resource: segments split on `:` and `/`, `*` one segment, `**` one or more.

```rust
pub fn satisfies( cap: &Value, route: &Route, body: Option<&Value>, resource: &str, gid: &str, now: i64, ) -> Option<Vec<Charge>>
```

ABY-3 §3: does capability `cap` cover this request? -> the counter charges (count, cumulative amounts) when it
does, `None` when it does not. `count` and cumulative amounts are kept under the root `gid`; the store checks
and applies them atomically (`until` `None`: until the grant expires).

```rust
pub fn attenuates(child: &Value, parent: &Value) -> bool
```

ABY-3 §3: a child capability is equal to or narrower than its parent (ABY-1 §4).

```rust
pub fn render_display(caps: &[Value], lang: Option<&str>, templates: &Map<String, Value>) -> Option<Value>
```

AMH-1 §4 / ABY-3 §5: the text a person signs, rendered from the service's own templates. `None` when a
template, a language or a constraint is missing, a value is outside the grammar or a line is over 280 chars.

## `allowedby::http`

`sdks/rust/src/http.rs`

```rust
pub const MAX_RESPONSE: u64 = 1 << 20
```

Responses larger than this are cut off and refused (Python `core.MAX_RESPONSE`).

```rust
pub struct HttpResponse
```

An HTTP answer: status and body.

```rust
pub status: u16
```

The status code.

```rust
pub body: Vec<u8>
```

The body (at most `MAX_RESPONSE` bytes).

```rust
pub struct HttpError(pub String)
```

A transport failure (no answer at all). Contains no secret: URLs and reasons only.

```rust
pub trait HttpClient: Send + Sync {
    /// GET `url`.
    fn get(&self, url: &str) -> Result<HttpResponse, HttpError>;
    /// POST `body` to `url` with `headers`.
    fn post(&self, url: &str, headers: &[(&str, &str)], body: &[u8]) -> Result<HttpResponse, HttpError>;
}
```

The HTTP client the SDK uses. The default (`http` feature) is `ureq` with rustls; tests and special setups
pass their own.

```rust
pub struct NoHttp
```

A client that refuses every call: for offline setups that install documents themselves.

```rust
pub struct UreqClient
```

The default client: `ureq` (blocking, rustls), 10 s timeouts, no redirects, bodies capped at 1 MiB.

## `allowedby::jose`

`sdks/rust/src/jose.rs`

```rust
pub fn sha256(data: &[u8]) -> [u8; 32]
```

SHA-256.

```rust
pub fn sha256_b64u(data: &[u8]) -> String
```

base64url(SHA-256(data)).

```rust
pub fn thumbprint(jwk: &Value) -> Option<String>
```

RFC 7638 JWK thumbprint (the `kid` everywhere in AllowedBy). `None` for a key type this SDK does not use.

```rust
pub fn alg_for(jwk: &Value) -> Option<&'static str>
```

The JWS `alg` a key signs with (OAID-1 §3.1): Ed25519 -> EdDSA, P-256 -> ES256, anything else none.

```rust
pub fn verify_raw(alg: Option<&str>, jwk: &Value, data: &[u8], sig: &[u8]) -> bool
```

JWS signature check: `alg` must be EdDSA or ES256 and match the key's type (no `none`, no RSA, no HMAC).
ES256 signatures are the 64-byte raw r||s of RFC 7518 §3.4 (DER is refused); a high S is accepted, as JOSE does.

```rust
pub fn webauthn_signature_ok(jwk: &Value, auth_data: &[u8], cdj: &[u8], sig: &[u8]) -> bool
```

WebAuthn assertion signature over authenticatorData || SHA-256(clientDataJSON): ES256 in DER (as authenticators
produce it) or Ed25519. RS256 passkeys are not supported by this SDK and fail closed.

```rust
pub struct Jws
```

A parsed compact JWS: header and payload objects, the signing input and the signature bytes.

```rust
pub header: Map<String, Value>
```

The protected header.

```rust
pub payload: Map<String, Value>
```

The payload (always a JSON object in AllowedBy).

```rust
pub signing_input: Vec<u8>
```

`base64url(header) "." base64url(payload)`, as signed.

```rust
pub signature: Vec<u8>
```

The signature bytes.

```rust
pub fn parse(t: &str) -> Option<Jws>
```

Parse a compact JWS: exactly three base64url parts, header and payload strict JSON objects. `None` otherwise.

```rust
pub fn header_str(&self, k: &str) -> Option<&str>
```

A header member as a string.

```rust
pub fn verify(&self, jwk: &Value) -> bool
```

Check the signature with `jwk`, using the header's `alg`.

```rust
pub fn payload_of(t: &str) -> Option<Map<String, Value>>
```

The payload of a compact JWS without checking anything (for documents already verified).

```rust
pub struct SigningKey
```

The service's signing key (Ed25519): signs the organisation profile and its approval requests.

```rust
pub fn generate() -> Option<SigningKey>
```

A new random key from the operating system's generator (`None` when it is unavailable).

```rust
pub fn from_seed(seed: &[u8; 32]) -> SigningKey
```

From a 32-byte Ed25519 seed (RFC 8032 private key).

```rust
pub fn public_jwk(&self) -> &Value
```

The public JWK, with its `kid`.

```rust
pub fn kid(&self) -> &str
```

The RFC 7638 thumbprint.

```rust
pub fn sign_jws(&self, typ: &str, payload: &Value) -> String
```

Sign a compact JWS: header `{alg: EdDSA, kid, typ}` and payload, both in JCS.

```rust
pub fn rand_bytes(n: usize) -> Option<Vec<u8>>
```

`n` bytes from the operating system's generator (`None` when it is unavailable: callers fail closed).

```rust
pub fn rand_id(n: usize) -> Option<String>
```

A random base64url id of `n` bytes (`None` when the generator is unavailable).

## `allowedby::json`

`sdks/rust/src/json.rs`

```rust
pub fn parse(bytes: &[u8]) -> Option<Value>
```

Parse JSON strictly: one value, duplicate member names refused, nesting at most 64 deep. `None` otherwise.

```rust
pub fn parse_object(bytes: &[u8]) -> Option<Map<String, Value>>
```

Parse a JSON object strictly. `None` for anything else.

```rust
pub fn jcs(v: &Value) -> Option<String>
```

RFC 8785 canonical JSON text. `None` only for a non-finite number (which strict parsing never produces).

```rust
pub fn jcs_bytes(v: &Value) -> Vec<u8>
```

RFC 8785 canonical JSON as UTF-8 bytes; values this SDK builds are always finite, so this never fails for them.

```rust
pub fn int(v: Option<&Value>) -> Option<i64>
```

A JSON integer (not a float, not a bool), as Python's `isinstance(x, int)` reads it.

```rust
pub fn str_of(v: Option<&Value>) -> Option<&str>
```

A JSON string.

```rust
pub fn get<'a>(doc: Option<&'a Value>, key: &str) -> Option<&'a Value>
```

`doc.get(key)` when `doc` is an object.

```rust
pub fn pointer<'a>(doc: Option<&'a Value>, ptr: &str) -> Option<&'a Value>
```

RFC 6901 JSON Pointer into objects only (as the reference `_pointer`).

```rust
pub fn leaves(doc: &Map<String, Value>, prefix: &str, out: &mut Vec<String>)
```

The JSON Pointers of every leaf member of an object (RFC 6901 escaping): what `fields` constrains.

## `allowedby::proto`

`sdks/rust/src/proto.rs`

```rust
pub const CORE_EXCLUDED: [&str; 7] = ["jti", "rev", "human_sig", "authority", "status", "log", "qes"]
```

ABY-1 §3.1: members that are not part of the core a person signs.

```rust
pub fn grant_core(g: &Map<String, Value>) -> Value
```

ABY-1 §3.1: what the person signs: the grant without `CORE_EXCLUDED`, and of `actor` only `operator` and
`runtime`.

```rust
pub fn core_hash(g: &Map<String, Value>) -> String
```

base64url SHA-256(JCS(grant core)): the WebAuthn challenge of one grant (ABY-1 §3.2).

```rust
pub fn batch_challenge(hashes: &[Value]) -> String
```

ABY-1 §3.2 / AMH-1 §11: SHA-256(JCS({"batch": [h1, ..., hn]})), each hi a core hash string.

```rust
pub fn request_digest(htm: &str, htu: &str, query: Option<&str>, body: Option<&[u8]>) -> String
```

ABY-1 §7: the digest a single-use grant is bound to.

```rust
pub fn make_proof( key: &SigningKey, htm: &str, htu: &str, allowed_by: Option<&str>, body: Option<&[u8]>, now: i64, ) -> Option<String>
```

ABY-2 §3: a proof JWT for one request (`body` as sent, or `None`); `allowed_by` adds `dth`. `None` only when
the system's random generator fails.

```rust
pub fn content_digest(body: &[u8]) -> String
```

RFC 9530 `Content-Digest`: sha-256 of the content as transmitted.

```rust
pub fn sig_base(components: &[String], values: &dyn Fn(&str) -> Option<String>, params: &str) -> Option<String>
```

RFC 9421 §2.5 signature base: one line per covered component, then `@signature-params`.

```rust
pub enum SigParam {
    /// `"..."`.
    Str(String),
    /// Digits.
    Int(i64),
}
```

A parameter of `Signature-Input`: a quoted string or an integer.

```rust
pub type SigInput = (Vec<String>, Vec<(String, SigParam)>, String)
```

A parsed `Signature-Input`: the covered components, the parameters, the raw text after `sig1=`.

```rust
pub fn parse_sig_input(s: &str) -> Option<SigInput>
```

`Signature-Input: sig1=("c1" "c2" ...);k=v;...` -> (components, params, the raw text after `sig1=`).
The grammar is the reference's: 1 to 8 components `"[a-z@-]+"`, 1 to 10 parameters `;[a-z]+=` with a quoted
value (no `"` or `\`, at most 200 characters) or 1 to 12 digits. A parameter named twice is refused.

```rust
pub fn status_bits(lst: &str) -> Option<Vec<u8>>
```

Decompress a status list's `lst` (base64url of zlib), at most 1 MiB of bits.

```rust
pub fn status_bit(bits: &[u8], idx: u64) -> bool
```

Bit `idx` of a decompressed status list (0 beyond its end, as the reference reads it).

```rust
pub fn check_assertion( a: &Map<String, Value>, challenge: &str, origin: &str, rp_id: &str, jwk: &Value, ) -> Option<&'static str>
```

ABY-1 §3.3: every WebAuthn check of one assertion `a` (`{authenticator_data, client_data_json, signature}`,
base64url). `None` when valid, else the reason.

## `allowedby::refresh`

`sdks/rust/src/refresh.rs`

```rust
pub const STARTUP_WAIT: Duration = Duration::from_secs(5)
```

How long `Refresher::spawn` waits for the first refresh (Python `STARTUP_WAIT`, SDK contract §2 item 4).

```rust
pub enum Trust {
    /// Trust on first use (the development default): each node origin with the highest level it may give; its
    /// `node` key is pinned on the first fetch and a changed key is refused.
    OnFirstUse(Vec<(String, u8)>),
    /// A signed OAID-5 trust list (anchors, programs, vouching, witnesses).
    List(TrustList),
}
```

Which nodes the service trusts.

```rust
pub fn origin_of(name: &str) -> String
```

A node name (`host[:port]`) as an origin: https, except this machine in development.

```rust
pub struct Refresher
```

Fetches and installs what the verifier needs. One per service.

```rust
pub fn new(verifier: Arc<Verifier>, trust: Trust, http: Arc<dyn HttpClient>) -> Refresher
```

A refresher for `verifier`.

```rust
pub fn refresh(&self) -> Vec<String>
```

One refresh. -> the failures (also logged).

```rust
pub fn spawn(this: &Arc<Refresher>, seconds: u64)
```

Refresh now, then every `seconds` (1 to 60) on a background thread, until the last handle to `this` is
dropped. Never on the request path. Returns once the first refresh is over (done or failed, at most
`STARTUP_WAIT`), so a service that starts cold (a new instance, or one that scales to zero) holds node keys
and status lists before its first request (ARCH-1 §4, SDK contract §2 item 4). It blocks the calling thread
that long: call it at startup, before serving, not from a task of an async runtime that is already serving.

## `allowedby::trust`

`sdks/rust/src/trust.rs`

```rust
pub struct Statement
```

A node statement (`oaid-node+jwt`, OAID-1 §7) whose self-signature and key thumbprints were checked.

```rust
pub name: String
```

The node's name (`iss`), `host[:port]`.

```rust
pub node_kid: String
```

The kid of its `node` key.

```rust
pub payload: Map<String, Value>
```

The statement payload.

```rust
pub keys: BTreeMap<String, Value>
```

Its keys by kid.

```rust
pub fn parse(jws: &str, now: Option<i64>) -> Option<Statement>
```

Check a statement: `typ`, exactly one key with roles `["node"]` that signed it, every key's kid its
thumbprint, an `iss`; with `now`, an `exp` still in the future. `None` otherwise.

```rust
pub fn role_keys(&self, role: &str) -> Vec<&Value>
```

The keys holding `role`.

```rust
pub fn endpoint(&self, name: &str) -> Option<&str>
```

An endpoint URL from the statement (`status`, `approvals`, `log`, ...).

```rust
pub struct TrustedNode
```

How a trusted node got there.

```rust
pub max_level: u8
```

The highest level its documents can give.

```rust
pub via: &'static str
```

`anchor`, `program` or `vouch`.

```rust
pub depth: u32
```

The vouching depth (0 for anchors and program nodes).

```rust
pub kid: String
```

The node key kid the trust is bound to.

```rust
pub struct TrustList
```

A signed OAID-5 trust list (`oaid-trust+jwt`), signed by the service's own key (configuration integrity).

```rust
pub exp: i64
```

When it stops being valid (then no node is trusted).

```rust
pub fn parse(jws: &str, key: &Value) -> Option<TrustList>
```

Check the list's signature with `key` (the service's public JWK) and its members.

```rust
pub fn denied(&self) -> BTreeSet<String>
```

Nodes never trusted.

```rust
pub fn witnesses_min(&self) -> usize
```

Distinct trusted witnesses a node's checkpoint needs (0: no witnessing required).

```rust
pub fn programs(&self) -> Vec<(String, Vec<String>, u8, i64)>
```

The program lists to fetch: (url, pinned kids, max_level, refresh seconds).

```rust
pub fn direct_names(&self, programs: &BTreeMap<String, String>, now: i64) -> Vec<String>
```

The names of the nodes listed directly (anchors and the anchors of pinned programs).

```rust
pub fn resolve( &self, statements: &BTreeMap<String, Statement>, programs: &BTreeMap<String, String>, vouches: &[String], now: i64, ) -> BTreeMap<String, TrustedNode>
```

OAID-5 §3: anchors, then program lists, then vouching depth by depth. `statements` are the checked
statements of the nodes known so far, `programs` the fetched program lists by URL, `vouches` the vouch
documents (`oaid-vouch+jwt`) found. -> every trusted node.

```rust
pub struct Checkpoint
```

A C2SP signed note: the body (with its final newline), origin, size, root and the signature lines.

```rust
pub body: String
```

The signed text.

```rust
pub origin: String
```

The log origin (first line).

```rust
pub size: u64
```

The tree size.

```rust
pub root: Vec<u8>
```

The root hash.

```rust
pub sigs: Vec<(String, Vec<u8>)>
```

(key name, signature bytes) for every signature line.

```rust
pub fn parse_note(text: &str) -> Option<Checkpoint>
```

Parse a signed note. `None` when malformed.

```rust
pub fn verify_checkpoint(text: &str, st: &Statement) -> Option<Checkpoint>
```

A checkpoint signed by a `checkpoint` key of `st` under its log origin. `None` otherwise.

```rust
pub fn cosig_time(cp: &Checkpoint, witness: &str, wst: &Statement) -> Option<u64>
```

C2SP tlog-cosignature/v1 by `witness` (a `witness` key of `wst`): its timestamp, or `None`.

```rust
pub fn witnesses( cp: &Checkpoint, node: &str, trusted: &BTreeMap<String, TrustedNode>, statements: &BTreeMap<String, Statement>, now: i64, ) -> usize
```

OAID-5 §3 step 5: distinct trusted nodes (other than `node`) that cosigned its checkpoint within 24 hours.

## `allowedby::util`

`sdks/rust/src/util.rs`

```rust
pub fn norm_path(p: &str) -> String
```

RFC 3986 §6.2.2 for a request path: percent-encoding normalised (unreserved characters decoded, hex upper
case) and dot segments removed (Python `core.norm_path`).

```rust
pub fn norm_origin(o: &str) -> Option<String>
```

A public origin, normalised as `htu` is (ABY-2 §3): lower-case scheme and host, default port removed, no path.
`None` when it is not `http(s)://host[:port]` (a trailing `/` is accepted; IPv6 literals are not).

```rust
pub fn netloc(origin: &str) -> &str
```

The host (and port) of an origin: `https://api.example.com` -> `api.example.com`.

```rust
pub fn is_local(host: &str) -> bool
```

True for this machine (development only: plain http is allowed for it). `host` may carry a port.

```rust
pub type Micros = i128
```

Amounts are decimal strings, at most 15 digits before the point and 6 after (Python `core.dec`); this SDK
keeps them as integers of millionths, so comparisons and sums are exact.

```rust
pub fn dec(v: Option<&serde_json::Value>) -> Option<Micros>
```

Parse an amount string; `None` for anything else (numbers, signs, exponents, more digits).

```rust
pub fn civil_from_days(z: i64) -> (i64, u32, u32)
```

(year, month, day) of a day number since 1970-01-01 (Howard Hinnant's civil_from_days).

```rust
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64
```

Days since 1970-01-01 of a civil date.

```rust
pub fn rfc3339(t: i64) -> String
```

RFC 3339 UTC time, `2025-10-26T12:15:00Z`.

```rust
pub fn period_bounds(per: &str, t: i64) -> Option<(i64, i64)>
```

The UTC calendar period (`day`, `week` from Monday, `month`) holding `t`: (start, end) in epoch seconds.

```rust
pub fn system_now() -> i64
```

Seconds since the epoch, from the system clock.

```rust
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool
```

Constant-time equality of two byte strings (for secrets and digests compared against attacker input).

## `allowedby::verifier`

`sdks/rust/src/verifier.rs`

```rust
pub const MAX_ENVELOPE: usize = 8192
```

ABY-2 §2: `Allowed-By` and `AllowedBy-Proof` together at most 8 KiB.

```rust
pub const MAX_CHAIN: usize = 2
```

ABY-2 §2 (0.2.14): a chain of at most two JWS, depth 1 (a root and one child).

```rust
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>
```

A clock: seconds since the epoch. Every time check uses it (tests inject one).

```rust
pub struct RouteInfo
```

The route an accepted request matched.

```rust
pub method: String
```

The method.

```rust
pub path: String
```

The path pattern (`/notes/{id}`).

```rust
pub capability: Option<String>
```

The capability, if any.

```rust
pub class: String
```

The class used for this request.

```rust
pub level: u8
```

The route's level.

```rust
pub struct Context
```

What the handler learns from an accepted request (ORG-1 §4.1, ABY-2 §5 step 10). Read-only.

```rust
pub agent: String
```

The agent (passport `sub`).

```rust
pub operator: String
```

The agent's operator (its vendor, `operator.id`).

```rust
pub human_id: Option<String>
```

The person's pairwise id at this service, `None` on level-0 routes.

```rust
pub level: u8
```

The identity level the request carries (0 to 3).

```rust
pub capabilities: Vec<String>
```

The capabilities of the grant (`notes:read`, ...).

```rust
pub display: Option<Value>
```

The text the person approved (`{summary, lines, lang}`), if any.

```rust
pub gid: Option<String>
```

The grant id of the leaf.

```rust
pub rev: Option<i64>
```

The leaf's revision.

```rust
pub jti: Option<String>
```

The leaf grant's `jti`.

```rust
pub acting_for: Option<Value>
```

Acting for an organisation (ORG-1 mandates): always `None` here, mandates are not supported yet.

```rust
pub tenant: Option<String>
```

The `{tenant}` path parameter, if the route has one, decoded once as in `params`.

```rust
pub route: RouteInfo
```

The route matched.

```rust
pub chain: Vec<(String, Option<i64>)>
```

The grant chain, leaf first: (gid, rev).

```rust
pub human_iss: Option<String>
```

The person's home node (`human.reg` issuer).

```rust
pub linked_account: Option<String>
```

On a `require_link` route, the account of yours the person is linked to (ABY-3 §6), also when no path
parameter names one; `None` elsewhere.

```rust
pub proof_jti: String
```

The proof's `jti` (or the RFC 9421 nonce): for audit logs.

```rust
pub run: Option<String>
```

The agent's run id (`run`), audit only.

```rust
pub call: Option<u64>
```

The agent's call number in its run (`call`), audit only.

```rust
pub params: BTreeMap<String, String>
```

The route's path values as they were checked (CONTRACT §2 item 7): each `{name}` of the route's template, from
the normalised path, decoded once (`%41` gives `A`, `%2561` gives `%61`). Act on these values, never on your
own reading of the raw path, which can differ.

```rust
pub struct NodeEntry
```

A trusted node in the cache.

```rust
pub statement: Statement
```

Its statement.

```rust
pub max_level: u8
```

The highest level its documents can give.

```rust
pub origin: String
```

The origin it was fetched from (RFC 9421 `Signature-Agent` names it).

```rust
pub revoked: BTreeMap<String, Option<i64>>
```

Withdrawn keys: kid -> documents logged at or before this index stay valid.

```rust
pub witness_ok: bool
```

OAID-5 `witnesses_min` met.

```rust
pub fn new(statement: Statement, max_level: u8, origin: &str) -> NodeEntry
```

An entry for a checked statement.

```rust
pub struct VerifierConfig
```

What a verifier is built from.

```rust
pub origin: String
```

The public origin (`https://api.example.com`), as agents sign it in `htu`.

```rust
pub routes: Vec<Route>
```

The route map.

```rust
pub service_kids: Vec<String>
```

The kids of this service's own keys (`initiator.kid` of serious grants).

```rust
pub clock: Clock
```

The clock.

```rust
pub store: Arc<dyn Store>
```

The store.

```rust
pub rfc9421: bool
```

Accept the RFC 9421 Web Bot Auth profile instead of the proof JWT (ABY-2 §3.1).

```rust
pub dev_webauthn_origins: BTreeMap<String, String>
```

Development: WebAuthn origins per rp_id (`localhost` -> the local node's origin).

```rust
pub templates: Map<String, Value>
```

This service's templates: a grant naming several audiences must carry exactly what they render.

```rust
pub struct Verifier
```

The verifier. Cheap to share (`Arc`); every method takes `&self`.

```rust
pub fn new(cfg: VerifierConfig) -> Verifier
```

A verifier. `origin` must already be normalised (see `util::norm_origin`).

```rust
pub fn replay_key(kid: &str, jti: &str) -> String
```

The store key of a proof in the replay set: `(kid, jti)`, or `(keyid, nonce)` for RFC 9421.

```rust
pub fn used_key(gid: &str) -> String
```

The store key marking a single-use grant consumed.

```rust
pub fn origin(&self) -> &str
```

The public origin.

```rust
pub fn routes(&self) -> &[Route]
```

The route map.

```rust
pub fn now(&self) -> i64
```

The current time on the verifier's clock.

```rust
pub fn nodes(&self) -> Arc<BTreeMap<String, NodeEntry>>
```

The trusted nodes now in the cache.

```rust
pub fn set_nodes(&self, nodes: BTreeMap<String, NodeEntry>)
```

Replace the trusted nodes (the background refresh does this; tests and offline setups may too).

```rust
pub fn install_node(&self, entry: NodeEntry)
```

Install one node: its checked statement, the highest level it can give and the origin it was fetched from.

```rust
pub fn install_status_list(&self, uri: &str, jws: &str) -> bool
```

Install a status list (`statuslist+jwt`) for `uri`, checked like the refresh does: signed by an `issue` key
of its trusted issuer that is not withdrawn, `sub` equal to `uri`. -> false when refused.

```rust
pub fn status_list_iat(&self, uri: &str) -> Option<i64>
```

The `iat` of the cached status list at `uri`, if any (for health checks).

```rust
pub fn node_doc(&self, j: &Jws, typ: &str, role: &str) -> Result<Map<String, Value>, Reject>
```

A document signed by a role key of a trusted node, from the cache only (OAID-1 §7, OAID-5 §3).

```rust
pub fn status_bit(&self, reference: Option<&Value>, max_age: i64, now: i64) -> Result<bool, Reject>
```

The status bit a document's `status` points to; `status_stale` when the cached list is missing or too old
for the class (60 s for serious classes, 3600 s otherwise, measured from the list's `iat`).

```rust
pub fn registration(&self, t: &str, now: i64, max_age: i64) -> Result<(Map<String, Value>, u8), Reject>
```

A person's registration (OAID-7 §4) from a trusted home node, unrevoked. -> (payload, effective level).

```rust
pub fn human(&self, g: &Map<String, Value>, now: i64, max_age: i64) -> Result<(Map<String, Value>, u8), Reject>
```

ABY-1 §3.3 steps 1-2 on a root grant, a batch signature included (§3.2). -> (registration, level).

```rust
pub fn verify(&self, req: &Request) -> Result<Context, Reject>
```

ABY-2 §5: verify one request against the route map. `Ok` with the context, or the refusal.

## `allowedby::actix`

`sdks/rust/src/actix.rs`

```rust
pub struct AllowedBy
```

The middleware factory: `App::new().wrap(AllowedBy::new(service))`.

```rust
pub fn new(svc: Service) -> AllowedBy
```

The middleware for `svc`.

```rust
pub fn to_actix(r: AbyResponse) -> HttpResponse
```

Convert an SDK response into an actix-web response.

```rust
pub struct AllowedByMiddleware<S>
```

The middleware service.

```rust
pub struct OptionalContext(pub Option<AllowedByContext>)
```

The optional context for actix-web: `None` on a path outside the map, the context on a checked request, and a
refusal (`400`) for a request changed after its check (plan 14). Use it, not `Option<AllowedByContext>`:
actix-web turns every error of an extractor inside `Option` into `None`, so with `Option` a rewritten request would
run as if it had not been checked (a registered handler is refused before extraction either way).

```rust
pub struct Registered
```

A resource whose handlers are registered with the service (CONTRACT §2.10 rule 5): give it to `.service(..)`. Built
by `resource`, `get`, `post`, `put`, `patch`, `delete` or `any`; add more methods with the methods of
the same names.

```rust
pub fn resource(svc: &Service, path: &str) -> Registered
```

A resource at `path` (the path the route map writes for it) whose handlers are registered with `svc`.

```rust
pub fn get<F, Args>(svc: &Service, path: &str, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

A resource at `path` with a registered `web::get()` handler: GET only (actix-web runs a resource's `any` route,
if it has one, for HEAD).

```rust
pub fn post<F, Args>(svc: &Service, path: &str, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

A resource at `path` with a registered `web::post()` handler.

```rust
pub fn put<F, Args>(svc: &Service, path: &str, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

A resource at `path` with a registered `web::put()` handler.

```rust
pub fn patch<F, Args>(svc: &Service, path: &str, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

A resource at `path` with a registered `web::patch()` handler.

```rust
pub fn delete<F, Args>(svc: &Service, path: &str, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

A resource at `path` with a registered `web::delete()` handler.

```rust
pub fn any<F, Args>(svc: &Service, path: &str, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

A resource at `path` with a registered `web::route()` handler, for every method (a catch-all that serves the
handler of a protected route is refused).

```rust
pub fn get<F, Args>(self, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

Adds a registered `web::get()` handler: GET only.

```rust
pub fn post<F, Args>(self, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

Adds a registered `web::post()` handler.

```rust
pub fn put<F, Args>(self, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

Adds a registered `web::put()` handler.

```rust
pub fn patch<F, Args>(self, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

Adds a registered `web::patch()` handler.

```rust
pub fn delete<F, Args>(self, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

Adds a registered `web::delete()` handler.

```rust
pub fn any<F, Args>(self, handler: F) -> Registered where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,
```

Adds a registered `web::route()` handler, for every method.

```rust
pub fn at(mut self, pattern: &str) -> Registered
```

The resource's own pattern, when it differs from the path the route map writes: inside
`web::scope("/api")`, `resource(&aby, "/api/notes/{id}").at("/notes/{id}")`.

## `allowedby::axum`

`sdks/rust/src/axum.rs`

```rust
pub fn protect(router: Router, svc: Service) -> Router
```

`router` behind AllowedBy: the SDK's endpoints, then the check on every route of the map, then `router`.
Paths outside the map reach `router` unchanged.

```rust
pub fn get<H, T, S>(svc: &Service, path: &str, handler: H) -> MethodRouter<S> where H: Handler<T, S>, T: 'static, S: Clone + Send + Sync + 'static,
```

`axum::routing::get(handler)`, registered with `svc` for `path` (the path the route map writes for it):
CONTRACT §2.10 rule 5 holds for it. HEAD is read as GET.

```rust
pub fn post<H, T, S>(svc: &Service, path: &str, handler: H) -> MethodRouter<S> where H: Handler<T, S>, T: 'static, S: Clone + Send + Sync + 'static,
```

`axum::routing::post(handler)`, registered with `svc` for `path`: CONTRACT §2.10 rule 5 holds for it.

```rust
pub fn put<H, T, S>(svc: &Service, path: &str, handler: H) -> MethodRouter<S> where H: Handler<T, S>, T: 'static, S: Clone + Send + Sync + 'static,
```

`axum::routing::put(handler)`, registered with `svc` for `path`: CONTRACT §2.10 rule 5 holds for it.

```rust
pub fn patch<H, T, S>(svc: &Service, path: &str, handler: H) -> MethodRouter<S> where H: Handler<T, S>, T: 'static, S: Clone + Send + Sync + 'static,
```

`axum::routing::patch(handler)`, registered with `svc` for `path`: CONTRACT §2.10 rule 5 holds for it.

```rust
pub fn delete<H, T, S>(svc: &Service, path: &str, handler: H) -> MethodRouter<S> where H: Handler<T, S>, T: 'static, S: Clone + Send + Sync + 'static,
```

`axum::routing::delete(handler)`, registered with `svc` for `path`: CONTRACT §2.10 rule 5 holds for it.

```rust
pub fn any<H, T, S>(svc: &Service, path: &str, handler: H) -> MethodRouter<S> where H: Handler<T, S>, T: 'static, S: Clone + Send + Sync + 'static,
```

`axum::routing::any(handler)`, registered with `svc` for `path` and every method: CONTRACT §2.10 rule 5 holds
for it (a catch-all route that serves the handler of a protected route is refused).

## `allowedby::tower`

`sdks/rust/src/tower.rs`

```rust
pub const MAX_BODY: usize = 1 << 20
```

The largest body the layer reads (Python `core.MAX_BODY`); larger bodies get `413`.

```rust
pub struct AllowedByLayer
```

The layer. `AllowedByLayer::new(service).layer(inner)`.

```rust
pub fn new(svc: Service) -> AllowedByLayer
```

A layer for `svc`.

```rust
pub struct AllowedBy<S>
```

The middleware service the layer builds.

```rust
pub type AbyBody<B> = Either<B, Full<Bytes>>
```

The response body: the inner service's, or the SDK's own.

```rust
pub type AbyReqBody<B> = Either<B, Full<Bytes>>
```

The request body the inner service receives: the original (paths outside the route map), or the bytes the SDK
read and verified.

```rust
pub fn to_http<B>(r: AbyResponse) -> Response<AbyBody<B>>
```

Convert an SDK response into an `http` response.

```rust
pub fn to_aby(parts: &http::request::Parts, body: &[u8]) -> AbyRequest
```

The SDK's view of an `http` request (headers as text; a value that is not text is kept lossily, which makes
any signature over it fail: fail closed).

## `allowedby (error.rs)`

`sdks/rust/src/error.rs`

```rust
pub enum Code {
    /// 400: malformed envelope, a body that is not a JSON object, a grant and a passport mixed.
    InvalidRequest,
    /// 401: no `Allowed-By` header.
    PassportRequired,
    /// 401: a signature, a proof, a replay, a broken chain.
    InvalidSignature,
    /// 401: the document's node is not trusted.
    UntrustedNode,
    /// 401: the node's log is not witnessed enough (OAID-5 `witnesses_min`).
    InsufficientWitnesses,
    /// 401 challenge: the route needs a grant and a passport was shown.
    GrantRequired,
    /// 401 challenge: the grant does not cover this request.
    GrantInsufficient,
    /// 401 challenge: a higher identity level is needed.
    LevelInsufficient,
    /// 401 challenge: a qualified electronic signature is needed.
    QesRequired,
    /// 401 challenge: the person must act under a company mandate this service accepts (ORG-1 §6).
    MandateRequired,
    /// 401 challenge: the grant expired.
    Expired,
    /// 401: not valid yet.
    NotYetValid,
    /// 401: the grant, an ancestor or the person's registration was revoked.
    Revoked,
    /// 401: the agent's key expired; rebind the grant.
    ActorExpired,
    /// 401: the grant lasts longer than the route's class allows.
    ClassLifetimeExceeded,
    /// 401: the single-use grant was already used.
    SingleUseConsumed,
    /// 403: no such route or capability.
    CapabilityDenied,
    /// 403: the agent's key custody or the person's authenticator is too weak.
    TierInsufficient,
    /// 403: the person's identity is not linked to the account this route serves (ABY-3 §6).
    HumanNotLinked,
    /// 403: the tenant's budget for this action cannot take this amount (ORG-1 §5.3).
    BudgetExceeded,
    /// 429: too many calls of this agent, or of its operator (rate limits).
    RateLimited,
    /// 431: `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (depth 1).
    EnvelopeTooLarge,
    /// 503: the revocation list is too old (or the replay store is unreachable); retry.
    StatusStale,
}
```

Why a request was refused. The wire name (`as_str`) goes in `type: https://allowedby.org/errors/``.

```rust
pub const ALL: [Code; 23] = [ Code::InvalidRequest, Code::PassportRequired, Code::InvalidSignature, Code::UntrustedNode, Code::InsufficientWitnesses, Code::GrantRequired, Code::GrantInsufficient, Code::LevelInsufficient, Code::QesRequired, Code::MandateRequired, Code::Expired, Code::NotYetValid, Code::Revoked, Code::ActorExpired, Code::ClassLifetimeExceeded, Code::SingleUseConsumed, Code::CapabilityDenied, Code::TierInsufficient, Code::HumanNotLinked, Code::BudgetExceeded, Code::RateLimited, Code::EnvelopeTooLarge, Code::StatusStale, ]
```

Every code, for tables and tests.

```rust
pub fn as_str(self) -> &'static str
```

The wire name.

```rust
pub fn status(self) -> u16
```

The HTTP status (ABY-2 §6).

```rust
pub fn is_challenge(self) -> bool
```

Codes answered with an AllowedBy challenge naming the action (Python `CHALLENGE_CODES`, minus the extended
`authority_required`).

```rust
pub fn from_wire(s: &str) -> Option<Code>
```

From the wire name.

```rust
pub struct Reject
```

A refused request: the code and a short reason (never a token, key, body or personal data).

```rust
pub code: Code
```

The refusal code.

```rust
pub why: &'static str
```

Why, for logs and the problem `title`. Fixed texts only: nothing from the request.

```rust
pub actor_sub: Option<String>
```

The agent (`sub`) when the proof was verified: the service-initiated approval is created for it.

```rust
pub nonce: Option<String>
```

A fresh `AllowedBy-Nonce` to answer with (ABY-2 §3.2): the route asks for a current nonce.

```rust
pub struct ConfigError(pub String)
```

A configuration error: what to fix, raised by `Service::new` and `Route` validation.

## `allowedby (keys.rs)`

`sdks/rust/src/keys.rs`

```rust
pub struct Keys
```

The service's private keys. `Debug` never prints them.

```rust
pub signing: SigningKey
```

Signs the organisation profile and approval requests (`initiator.kid`).

```rust
pub disclosure: p256::SecretKey
```

Personal data is encrypted to it (ORG-1 §4; the disclosure callback is not in this SDK yet).

```rust
pub fn generate() -> Result<Keys, ConfigError>
```

Fresh random keys (lost at restart: agents then re-fetch `/.well-known/allowedby`).

```rust
pub fn from_seed(seed: &[u8; 32]) -> Result<Keys, ConfigError>
```

From an Ed25519 seed (e.g. from a secret manager), with a fresh disclosure key.

```rust
pub fn load_or_create(path: &Path) -> Result<Keys, ConfigError>
```

Load the keys from `path`, creating the file with fresh keys when it does not exist. Instances started together
all get the keys on disk; a file system without hard links is refused (create the file elsewhere).

## `allowedby (linking.rs)`

`sdks/rust/src/linking.rs`

```rust
pub type LinkAuthorize = Arc<dyn Fn(&str, &Route, &BTreeMap<String, String>) -> bool + Send + Sync>
```

The application's own rule for account linking: may the person linked to `account` call `route` with these path
values (as checked: decoded once)? Only `true` lets the request through.

```rust
pub struct LinkError(pub String)
```

Why `crate::Service::link_start` gave no code.

## `allowedby (request.rs)`

`sdks/rust/src/request.rs`

```rust
pub struct Request
```

A request: method, path (as received, not decoded), query (without `?`), headers and the body as sent.

```rust
pub method: String
```

`GET`, `POST`, ...

```rust
pub path: String
```

The path as sent (percent-encoded).

```rust
pub query: String
```

The query string without the `?`, empty when none.

```rust
pub headers: Vec<(String, String)>
```

Header names and values (names in any case).

```rust
pub body: Vec<u8>
```

The body bytes exactly as received (empty when none).

```rust
pub fn new(method: &str, target: &str) -> Request
```

A request for `method` and `target` (`/path?query`).

```rust
pub fn header(mut self, name: &str, value: &str) -> Request
```

Add a header.

```rust
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Request
```

Set the body.

```rust
pub fn single_header(&self, name: &str) -> Result<Option<&str>, Reject>
```

The value of header `name` (any case). `Err` when it is sent more than once: two values of an AllowedBy
header would be read differently by different components, so the request is refused (`invalid_request`).

```rust
pub fn first_header(&self, name: &str) -> Option<&str>
```

The first value of header `name` (any case).

```rust
pub struct Response
```

A response the SDK sends itself (discovery documents, refusals and challenges).

```rust
pub status: u16
```

The HTTP status.

```rust
pub headers: Vec<(String, String)>
```

Headers, `Content-Type` included.

```rust
pub body: Vec<u8>
```

The body.

```rust
pub fn json(status: u16, content_type: &str, value: &serde_json::Value) -> Response
```

A JSON response.

```rust
pub fn header(&self, name: &str) -> Option<&str>
```

The value of header `name` (any case).

## `allowedby (routes.rs)`

`sdks/rust/src/routes.rs`

```rust
pub const MAX_LIFETIME: i64 = 30 * 86_400
```

ABY-1 §2: no grant outlives 30 days, whatever a route map says.

```rust
pub enum Class {
    /// Looks at data. Standing grants up to 30 days.
    Read,
    /// Changes data, can be undone. Standing grants up to 7 days.
    Write,
    /// A hard-to-undo change. Approved every time, up to 1 day.
    WriteHard,
    /// Money or a final step. Approved every time, up to 1 hour.
    Irreversible,
}
```

How serious an action is (ABY-3 §4). Serious classes (`write-hard`, `irreversible`) need a single-use approval
that the service itself requests, for the exact request.

```rust
pub fn as_str(self) -> &'static str
```

The wire name.

```rust
pub fn parse(s: &str) -> Option<Class>
```

From the wire name.

```rust
pub fn is_serious(self) -> bool
```

`write-hard` and `irreversible`.

```rust
pub fn max_lifetime(self) -> i64
```

The longest grant this class accepts (Python `CLASS_MAX`).

```rust
pub fn status_max_age(self) -> i64
```

The oldest status list accepted (OAID-5 §6): 60 s for serious classes, 3600 s otherwise.

```rust
pub enum Authn {
    /// Any passkey.
    Software,
    /// A synced passkey or better.
    Synced,
    /// A hardware security key.
    Hardware,
}
```

The person's authenticator class a route requires (OAID-7 §4).

```rust
pub fn as_str(self) -> &'static str
```

The wire name.

```rust
pub fn parse(s: &str) -> Option<Authn>
```

From the wire name.

```rust
pub struct Threshold
```

One step of a class chosen by amount: up to `up_to` (inclusive), or the rest when `up_to` is `None`.

```rust
pub up_to: Option<String>
```

The amount, a decimal string such as `"1000.00"`; `None` for the last step.

```rust
pub class: Class
```

The class at or under that amount.

```rust
pub fn up_to(amount: &str, class: Class) -> Threshold
```

A step: amounts up to `amount` (inclusive) get `class`.

```rust
pub fn rest(class: Class) -> Threshold
```

The last step: every larger amount, and requests whose amount cannot be read.

```rust
pub struct Route
```

One line of the route map. Build it with `Route::new` (or `Route::get`, `Route::post`, ...) and the
setters; `crate::Service::new` validates every route and fails with a message that says what to fix.

```
use allowedby::{Class, Route};
let r = Route::delete("/notes/{id}")
    .capability("notes:delete")
    .class(Class::WriteHard)
    .level(2)
    .resource("note:{id}")
    .summary("Delete a note");
assert_eq!(r.path(), "/notes/{id}");
```

```rust
pub fn new(method: &str, path: &str) -> Route
```

A route for `method` (GET, POST, PUT, PATCH, DELETE) and `path` (`{param}` segments allowed). Defaults, as
the Python `route()`: class `read`, level 1, resource `<namespace>:*`, currency field `/currency`.

```rust
pub fn get(path: &str) -> Route
```

`Route::new("GET", path)`.

```rust
pub fn post(path: &str) -> Route
```

`Route::new("POST", path)`.

```rust
pub fn put(path: &str) -> Route
```

`Route::new("PUT", path)`.

```rust
pub fn patch(path: &str) -> Route
```

`Route::new("PATCH", path)`.

```rust
pub fn delete(path: &str) -> Route
```

`Route::new("DELETE", path)`.

```rust
pub fn capability(mut self, cap: &str) -> Route
```

The capability a grant must hold (`notes:read`). Without one the route is level 0: the agent's passport
is enough and no person approves.

```rust
pub fn class(mut self, class: Class) -> Route
```

The class (default `read`).

```rust
pub fn class_by_amount(mut self, steps: Vec<Threshold>) -> Route
```

A class chosen by the request's amount (ABY-3 §4): `[up_to(..), ..., rest(..)]`; needs `amount_field`.

```rust
pub fn level(mut self, level: u8) -> Route
```

The identity level (0 = the agent only, 1 = a passkey tap, 2 = verified identity, 3 = eIDAS high).

```rust
pub fn resource(mut self, resource: &str) -> Route
```

The resource the grant's `scope` must name; `{param}` takes the path parameter (`note:{id}`).

```rust
pub fn amount_field(mut self, pointer: &str) -> Route
```

The JSON Pointer of the amount in the body (`/total`): grants must then cap the amount.

```rust
pub fn currency_field(mut self, pointer: &str) -> Route
```

The JSON Pointer of the currency (default `/currency`).

```rust
pub fn authn(mut self, authn: Authn) -> Route
```

The person's authenticator class required (`synced` or `hardware`).

```rust
pub fn tier(mut self, tier: u8) -> Route
```

The agent key custody tier required (OAID-6), default 0.

```rust
pub fn max_lifetime(mut self, seconds: i64) -> Route
```

A shorter grant lifetime than the class allows, in seconds (60 s to 30 days).

```rust
pub fn summary(mut self, text: &str) -> Route
```

What the operation does, for agents (OpenAPI `summary`).

```rust
pub fn body_field(mut self, name: &str, description: &str) -> Route
```

One member of the JSON body, for agents (OpenAPI `requestBody`).

```rust
pub fn level_profile(mut self, profile: &str) -> Route
```

Level 3 for one OAID-7 §5.3 profile only (`eu` or `na`).

```rust
pub fn qes(mut self, on: bool) -> Route
```

A qualified electronic signature (OAID-7 §10). This SDK has no EU trusted list yet: `Service::new` refuses a
route with it, and a bare `Verifier` refuses every request on it with `qes_required` (fail closed).

```rust
pub fn requires_qes(&self) -> bool
```

Whether the route asks for a qualified electronic signature.

```rust
pub fn require_link(mut self, on: bool) -> Route
```

Account linking (ABY-3 §6, CONTRACT "Extended"): the person's AllowedBy identity must be linked to one of
your accounts (`crate::Service::link_start`), `403 human_not_linked` otherwise. When the path has the
`Route::account_param` parameter, the person must be linked to that account. A route of level 1 or more.

```rust
pub fn account_param(mut self, name: &str) -> Route
```

The path parameter that names one of your accounts (default `account`): with `require_link`, the linked
account must be that one; the approvals the service asks for name the person linked to it (AMH-1 §7).

```rust
pub fn nonce(mut self, on: bool) -> Route
```

AllowedBy-Nonce (ABY-2 §3.2, CONTRACT "Extended"): every proof needs a current service nonce (`401
invalid_signature` with a fresh one in `AllowedBy-Nonce` otherwise). Needs `Options::nonce(true)`; with it,
every `irreversible` route asks for one.

```rust
pub fn requires_nonce(&self) -> bool
```

Whether the route asks for a service nonce of its own (an `irreversible` one does too, with nonces on).

```rust
pub fn requires_link(&self) -> bool
```

Whether the route needs a linked account.

```rust
pub fn account_param_of(&self) -> &str
```

The path parameter that names an account (`account` by default).

```rust
pub fn method(&self) -> &str
```

The method.

```rust
pub fn path(&self) -> &str
```

The path pattern.

```rust
pub fn capability_name(&self) -> Option<&str>
```

The capability, if any.

```rust
pub fn class_of(&self) -> Class
```

The class (for a class chosen by amount: the class resolved for this request, or the base class).

```rust
pub fn level_of(&self) -> u8
```

The level.

```rust
pub fn tier_of(&self) -> u8
```

The custody tier.

```rust
pub fn amount_field_of(&self) -> Option<&str>
```

The amount field, if any.

```rust
pub fn resource_pattern(&self) -> String
```

The resource pattern (default `<namespace>:*`).

```rust
pub fn top_class(&self) -> Class
```

The most serious class the route can have (a class by amount: its last step).

```rust
pub fn validate(&self) -> Result<(), ConfigError>
```

Check the route, as Python's `route()` does. Called by `Service::new` and `Verifier::new`.

```rust
pub fn from_json(v: &Value) -> Result<Route, ConfigError>
```

A route from the Python SDK's JSON form (`{"method", "path", "capability", "class", "level", "resource",
"amount_field", "currency_field", "authn", "tier", "max_lifetime", "summary", "body", "qes",
"level_profile", "require_link", "account_param", "nonce"}`). Options the Python SDK has and this SDK does not
enforce yet (`mandate`, `disclose`, `disclose_optional`, `authority`) fail with a message naming them:
accepting an option and not enforcing it would fail open.

## `allowedby (service.rs)`

`sdks/rust/src/service.rs`

```rust
pub struct Org
```

ORG-1 §2: who runs the service, shown to people on the approval page.

```rust
pub fn new(legal_name: &str, country: &str) -> Org
```

The organisation's legal name and ISO 3166-1 alpha-2 country (`FR`).

```rust
pub fn website(mut self, url: &str) -> Org
```

Its website (https).

```rust
pub fn support(mut self, url: &str) -> Org
```

Where people get support (https).

```rust
pub fn privacy_policy(mut self, url: &str) -> Org
```

Its privacy policy (https); default `<origin>/privacy`.

```rust
pub struct Template
```

The sentences a person reads and signs for one capability, per language (AMH-1 §4, ABY-3 §5). Placeholders:
`{scope}`, `{fields}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, ...

```rust
pub fn new() -> Template
```

An empty template; add languages with `Template::lang`.

```rust
pub fn lang(mut self, lang: &str, summary: &str, line: &str) -> Template
```

The summary and the line in `lang` (`en`, `fr`, ...).

```rust
pub struct Options
```

Everything a `Service` is built from. `origin`, `node` and `org` are required; the rest has defaults.

```rust
pub fn new(origin: &str, node: &str) -> Options
```

`origin`: your API's public origin (`https://api.example.com`), exactly as agents call it.
`node`: the AllowedBy node you trust (`https://node.example.org`).

```rust
pub fn org(mut self, org: Org) -> Options
```

Your organisation (required).

```rust
pub fn route(mut self, route: Route) -> Options
```

Add a route of the map.

```rust
pub fn routes(mut self, routes: impl IntoIterator<Item = Route>) -> Options
```

Add several routes.

```rust
pub fn template(mut self, capability: &str, template: impl Into<Template>) -> Options
```

The template of `capability` (a `&str` is the English sentence).

```rust
pub fn key_file(mut self, path: impl Into<PathBuf>) -> Options
```

A private JSON file keeping the signing and disclosure keys across restarts, shared by every instance
(created on first use, mode 0600; the Python SDK's format).

```rust
pub fn keys(mut self, keys: Keys) -> Options
```

Keys you load yourself (from a secret manager). Takes precedence over `key_file`.

```rust
pub fn store(mut self, store: Arc<dyn Store>) -> Options
```

The store for the replay set, single use and counters (default: in memory, one process only).

```rust
pub fn trust_list(mut self, jws: &str) -> Options
```

A signed OAID-5 trust list (`oaid-trust+jwt`, signed by this service's own key) instead of trust on first
use of `node`.

```rust
pub fn refresh_seconds(mut self, seconds: u64) -> Options
```

Seconds between background refreshes (default 5, at least 1, at most 60).

```rust
pub fn node_max_level(mut self, level: u8) -> Options
```

The highest level `node` may give (default 3).

```rust
pub fn clock(mut self, clock: impl Fn() -> i64 + Send + Sync + 'static) -> Options
```

The clock (seconds since the epoch) for every time check: tests inject one.

```rust
pub fn title(mut self, title: &str) -> Options
```

The API title (OpenAPI), default `<legal name> API`.

```rust
pub fn version(mut self, version: &str) -> Options
```

The API version (OpenAPI), default `1.0.0`.

```rust
pub fn description(mut self, text: &str) -> Options
```

The API description (OpenAPI).

```rust
pub fn rfc9421(mut self, on: bool) -> Options
```

Accept the RFC 9421 Web Bot Auth profile instead of the proof JWT (ABY-2 §3.1).

```rust
pub fn http_client(mut self, http: Arc<dyn HttpClient>) -> Options
```

The HTTP client (default: `ureq` with the `http` feature; without it, none and no fetch at all).

```rust
pub fn background_refresh(mut self, on: bool) -> Options
```

Start the background refresh thread (default true). Tests that install documents themselves turn it off.

```rust
pub fn log_requests(mut self, on: bool) -> Options
```

Log one line per protected request on stderr: method, route pattern and outcome code (no ids, no paths).

```rust
pub fn unprotected(mut self, path: &str) -> Options
```

A page of your own that the SDK would refuse as a variant of a protected route, or as a path below one
(CONTRACT §2.10): an exact path (`/notes/new/`), or a template (`/notes/{id}/comments`), for every method.

```rust
pub fn unprotected_for(mut self, method: &str, path: &str) -> Options
```

The same for one method.

```rust
pub fn nonce(mut self, on: bool) -> Options
```

AllowedBy-Nonce (ABY-2 §3.2, CONTRACT "Extended"; default off): every `irreversible` route, and every route
with `Route::nonce(true)`, takes only a proof that carries a current service nonce (300 s). Nonces are made
from this service's key (`key_file`): every instance that shares it, and a restart, takes them.

```rust
pub fn rate(mut self, actor: (u64, u64), operator: (u64, u64)) -> Options
```

Rate limits (CONTRACT "Extended"): at most `actor.0` calls per agent (the passport's `sub`) and `operator.0`
per operator (`operator.id`) in any `actor.1` (`operator.1`) seconds, on the SDK's clock: `429 rate_limited`
beyond. Default 600 and 6000 calls per 60 s. Each number is 1 or more.

```rust
pub fn tenants(mut self, tenants: Value) -> Options
```

Tenants (ORG-1 §3.3) and tenant budgets (ORG-1 §5.3), CONTRACT "Extended": `{id: {name, routes:
{capability: override}, members_only, org, budgets: {capability: {max, currency, per, tz?}}}}`, for the routes
whose path has the `tenant` parameter. An override only tightens a route: `level`, `authn`, `mandate`,
`require_link`, `max_lifetime`, `amount_max`, `operators`. Checked by `Service::new`, which refuses any
other key or shape; the value is copied, never changed.

```rust
pub fn link_authorize( mut self, f: impl Fn(&str, &Route, &BTreeMap<String, String>) -> bool + Send + Sync + 'static, ) -> Options
```

Account linking (ABY-3 §6): your own rule for a linked account, `f(account, route, params)`. On a route with
`require_link`, the person linked to `account` (the one the path's `account_param` names, if it names one)
may call the route with these path values (as checked: decoded once) only when `f` returns `true`: `false`,
or a panic in it (caught), answers `403 human_not_linked`. It is only asked for a person who is linked. None
set: every linked person passes.

```rust
pub enum Outcome {
    /// Answer with this response (a discovery document, a refusal or a challenge); the app is not called.
    Respond(Response),
    /// Call the app: with the context on a route of the map, `None` on paths outside it (they reach the app
    /// unchanged and your own authentication applies).
    Forward(Option<Context>),
}
```

What the middleware does with a request.

```rust
pub struct Service
```

The AllowedBy service SDK. Clone it freely (it is an `Arc`).

```no_run
use allowedby::{Class, Options, Org, Route, Service};
let aby = Service::new(
    Options::new("https://notes.example", "https://node.example.org")
        .org(Org::new("Notes Ltd", "FR"))
        .route(Route::get("/notes").capability("notes:read").resource("note:*"))
        .route(Route::post("/notes").capability("notes:write").class(Class::Write).resource("note:new"))
        .template("notes:read", "Read your notes")
        .template("notes:write", "Write notes"),
)?;
# Ok::<(), allowedby::ConfigError>(())
```

```rust
pub fn new(opts: Options) -> Result<Service, ConfigError>
```

Build the service. Fails with a message that says what to fix: a bad origin or node, no organisation, a
country that is not ISO 3166-1, a route the reference would refuse, a capability without a template, an
unreadable key file or trust list. With the background refresh (the default), it returns once the first
refresh is over (done or failed, at most 5 s), so a service that starts cold holds node keys and status lists
before its first request; nothing is fetched at request time (ARCH-1 §4). Call it at startup, before serving.

```rust
pub fn verifier(&self) -> &Arc<Verifier>
```

The verifier (to install documents in tests or offline setups, or to verify by hand).

```rust
pub fn refresh_now(&self) -> Vec<String>
```

Refresh node statements and status lists now (the background thread does it on its own, and `new` waits
for its first run). -> failures.

```rust
pub fn origin(&self) -> &str
```

The public origin.

```rust
pub fn kid(&self) -> &str
```

The signing key's kid (`initiator.kid` of the approvals this service requests).

```rust
pub fn well_known(&self) -> Value
```

`/.well-known/allowedby`: vocabulary, templates, keys and the signed organisation profile.

```rust
pub fn openapi(&self) -> Value
```

`/openapi.json`: OpenAPI 3.1 for the route map (ABY-3 §5.1); each operation's `security` names the
capability it needs, `x-allowedby` adds class, level and amount.

```rust
pub fn api_catalog(&self) -> Value
```

`/.well-known/api-catalog` (RFC 9727): where this origin's APIs and their descriptions are.

```rust
pub fn endpoint(&self, req: &Request) -> Option<Response>
```

The SDK's own endpoints: discovery, and account linking (`POST /allowedby/link`, ABY-3 §6). `None` when the
request is for none of them. Only that exact path is the link endpoint: a variant of it (a trailing or doubled
`/`, an encoded letter) is no endpoint, so it asks for no approval and links nothing.

```rust
pub fn check(&self, req: &Request) -> Result<Option<Context>, Response>
```

The check on one request: `Ok(None)` outside the route map, `Ok(Some(context))` when accepted, `Err` with
the refusal or challenge to send. The route is matched on the normalised path, so an encoded path cannot
slip past the map; a spelling CONTRACT §2.10 refuses (`/x/../notes`, `/notes/7%0A`, `/notes/`) is refused
whether it matches a route or not.

```rust
pub fn handle(&self, req: &Request) -> Outcome
```

Everything the middleware does: the SDK's endpoints first, then the check on routes of the map.

```rust
pub fn challenge(&self, req: &Request, rej: &Reject) -> Response
```

The answer to a refusal (ABY-2 §6): a problem, with an AllowedBy challenge naming the action for the
challenge codes; for serious routes, with the approval this service created at the node (§7).

```rust
pub fn sign(&self, typ: &str, payload: &Value) -> String
```

Sign a payload as this service (`aby-org+jwt`, trust lists, ...): for tooling and tests.

```rust
pub fn link_start(&self, account: &str) -> Result<String, LinkError>
```

A linking code for one of your accounts (ABY-3 §6), valid 600 s: the signed-in account page shows it, and the
person gives it to their agent, which sends it to `POST /allowedby/link` under a single-use approval of
`aby:link`. The code is single use; using it links the person to `account` and revokes the account's other
pending codes. Fails for an empty account, or when 10 000 codes are pending.

```rust
pub fn link_start_ttl(&self, account: &str, ttl: std::time::Duration) -> Result<String, LinkError>
```

`Service::link_start`, valid `ttl` (1 s to a day).

```rust
pub fn handles(&self, req: &Request) -> bool
```

Whether the SDK acts on this method and path at all: one of its endpoints, or a route of the map (on the
normalised path, HEAD as GET). Adapters hand anything else to the app untouched, body included.

Variants of a protected route also count (see `Service::variant_refusal`), so they are refused rather
than handed on. `req.body` is ignored: adapters ask before reading it.

```rust
pub fn variant_refusal(&self, req: &Request) -> Option<Response>
```

CONTRACT §2.10: a request the route map does not match as sent, but that a router could still take to the
handler of a protected route, is refused (`400 invalid_request`): a method override, a variant of the path (a
trailing or doubled `/`, a dot segment, a control character, a format suffix, `;parameters`), or a path below a
route that ends in a parameter (`/notes/7/x`, for `/notes/{id}`). `None` otherwise, and for the pages declared
with `Options::unprotected`.

```rust
pub fn mount_refusal(&self, req: &Request, prefix: &str) -> Option<Response>
```

CONTRACT §2.10, mounts: the map holds paths as the app sees them. A map written with the prefix the app is
mounted at (axum `nest`) would protect nothing: such a request is refused.

```rust
pub fn route_class(&self, method: &str, path: &str) -> Option<Class>
```

The class of a route for diagnostics: `None` when no route matches.

## `allowedby (store.rs)`

`sdks/rust/src/store.rs`

```rust
pub struct Charge
```

One counter increment, applied with the others of a request all or nothing.

```rust
pub key: String
```

The counter's key.

```rust
pub increment: Micros
```

The increment: 1 for a count or a single use, an amount in millionths otherwise; negative in a refund.

```rust
pub max: Option<Micros>
```

The highest total allowed, if any.

```rust
pub until: Option<i64>
```

Keep the counter until this time (epoch seconds); `None` until the grant expires (the verifier fills it).

```rust
pub fn new(key: String, increment: Micros, max: Option<Micros>, until: Option<i64>) -> Charge
```

A charge.

```rust
pub struct StoreError(pub String)
```

A store failure (unreachable, timed out). The verifier refuses the request when it sees one.

```rust
pub trait Store: Send + Sync {
    /// Add `key` until `until` unless it is present and live at `now`: `false` when it already was (a replay).
    fn add(&self, key: &str, until: i64, now: i64) -> Result<bool, StoreError>;
    /// The live value of `key` at `now` (0 when absent or expired).
    fn get(&self, key: &str, now: i64) -> Result<Micros, StoreError>;
    /// All or nothing: apply every increment when every total stays within its max; `false` otherwise. Every
    /// charge's `until` is set (the verifier fills `None` before calling). A refund (CONTRACT §2 item 10: the SDK
    /// refused a request it had accepted, before its handler started) is a call with negative increments and no
    /// maximum: apply it exactly, whatever the totals become.
    fn charge(&self, charges: &[Charge], now: i64) -> Result<bool, StoreError>;
}
```

What the verifier needs from a store. Implementations must be atomic across every instance that shares them.

```rust
pub struct MemoryStore
```

The in-memory store, for one process only (several instances behind a load balancer need a shared store such
as `crate::RedisStore`, or a replayed proof is accepted once per instance). Thread-safe, bounded.

```rust
pub fn new(max_keys: usize) -> MemoryStore
```

A store holding at most `max_keys` live entries; when full of live entries it refuses (fail closed).

## `allowedby (redis_store.rs)`

`sdks/rust/src/redis_store.rs`

```rust
pub struct RedisStore
```

The Redis store: `RedisStore::open("redis://127.0.0.1/", "myapp")`.

```rust
pub fn open(url: &str, prefix: &str) -> Result<RedisStore, StoreError>
```

Connect to `url` (`redis://host:port/db`); every key starts with `prefix:aby:`.
