# AllowedBy for Rust # How it works Four parties take part: the **agent**, your **app**, the **person**, and a **node** that the person and your app trust. ## Three documents | Document | Who signs it | What it says | |---|---|---| | Passport | The node | Which agent this is, who operates it, and which key it holds | | Grant | The person (passkey) and the node | What the person approved, for which app, for how long, with which limits | | Proof | The agent | This request: method, address, body and time, with the agent's key | The agent sends the first two in `Allowed-By` and the proof in `AllowedBy-Proof`. ## What your app checks The SDK does all of this offline, on each request, in about a millisecond: 1. The passport or grant comes from a node you trust, is not expired, and is not withdrawn. 2. The person's passkey signed exactly this grant, and their identity level is enough for the route. 3. The proof is for this exact request, by the agent the grant names, and was never seen before. 4. The grant covers the action, the resource and the amount. 5. A serious action has an approval made for this request only, and it has not been used. Anything unknown, missing or unreadable is refused. See [error codes](https://docs.allowedby.com/errors) for each refusal. ## Levels: how sure you are of the person | Level | The person | Use it for | |---|---|---| | 0 | is not asked: only the agent is identified | Public or per-agent data | | 1 | tapped a passkey | Everyday actions | | 2 | has a verified legal identity, and tapped a passkey | Orders, contracts, anything hard to undo | | 3 | is verified at the highest level, with a hardware passkey | Payments and signatures of value | ## Classes: how serious the action is | Class | Example | Approval | |---|---|---| | `read` | List notes | Reused until it ends | | `write` | Add a note | Reused until it ends | | `write-hard` | Delete, publish | For that request, once | | `irreversible` | Pay, sign | For that request, once | For the last two, your app creates the approval itself. The agent cannot change what the person will read. ## The node A node issues passports, shows the approval page, and countersigns grants. It learns what was approved, never the data in your app. You choose which nodes to trust: one hosted node, your own, or a signed list. --- # AllowedBy for Rust This guide shows how a Rust API accepts AI agents that act for a person, with that person's approval. The concepts (routes, classes, levels, the approval flow, the context) are explained once in [docs/deploy-saas.md](https://docs.allowedby.com/guides/accept-agents); this guide shows them in Rust. Every code block below is a file under `sdks/rust/examples/` that CI builds, and a test checks that the blocks here are those files, byte for byte. Terms used once: an **agent** is software acting for a person; its **passport** (OAID-3) names the agent and its operator; a **grant** (ABY-1) is the person's signed approval; a **proof** (ABY-2 §3) is the agent's signature over one request; a **node** issues passports and runs the approval page; **JWS** is a signed JSON document (RFC 7515). ## Install Add the `allowedby` crate from the repository with the feature of your framework; it needs Rust 1.89 or newer. ```bash cargo add allowedby --git https://github.com/yannUpTo/allowedby --features axum ``` The command is the same on Linux, macOS and Windows (PowerShell). Features: | Feature | Gives | Default | |---|---|---| | `http` | The HTTP client for the background refresh and the service-initiated approval (`ureq`, rustls). | on | | `tower` | `AllowedByLayer`, a tower layer for any tower + `http` 1 stack (axum, hyper). | off | | `axum` | `allowedby::axum::protect` and the `AllowedByContext` extractor (includes `tower`). | off | | `actix` | `allowedby::actix::AllowedBy` middleware and the extractor. | off | | `redis` | `RedisStore`, a store shared by every instance. | off | Dependencies, each pinned (exact versions for the verification core, `Cargo.lock` for the integrations), and why: `serde` and `serde_json` (JSON; this SDK refuses duplicate member names and implements JCS, RFC 8785, itself), `sha2` (SHA-256), `ed25519-dalek` (EdDSA), `p256` (ES256 and the disclosure key), `getrandom` (keys and ids), `miniz_oxide` (zlib status lists), `ureq` (HTTP), `jiff` (feature `tz`, default: the IANA time-zone database, bundled, for tenant budgets in local calendar periods). The library forbids `unsafe` and denies `unwrap`, `expect` and `panic`. With Docker, without a local Rust toolchain (Linux and macOS): ```bash docker run --rm -v "$PWD":/src -w /src/sdks/rust rust:1.89 cargo test --all-features ``` Windows PowerShell: ```powershell docker run --rm -v "${PWD}:/src" -w /src/sdks/rust rust:1.89 cargo test --all-features ``` ## Quick start A complete axum app that serves `GET /notes` to agents once the person approved "Read your notes" (`sdks/rust/examples/quickstart.rs`): ```rust use allowedby::{AllowedByContext, Options, Org, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; async fn notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "for": ctx.human_id, "level": ctx.level})) } #[tokio::main] async fn main() -> Result<(), Box> { let aby = Service::new( Options::new("http://localhost:8790", "http://localhost:8000") .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes"), )?; let app = allowedby::axum::protect(Router::new().route("/notes", get(notes)), aby); let listener = tokio::net::TcpListener::bind("127.0.0.1:8790").await?; axum::serve(listener, app).await?; Ok(()) } ``` See it work against the local node. From the repository root, start the node (needs Python 3.10+ and `pip install -r requirements.txt`), then the app: ```bash python demo/run.py --port 8000 & cd sdks/rust && cargo run --features axum --example quickstart ``` ```powershell Start-Process python -ArgumentList "demo/run.py", "--port", "8000" cd sdks/rust; cargo run --features axum --example quickstart ``` Then ask as an agent without credentials would: ```bash curl -i http://localhost:8790/notes curl -s http://localhost:8790/.well-known/allowedby ``` ```powershell curl.exe -i http://localhost:8790/notes Invoke-RestMethod http://localhost:8790/.well-known/allowedby ``` The first answers `401` with `WWW-Authenticate: AllowedBy realm="localhost:8790", error="passport_required"`; the second lists the capability and the sentence the person signs. To see the whole flow (passport, approval with a passkey, retry, replay refused, revocation), run the interop test against this SDK (section Testing). Against the hosted node, use `https://demo.allowedby.com` as `node` and your public `https` origin as `origin`. ## Routes and templates Each route of your API that agents may call is one `Route`: the capability a grant must hold, its class, the identity level, and the resource it acts on; the template is the sentence the person reads and signs. | Builder | Meaning | Default | |---|---|---| | `Route::get(path)`, `post`, `put`, `patch`, `delete`, `Route::new(method, path)` | The operation. `{param}` segments are path parameters. | | | `.capability("notes:read")` | What the person allows, `namespace:action`. Without it the route is level 0: the agent's passport is enough. | none | | `.class(Class::Read)` | `Read`, `Write` (reversible), `WriteHard` (hard to undo), `Irreversible` (money, final steps). For `WriteHard` and `Irreversible` the SDK creates the approval, bound to the exact request, usable once. | `Read` | | `.class_by_amount(vec![Threshold::up_to("1000.00", Class::WriteHard), Threshold::rest(Class::Irreversible)])` | The class read from the request's amount (needs `amount_field`); no readable amount: the last class. | | | `.level(n)` | 0 agent only, 1 a passkey tap, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey. | 1 | | `.resource("note:{id}")` | The resource; `{param}` takes the path parameter. Grants must name it in their `scope`. | `:*` | | `.amount_field("/total")`, `.currency_field("/currency")` | JSON Pointers to the amount and currency in the body; grants must cap the amount. | none, `/currency` | | `.authn(Authn::Synced)` | The person's authenticator class at least `Synced` or `Hardware`. | any | | `.tier(n)` | The agent key's custody tier at least `n` (OAID-6). | 0 | | `.max_lifetime(seconds)` | A shorter grant lifetime than the class allows (60 s to 30 days). | the class's | | `.level_profile("eu")` | Level 3 from this OAID-7 §5.3 profile only (`eu` or `na`; see Level profiles). | none | | `.nonce(true)` | A current service nonce in every proof (see AllowedBy-Nonce); needs `Options::nonce(true)`. | off | | `.require_link(true)`, `.account_param("account")` | A person linked to your account (see Account linking). | off, `account` | | `.qes(true)` | A qualified electronic signature. No EU trusted list in this SDK yet: `Service::new` refuses it (a bare `Verifier` refuses every request with `qes_required`). | off | | `.summary(text)`, `.body_field(name, description)` | What the operation does and each body member, for agents (OpenAPI). | none | Templates: `.template("notes:read", "Read your notes")` is the English sentence; `Template::new().lang("en", summary, line).lang("fr", ...)` gives several languages. Placeholders: `{scope}`, `{fields}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`. `Service::new` refuses a capability without a template, a route the Python `route()` would refuse, and the route options this SDK does not enforce (`Route::from_json` names them). Every option, and the documents agents read (`sdks/rust/examples/routes.rs`): ```rust //! Every route option, and the documents agents read: prints /openapi.json and /.well-known/allowedby. //! Runs offline: `cargo run --example routes`. use allowedby::{Authn, Class, Options, Org, Request, Route, Service, Template, Threshold}; fn main() -> Result<(), Box> { let aby = Service::new( Options::new("https://api.example.com", "https://node.example.org") .org(Org::new("Invoices Ltd", "FR").website("https://example.com").support("https://example.com/help")) // level 0: the agent's passport is enough, no person approves .route(Route::get("/me").level(0).summary("Who is calling")) // read, level 1 (the defaults): a passkey tap, standing for up to 30 days .route(Route::get("/invoices").capability("invoices:read").resource("invoice:*").summary("List invoices")) // write: standing for up to 7 days; the body members are described for agents .route( Route::post("/invoices/{id}/comments") .capability("invoices:comment") .class(Class::Write) .resource("invoice:{id}") .body_field("text", "the comment"), ) // write-hard, level 2, synced passkey or better: approved for this exact request, used once .route( Route::post("/invoices/{id}/approve") .capability("invoices:approve") .class(Class::WriteHard) .level(2) .authn(Authn::Synced) .resource("invoice:{id}") .amount_field("/total") .currency_field("/currency"), ) // a payment: its class depends on the amount; level 3 for the EU profile, hardware key, custody tier 1 .route( Route::post("/invoices/{id}/pay") .capability("invoices:pay") .class_by_amount(vec![ Threshold::up_to("1000.00", Class::WriteHard), Threshold::rest(Class::Irreversible), ]) .amount_field("/total") .level(3) .level_profile("eu") .authn(Authn::Hardware) .tier(1) .max_lifetime(600) .resource("invoice:{id}"), ) .template("invoices:read", "Read your invoices") .template( "invoices:comment", Template::new().lang("en", "Comment on {scope}", "Comment on {scope}").lang( "fr", "Commenter {scope}", "Commenter {scope}", ), ) .template("invoices:approve", "Approve {scope}, up to {amount.max} {amount.currency}") .template("invoices:pay", "Pay {scope}, up to {amount.max} {amount.currency}") .background_refresh(false), )?; for path in ["/openapi.json", "/.well-known/allowedby"] { if let allowedby::Outcome::Respond(r) = aby.handle(&Request::new("GET", path)) { println!("{path}: {}", String::from_utf8_lossy(&r.body)); } } Ok(()) } ``` ### AllowedBy-Nonce (extended) AllowedBy-Nonce (ABY-2 §3.2, CONTRACT "Extended") makes a captured proof useless after 300 s, whatever its own time says. `Options::nonce(true)` turns it on (off by default). Every `irreversible` route, and every route with `.nonce(true)`, then takes only a proof that carries a current service nonce. A proof without one gets `401 invalid_signature` with a fresh nonce in `AllowedBy-Nonce`, and the agent retries once with it. With RFC 9421 the nonce is the request's `AllowedBy-Nonce` header, and it counts only when the signature covers it. A route with `.nonce(true)` while the service has nonces off is refused by `Service::new`. Nonces carry no state: a nonce is its issue time and a MAC of it under a key derived from your signing key (HKDF-SHA256, info `allowedby/nonce/v1`). So every instance that shares the key file, and a restart, takes the nonces of the others, and so do the SDKs of the other languages on the same key file. ### Level profiles (extended) `.level_profile("eu")` or `.level_profile("na")` on a level-3 route (OAID-7 §5.3) takes only a person verified to level 3 by a source of that profile: another profile, or none, gets `401 level_insufficient`. The approval the service asks for names the profile, so the person's home node offers only those sources. A level-3 route without a profile takes any. ### Tenants (extended) `Options::tenants(json!({id: {name, routes: {capability: override}, members_only, org, budgets}}))` (ORG-1 §3.3) gives each customer account of a multi-tenant API its own rules, on the routes whose path has the `tenant` parameter (`/t/{tenant}/invoices/{id}`). An override only tightens the route of its capability: `level` (the higher counts), `authn` (the stronger), `mandate` and `require_link` (true wins; a link raises level 0 to 1), `max_lifetime` (the shorter), `amount_max` (the lower; above it `403 capability_denied`) and `operators` (an allowlist of `operator.id`; any other operator gets `403 capability_denied`). Overrides are by capability, and a level-0 route has none (it needs no grant: `Service::new` refuses one), so they never reach a route the agent alone may call. A tenant the path names but the option does not has the route as the map has it. `Service::new` refuses an id outside `[A-Za-z0-9_-]{1,64}`, any other key (`policy` among them), a `name` that is not 1-200 characters, an `org` that is not an https origin with no path, a capability the map does not have, a value of another shape, and an override or a budget on a capability that has a route without `{tenant}` (the error names that route): a misspelt override would leave the route as loose as yours. The option is read, never changed. This SDK verifies no company mandates yet (CONTRACT: company mandates), so until it does, a tenant route with `mandate: true`, and every route of a `members_only` tenant with an `org`, refuses every request with `401 mandate_required`, with no challenge: no approval could ever pass there, so none is asked for. `members_only` is the whole tenant's: it holds on the routes the agent alone may call too (level 0). The overrides `qes` and `authority` are refused by `Service::new` (no EU trusted list, no authority policies yet). ### Tenant budgets (extended) `tenants[id].budgets[capability] = {max, currency, per: day | week | month, tz?}` (ORG-1 §5.3) caps what a tenant spends on a capability per calendar period. Every route of that capability needs `amount_field`, or `Service::new` refuses the budget. The service counts the amounts it accepts in the verifier's store, per tenant, capability, currency, zone and period, so every instance that shares the store shares the count. A request without an amount in the budget's currency, or over what is left, gets `403 budget_exceeded`, before any challenge: no approval is asked for one that cannot succeed. A refused request counts nothing, and a refund (CONTRACT §2 item 10) gives the amount back. When the store does not answer, the request gets `503 status_stale` with `Retry-After`, and what the check spent is given back. `tz` is any IANA zone (`Europe/Paris`; `UTC` by default): the default feature `tz` bundles the IANA database (`jiff`), and a period runs from a local midnight to the next one, so a day with a daylight-saving change lasts 23 or 25 hours. Without that feature, only `UTC` and the fixed offsets `Etc/GMT-N` / `Etc/GMT+N`; `Service::new` refuses any other zone. ### Rate limits (extended) Every service limits calls per agent (the passport's `sub`) and per operator (`operator.id`): 600 and 6000 calls per 60 s by default, `Options::rate((calls, seconds), (calls, seconds))` for others (each number 1 or more, checked by `Service::new`). A call over either limit gets `429 rate_limited` with `Retry-After`. The window slides on the SDK's clock (a call at t sees those of the last `seconds`). A call counts once its proof is verified and is no replay, whatever is decided after it (a call refused as `grant_required` counts); a call the limit refuses counts for neither limit. A call with an expired agent key is refused (`actor_expired`) before it counts. The counts are per process, like `MemoryStore`. ### Account linking (extended) Account linking (ABY-3 §6, CONTRACT "Extended") ties a person's AllowedBy identity to one of your own accounts, so that a route reaches only the account the person owns. - **The code.** While the user is signed in, your account page calls `aby.link_start(&account)` (or `link_start_ttl(&account, ttl)`, 1 s to a day; 600 s by default) and shows the code. It is single use, 96 random bits. Using one revokes the account's other pending codes. It fails (`LinkError`) for an empty account, or when 10 000 codes are pending. The SDK always draws the code: the cargo feature `conformance-hooks`, which lets the conformance runner set one, is for this SDK's own tests only; never enable it in an app. - **The endpoint.** The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves it itself, through `Service::handle` and every adapter; your router needs no route for it. An unknown or expired code is refused with `400 invalid_request` before any approval is asked for. Then the request needs a single-use grant of `aby:link`: without one, the SDK asks the node for an approval bound to this request (the agent gets a challenge). Accepted, the pair (home node, pairwise id) is linked to the account, replacing any other person linked to it: `200 {"linked": true}`. Only that exact path is the endpoint: a variant (`/allowedby/link/`, `/allowedby/%6Cink`, `//allowedby/link`) or a method override asks for no approval and links nothing. `/.well-known/allowedby` names the endpoint (`link`), and `/openapi.json` lists it. - **The routes.** `Route::require_link(true)` needs a linked person (`403 human_not_linked` otherwise), on a route of level 1 or more: `Service::new` refuses it on a level-0 route. When the path has the `account_param` parameter (`Route::account_param`, default `account`), the person must be linked to that very account. The context's `linked_account` is the account, also when the path names none. A grant that names no person for your service (`human.id`) is refused with `401 grant_insufficient` on the endpoint and on these routes. An approval the service asks for on a route that names a linked account names that person (`human_hint`, AMH-1 §7). - **Your own rule.** `Options::link_authorize(|account, route, params| ...)` is your authorisation of the linked account for the resource. Only `true` lets the request through; `false`, or a panic in it, is `403 human_not_linked`. It is asked only for a person linked to the account the path names. - **Rule 5.** A handler shared with a route that needs a link runs for another route only if that route needs one too, with the account in the same path segment, by the same parameter. - **Limits.** Codes and links live in memory, per process: behind several instances, a code is used on the instance that issued it, and a link holds on the instance that made it. At most 10 000 pending codes and 100 000 links (the oldest link goes first). ## Framework recipes Wrap your whole app so the SDK's endpoints come first, then the check on every route of the map, then your handlers; paths outside the map reach your app unchanged and the body is handed on intact. Variants of a protected route that a router could still dispatch to its handler are refused with `400 invalid_request` (CONTRACT §2.10): a trailing or doubled `/` (`/notes/`, `//notes`), a dot segment (`/notes/..`, `/x/../notes`), a control character (`/notes%0A`), `;parameters`, a format suffix (`/notes.json`), a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `?_method=`) on a path of the map. axum and actix-web read no method from a form body (`_method`); do not add a middleware that rewrites paths or methods between the SDK and your handlers. A wildcard serves more paths than the route map names: `/notes/{*id}` (axum) or `/notes/{id:.*}` (actix-web) also runs for `/notes/7/x`, which no approval was checked for, and `/notes/{id}/{*rest}` runs for `/notes/7/archive/x` next to `DELETE /notes/{id}/archive`. No adapter here can tell which handler its router chose (actix-web's resource map ignores method guards), so, for the methods the map uses there, every request below a route of the map that has a parameter, or that a parameter taking several segments would make one, is refused with `400` (stricter than CONTRACT §2.10 asks). A route without a parameter keeps its sub-resources: `GET /notes/7` runs when only `GET /notes` is mapped. Under axum's `nest`, wrap the outer router with `protect`, and write the map with the paths it sees. A map that names the mount point of a nested `protect` would protect nothing: its requests are refused with `400`. Under actix-web's `web::scope("/api").wrap(AllowedBy::new(..))` it is the other way round: the middleware sees the whole path, so the map holds `/api/notes/{id}`; a map written with the scope's own paths (`/notes/{id}`) would protect nothing, and its requests are refused with `400`. Each framework below has a complete app, the notes API of `sdks/interop/reference_app.py`, that CI runs against a real node, agent and person: the whole interop test (26 scenarios: levels 0, 1 and 2, every refusal), on Rust stable and on Rust 1.89, for each version in `sdks/rust/examples/frameworks.json`. **axum**: `allowedby::axum::protect(router, service)` wraps a `Router`; handlers take `AllowedByContext` (or `Option` on paths outside the map). Feature `axum` (`sdks/rust/examples/frameworks/axum/main.rs`): ```rust //! axum: the notes API of sdks/interop/reference_app.py (sdks/CONTRACT.md §6), the interop test's app. //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features axum --example interop //! //! GET /me (level 0), GET /health (outside the route map), GET /notes (notes:read, L1), POST /notes //! (notes:write, write, L1), DELETE /notes/{id} (notes:delete, write-hard, L2); anything else 404. use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use axum::body::Bytes; use axum::extract::{Path, State}; use axum::http::StatusCode; use axum::routing::get; use axum::{Json, Router}; use serde_json::{json, Value}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = Arc>; type Reply = (StatusCode, Json); fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } async fn health() -> Json { Json(json!({"ok": true})) } async fn me(ctx: AllowedByContext) -> Json { Json(json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } async fn get_notes(State(db): State, ctx: AllowedByContext) -> Reply { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx .human_id .as_ref() .and_then(|h| db.by_person.get(h)) .map(|n| list(n.as_slice())) .unwrap_or_else(|| json!([])); (StatusCode::OK, Json(json!({"notes": mine}))) } async fn add_note(State(db): State, ctx: AllowedByContext, body: Bytes) -> Reply { let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return (StatusCode::BAD_REQUEST, Json(json!({"error": "text: a string of 1 to 2000 characters"}))); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } (StatusCode::CREATED, Json(json!({"id": id}))) } async fn delete_note(State(db): State, ctx: AllowedByContext, Path(id): Path) -> Reply { let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| *i != id); } (StatusCode::OK, Json(json!({"deleted": id}))) } async fn not_found() -> Reply { (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))) } fn env(k: &str) -> Result { std::env::var(k).map_err(|_| format!("{k} is not set")) } #[tokio::main] async fn main() -> Result<(), Box> { let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "18790".into()).parse()?; let refresh: u64 = std::env::var("ALLOWEDBY_REFRESH_SECONDS").unwrap_or_else(|_| "5".into()).parse()?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), )?; // the handlers of the routes of the map, registered with the service: CONTRACT §2.10 rule 5 holds for them (an // alias of one on another path, another method or a catch-all is refused); /health is the app's own page use allowedby::axum as aby_routing; let router = Router::new() .route("/health", get(health)) .route("/me", aby_routing::get(&aby, "/me", me)) .route("/notes", aby_routing::get(&aby, "/notes", get_notes)) .route("/notes", aby_routing::post(&aby, "/notes", add_note)) .route("/notes/{id}", aby_routing::delete(&aby, "/notes/{id}", delete_note)) .fallback(not_found) .with_state(Db::default()); let app = allowedby::axum::protect(router, aby); let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; println!("interop app listening on {port}"); axum::serve(listener, app).await?; Ok(()) } ``` **tower**: `AllowedByLayer::new(service).layer(inner)` (feature `tower`) gives a `tower::Service>`; the inner service receives `http::Request>>` (`allowedby::tower::AbyReqBody`): the original body outside the route map, the verified bytes on it, with an `AllowedByContext` in its extensions. Verification runs on Tokio's blocking pool, since a serious route's challenge calls the node. Here the service behind the layer routes by hand, and axum only serves the connection (`sdks/rust/examples/frameworks/tower/main.rs`): ```rust //! The bare tower layer: the notes API of sdks/interop/reference_app.py as a service that routes by hand behind //! `AllowedByLayer` (no axum router behind the layer), so that the interop test runs against the layer alone //! (sdks/CONTRACT.md §6). axum only serves the connection. //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features axum --example interop_tower use allowedby::tower::{AbyReqBody, AllowedByLayer}; use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use bytes::Bytes; use http::{Method, Request, Response, StatusCode}; use http_body_util::{BodyExt, Full, Limited}; use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::Infallible; use std::sync::{Arc, Mutex}; use tower::Layer; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = Arc>; fn reply(status: StatusCode, v: Value) -> Response> { let mut r = Response::new(Full::new(Bytes::from(v.to_string()))); *r.status_mut() = status; r.headers_mut().insert(http::header::CONTENT_TYPE, http::HeaderValue::from_static("application/json")); r } fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } /// The app's own routing: by method and path segments, as a hand-written hyper service does. async fn app(db: Db, req: Request>) -> Result>, Infallible> { let ctx = req.extensions().get::().cloned(); let method = req.method().clone(); let path = req.uri().path().to_owned(); let segments: Vec<&str> = path.split('/').skip(1).collect(); let read = method == Method::GET || method == Method::HEAD; // a protected handler without the context the layer gives: the layer let the request through unchecked let unchecked = || reply(StatusCode::INTERNAL_SERVER_ERROR, json!({"error": "no AllowedBy context"})); Ok(match (segments.as_slice(), ctx) { (["health"], _) if read => reply(StatusCode::OK, json!({"ok": true})), (["me"], Some(ctx)) if read => { reply(StatusCode::OK, json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } (["notes"], Some(ctx)) if read => { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx.human_id.as_ref().and_then(|h| db.by_person.get(h)).map(|n| list(n.as_slice())); reply(StatusCode::OK, json!({"notes": mine.unwrap_or_else(|| json!([]))})) } (["notes"], Some(ctx)) if method == Method::POST => { let body = Limited::new(req.into_body(), 1 << 20).collect().await.map(|b| b.to_bytes()).unwrap_or_default(); let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return Ok(reply(StatusCode::BAD_REQUEST, json!({"error": "text: a string of 1 to 2000 characters"}))); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } reply(StatusCode::CREATED, json!({"id": id})) } (["notes", _], Some(ctx)) if method == Method::DELETE => { // the id as the SDK checked it, never this app's own reading of the raw path let Some(id) = ctx.params.get("id") else { return Ok(reply(StatusCode::NOT_FOUND, json!({}))) }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| i != id); } reply(StatusCode::OK, json!({"deleted": id})) } (["me"] | ["notes"], None) if read || method == Method::POST => unchecked(), (["notes", id], None) if method == Method::DELETE && !id.is_empty() => unchecked(), _ => reply(StatusCode::NOT_FOUND, json!({"error": "not found"})), }) } fn env(k: &str) -> Result { std::env::var(k).map_err(|_| format!("{k} is not set")) } #[tokio::main] async fn main() -> Result<(), Box> { let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "18790".into()).parse()?; let refresh: u64 = std::env::var("ALLOWEDBY_REFRESH_SECONDS").unwrap_or_else(|_| "5".into()).parse()?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), )?; let db = Db::default(); let inner = tower::service_fn(move |req| app(db.clone(), req)); let layered = AllowedByLayer::new(aby).layer(inner); // axum only serves the connection: nothing is routed before the layer let server = axum::Router::new().fallback_service(layered); let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; println!("interop app listening on {port}"); axum::serve(listener, server).await?; Ok(()) } ``` **hyper**: the same tower service, served by hyper's own HTTP/1 connection through hyper-util's `TowerToHyperService`, without a framework (`sdks/rust/examples/frameworks/hyper/main.rs`): ```rust //! hyper 1 without a framework: the notes API of sdks/interop/reference_app.py as a hand-written service behind //! `AllowedByLayer`, served by hyper's own HTTP/1 connection (hyper-util's `TowerToHyperService` turns the tower //! service into a hyper one). The interop test runs against it (sdks/CONTRACT.md §6). //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features tower --example interop_hyper use allowedby::tower::{AbyReqBody, AllowedByLayer}; use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use bytes::Bytes; use http::{Method, Request, Response, StatusCode}; use http_body_util::{BodyExt, Full, Limited}; use hyper::body::Incoming; use hyper::server::conn::http1; use hyper_util::rt::TokioIo; use hyper_util::service::TowerToHyperService; use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::Infallible; use std::sync::{Arc, Mutex}; use tower::Layer; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = Arc>; fn reply(status: StatusCode, v: Value) -> Response> { let mut r = Response::new(Full::new(Bytes::from(v.to_string()))); *r.status_mut() = status; r.headers_mut().insert(http::header::CONTENT_TYPE, http::HeaderValue::from_static("application/json")); r } fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } /// The app's own routing: by method and path segments. async fn app(db: Db, req: Request>) -> Result>, Infallible> { let ctx = req.extensions().get::().cloned(); let method = req.method().clone(); let path = req.uri().path().to_owned(); let segments: Vec<&str> = path.split('/').skip(1).collect(); let read = method == Method::GET || method == Method::HEAD; // a protected handler without the context the layer gives: the layer let the request through unchecked let unchecked = || reply(StatusCode::INTERNAL_SERVER_ERROR, json!({"error": "no AllowedBy context"})); Ok(match (segments.as_slice(), ctx) { (["health"], _) if read => reply(StatusCode::OK, json!({"ok": true})), (["me"], Some(ctx)) if read => { reply(StatusCode::OK, json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } (["notes"], Some(ctx)) if read => { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx.human_id.as_ref().and_then(|h| db.by_person.get(h)).map(|n| list(n.as_slice())); reply(StatusCode::OK, json!({"notes": mine.unwrap_or_else(|| json!([]))})) } (["notes"], Some(ctx)) if method == Method::POST => { let body = Limited::new(req.into_body(), 1 << 20).collect().await.map(|b| b.to_bytes()).unwrap_or_default(); let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return Ok(reply(StatusCode::BAD_REQUEST, json!({"error": "text: a string of 1 to 2000 characters"}))); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } reply(StatusCode::CREATED, json!({"id": id})) } (["notes", _], Some(ctx)) if method == Method::DELETE => { // the id as the SDK checked it, never this app's own reading of the raw path let Some(id) = ctx.params.get("id") else { return Ok(reply(StatusCode::NOT_FOUND, json!({}))) }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| i != id); } reply(StatusCode::OK, json!({"deleted": id})) } (["me"] | ["notes"], None) if read || method == Method::POST => unchecked(), (["notes", id], None) if method == Method::DELETE && !id.is_empty() => unchecked(), _ => reply(StatusCode::NOT_FOUND, json!({"error": "not found"})), }) } fn env(k: &str) -> Result { std::env::var(k).map_err(|_| format!("{k} is not set")) } #[tokio::main] async fn main() -> Result<(), Box> { let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "18790".into()).parse()?; let refresh: u64 = std::env::var("ALLOWEDBY_REFRESH_SECONDS").unwrap_or_else(|_| "5".into()).parse()?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), )?; let db = Db::default(); let service = AllowedByLayer::new(aby).layer(tower::service_fn(move |req| app(db.clone(), req))); let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; println!("interop app listening on {port}"); loop { let (stream, _) = listener.accept().await?; let service = TowerToHyperService::new(service.clone()); tokio::spawn(async move { if let Err(e) = http1::Builder::new().serve_connection(TokioIo::new(stream), service).await { eprintln!("connection: {e}"); } }); } } ``` **actix-web**: `App::new().wrap(allowedby::actix::AllowedBy::new(service))`; handlers take `AllowedByContext`. Feature `actix` (`sdks/rust/examples/frameworks/actix-web/main.rs`): ```rust //! actix-web: the notes API of sdks/interop/reference_app.py behind the actix-web middleware; the interop test runs //! against it (sdks/CONTRACT.md §6). //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features actix --example interop_actix use actix_web::{web, App, HttpResponse, HttpServer}; use allowedby::actix::AllowedBy; use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use serde_json::{json, Value}; use std::collections::HashMap; use std::sync::Mutex; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = web::Data>; fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } async fn health() -> HttpResponse { HttpResponse::Ok().json(json!({"ok": true})) } async fn me(ctx: AllowedByContext) -> HttpResponse { HttpResponse::Ok().json(json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } async fn get_notes(db: Db, ctx: AllowedByContext) -> HttpResponse { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx .human_id .as_ref() .and_then(|h| db.by_person.get(h)) .map(|n| list(n.as_slice())) .unwrap_or_else(|| json!([])); HttpResponse::Ok().json(json!({"notes": mine})) } async fn add_note(db: Db, ctx: AllowedByContext, body: web::Bytes) -> HttpResponse { let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return HttpResponse::BadRequest().json(json!({"error": "text: a string of 1 to 2000 characters"})); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } HttpResponse::Created().json(json!({"id": id})) } async fn delete_note(db: Db, ctx: AllowedByContext, id: web::Path) -> HttpResponse { let id = id.into_inner(); let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| *i != id); } HttpResponse::Ok().json(json!({"deleted": id})) } async fn not_found() -> HttpResponse { HttpResponse::NotFound().json(json!({"error": "not found"})) } fn env(k: &str) -> std::io::Result { std::env::var(k).map_err(|_| std::io::Error::other(format!("{k} is not set"))) } fn number(k: &str, default: &str) -> std::io::Result { std::env::var(k) .unwrap_or_else(|_| default.into()) .parse() .map_err(|_| std::io::Error::other(format!("{k}: a number"))) } #[actix_web::main] async fn main() -> std::io::Result<()> { let port: u16 = number("PORT", "18790")?; let refresh: u64 = number("ALLOWEDBY_REFRESH_SECONDS", "5")?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), ) .map_err(std::io::Error::other)?; let db: Db = web::Data::new(Mutex::new(Notes::default())); let server = HttpServer::new(move || { // the handlers of the routes of the map, registered with the service: CONTRACT §2.10 rule 5 holds for them (an // alias of one on another path, another method or a catch-all is refused); /health is the app's own page App::new() .app_data(db.clone()) .wrap(AllowedBy::new(aby.clone())) .route("/health", web::get().to(health)) .service(allowedby::actix::get(&aby, "/me", me)) .service(allowedby::actix::get(&aby, "/notes", get_notes).post(add_note)) .service(allowedby::actix::delete(&aby, "/notes/{id}", delete_note)) .default_service(web::to(not_found)) }) .bind(("127.0.0.1", port))?; println!("interop app listening on {port}"); server.run().await } ``` **Any other framework**: build an `allowedby::Request` (method, path as sent, query, headers, body bytes) and call `service.handle(&request)`: `Outcome::Respond(response)` is what to send, `Outcome::Forward(context)` means call your handler with that context (`None` outside the route map). `sdks/rust/examples/testing.rs` shows it. ### Your own sub-resources With `GET /notes/{id}` on the map, your own `GET /notes/{id}/comments` is refused with `400` until you declare it. The refusal names the route it is below and the line to add, and the service lists the routes concerned once in its log at startup. Declare the template with the method your handler serves, and a word of its own (a template that a route of any method reaches must name its method). A page the rules above take for a variant is declared by its exact path, `Options::unprotected_for("GET", "/notes.json")`. An entry a router may read as another path (`;`, `%`, `\`, dot segments), or that is a route of the map but for its last `/`, fails at construction (`sdks/rust/examples/sub_resources.rs`): ```rust //! Your own sub-resources: below a route of the map that has a parameter, a path is refused (400) until the app //! declares that a handler of its own serves it. The refusal names the line to add. Runs offline: //! `cargo run --example sub_resources`. use allowedby::{Options, Org, Outcome, Request, Route, Service}; fn main() -> Result<(), Box> { let notes = || { Options::new("https://notes.example", "https://node.example.org") .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes/{id}").capability("notes:read").resource("note:{id}")) .template("notes:read", "Read note {scope}") .background_refresh(false) }; let comments = Request::new("GET", "/notes/7/comments"); // not declared: refused, and the answer says what to add let Outcome::Respond(r) = Service::new(notes())?.handle(&comments) else { return Err("not refused".into()) }; let detail = String::from_utf8(r.body)?; assert_eq!(r.status, 400); assert!(detail.contains(r#"Options::unprotected_for(\"GET\", \"/notes/{id}/\")"#), "{detail}"); assert!(!detail.contains("comments"), "the answer never repeats the path: {detail}"); // declared: it reaches your app, without a context (your own authentication applies) let aby = Service::new(notes().unprotected_for("GET", "/notes/{id}/comments"))?; assert_eq!(aby.handle(&comments), Outcome::Forward(None)); println!("ok: /notes/7/comments is refused until declared, then reaches the app"); Ok(()) } ``` ### Handler identity (CONTRACT §2.10 rule 5): register your handlers Rule 5 asks an adapter to refuse any request not checked for a route that would run that route's handler: an alias on another path, another method, a catch-all, one function on two routes that do not cover each other. No Rust adapter sees on its own which handler its router chose: - **axum** (`protect`, and any tower stack): the layer runs in front of the whole `Router`, before it routes. axum names the rule it matched only to the matched route's own services (`MatchedPath`, after routing), and nothing in axum tells which function a route runs: a `Router` cannot be listed, and two `.route(..)` calls with one handler are two unrelated services. - **actix-web** (`AllowedBy` on the `App` or a `web::scope`): the middleware runs before the resource is chosen. `ServiceRequest::match_pattern()` compares patterns only (it ignores method guards), and actix-web does not expose which function a resource's route runs. So register the handlers of your routes with the SDK. With axum: `allowedby::axum::{get, post, put, patch, delete, any}(&service, path, handler)` in place of `axum::routing`'s, with the path the route map writes for them (the axum app above does). Under `nest`, with `protect` around the outer router, that is the full path, mount prefix included: `.nest("/api", Router::new().route("/notes/{id}", delete(&aby, "/api/notes/{id}", remove)))`; a handler registered with the path inside the mount answers `400` on its route, with a refusal that says so. Each registration records the handler's type (every function item and closure expression has its own; the closures one generic function returns share one, so they count as one handler) and its method and path, and runs after routing, where axum names the rule that matched. Rule 5 then holds for registered handlers, so the Known gaps line says `rules 1-4, 6` and this guide says rule 5 with registered handlers: - a registered handler of a route of the map runs only for a request checked for that route (HEAD is read as GET); registered on another path, under another method or behind a catch-all (`any(&service, "/{*rest}", handler)`), it answers `400` there, with a refusal that names the fix and never the path; - registered on two routes of the map, it runs only for a request checked for a route that covers the other (the same capability, resource and amount fields; a level, tier, class and passkey at least as strong; a grant lifetime no longer); otherwise for neither, and the service logs both routes once, at registration; - a registered handler that serves no route of the map runs as before for a request checked for no route; for a request checked for a route, it is refused like any handler of another route: a literal page `/notes/export` registered next to `GET /notes/{id}` on the map gets that route's check and then `400` (CONTRACT §2.10 rule 5: a handler that serves only the request's value is refused). Give such a page a path no route of the map matches, or register it with `axum::routing`; - every handler registered with `axum::routing` behaves as before: the extractor below is what protects it. A function registered once with the SDK and again with `axum::routing` is seen only where it is registered with the SDK: register every use of a protected handler. With actix-web, register them the same way: `allowedby::actix::{get, post, put, patch, delete, any}(&service, path, handler)` build a resource whose handlers are registered, which you give to `.service(..)`; add the other methods of the same path on it (`get(&aby, "/notes", list).post(add)`), as one actix-web resource serves one path. The check runs after the resource is chosen, with the pattern actix-web matched (the actix-web app above does). Inside `web::scope("/api")`, the route map writes the whole path and the resource its own pattern: `allowedby::actix::delete(&aby, "/api/notes/{id}", remove).at("/notes/{id}")`. The same refusals apply, and the same pair line is logged. A request is checked against the route actix-web runs for it: the first of the resource's routes whose method takes it. For HEAD, every GET and `any` route of the resource is checked, and each must allow it, so a registered handler never runs unchecked whichever of them actix-web picks. What protects an unregistered handler is that it takes `AllowedByContext`. The extractor fails (`500`) when no route of the map was checked for the request, so a protected handler's body never runs for an unchecked request, whatever path reached it; it cannot tell which route was checked. So give each protected route its own handler, taking `AllowedByContext` (not `Option`), register it, and do not give it to another path or a catch-all (`/{*rest}`, `{tail:.*}`) through the framework's own API. A site-wide catch-all that dispatches protected actions on paths no route maps (a legacy front controller that deletes at `/legacy/delete?id=7`) is not something any adapter can see, and a front controller shared by routes of different capabilities or resources runs for none of them: give each protected route its own handler. ### A request changed after the check A layer between the SDK and your handler can rewrite an accepted request: a tower layer or axum's `map_request` on the router inside `protect`, an actix-web middleware wrapped before `AllowedBy`, a rewrite of the URI or a method override. The handler would then act on values the person never approved. So the SDK keeps, with an accepted request, the method it checked (HEAD as GET) and its normalised path, and refuses it with `400 invalid_request` (never repeating the path) where it can see the handler run: in the `AllowedByContext` extractor (axum's `Option` too; with actix-web, `allowedby::actix::OptionalContext`, since actix-web turns an error of an extractor inside `Option` into `None`), and in the handlers registered with `allowedby::axum::{get, ...}` or `allowedby::actix::{get, ...}`. Another spelling of the same path (`/notes/%37` for `/notes/7`) and a mount axum's `nest` took off the path are not changes. Limit: a handler that takes no `AllowedByContext` and is not registered runs whatever a layer did to the request. Put no layer that rewrites the method or the URI after the SDK, and take path values from the context's `params`. ## The context A handler of an accepted request receives `AllowedByContext`, a read-only `Context` (it derefs to it) with who is calling, for whom, and with which approval. | Field | Type | What | |---|---|---| | `agent` | `String` | The agent: its passport `sub`. | | `operator` | `String` | The agent's operator (vendor), `operator.id`. | | `human_id` | `Option` | The person's pairwise id at your service (different at every service); `None` on level-0 routes. Key their data on it. | | `level` | `u8` | The identity level of this request (0 to 3). | | `capabilities` | `Vec` | The grant's capabilities. | | `display` | `Option` | What the person approved: `{summary, lines, lang}`. | | `gid`, `rev`, `jti` | `Option`, `Option`, `Option` | The leaf grant's id, revision and `jti`. | | `acting_for` | `Option` | Company mandates: always `None` (not supported yet). | | `tenant` | `Option` | The `{tenant}` path parameter, when the route has one, decoded once as in `params`. | | `route` | `RouteInfo` | The route matched: method, path pattern, capability, class used, level. | | `chain` | `Vec<(String, Option)>` | The grant chain, leaf first: (gid, rev). | | `human_iss` | `Option` | The person's home node. | | `linked_account` | `Option` | On a `require_link` route, your account the person is linked to (Account linking); `None` elsewhere. | | `proof_jti` | `String` | The proof's `jti` (or RFC 9421 nonce), for your audit log. | | `run`, `call` | `Option`, `Option` | The agent's run id and call number, audit only. | | `params` | `BTreeMap` | The route's path values as the SDK checked them: each `{name}` of the route, from the normalised path, decoded once. | Act on `params`, never on your own reading of the raw path: the two can differ (`/notes/%37` is checked as note `7`; `/notes/%2561` gives `%61`, decoded once, not `a`). A framework router already hands your handler the values it matched (axum's `Path`, actix-web's `web::Path`), and the SDK refuses a path that it would read another way; a service without a router, behind the tower layer or on hyper, takes them from `params` (`sdks/rust/examples/frameworks/tower/main.rs`, `sdks/rust/examples/frameworks/hyper/main.rs`). ## Production In production, keep the keys in a private file or a secret manager, share one store between instances, choose your trust (one node, or a signed trust list), and leave the refresh running. - **Keys** (`key_file(path)` or `keys(Keys)`): the signing key (Ed25519) signs your organisation profile and your approval requests; the disclosure key (P-256) receives personal data. Without either, both are new at each start and agents re-fetch `/.well-known/allowedby`. The file uses the Python SDK's format, is created with mode 0600, and concurrent starts agree on one file (first writer wins, every start uses the keys on disk). The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `key_file` at it, or write it from your secret manager. An existing file works anywhere. - **Store** (`store(Arc)`): the replay set, single-use consumption and counters. `MemoryStore` (the default) is for one process only: behind a load balancer use `RedisStore` (feature `redis`) or your own `Store`. A store error refuses the request (`503 status_stale`, the agent retries). - **Refunds** (CONTRACT §2 item 10): the check spends the approval (a single-use grant's mark, its `count` and `amount` totals). When the SDK itself then refuses that accepted request before its handler started, it gives back exactly what the request spent, once, so the approval serves the request on its own route afterwards. That covers the guard of a registered handler (axum's `allowedby::axum::{get, post, ..}`, actix-web's `allowedby::actix::{resource, get, ..}`): a refusal of rule 5, or of a request changed after the check. Nothing is refunded once a guard handed the request to its handler, for a refusal of your own (a handler, a layer or a middleware that answers), or for the `AllowedByContext` and `OptionalContext` extractors, which run inside the handler. A request for a route that no registered handler serves is spent for good as the layer or middleware hands it on (a handler the SDK does not know may act on it), and every request is once the app has answered it. A refunded request never reaches a handler, even dispatched again (`400`). A refund the store does not take leaves the approval spent, and is logged without request data. A store refunds with a `charge` of negative increments and no maximum, which it applies exactly (`Store::charge`). - **Trust**: by default the node's key is pinned on first fetch (trust on first use). `trust_list(jws)` takes a signed OAID-5 list (anchors, programs, vouching, witnesses) instead; it must be signed by your own key. - **Refresh**: node statements and status lists are fetched every `refresh_seconds` (default 5, at least 1, at most 60) on a background thread, never on the request path. `Service::new` returns once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, or one that scales to zero) holds the node's keys and status lists before its first request; it blocks the calling thread that long, so build the service at startup, before serving. A failed refresh logs `[verifier] refresh failed: ...` on stderr and the cache keeps serving; an old status list then fails closed. - **Logging**: nothing per request by default; `log_requests(true)` prints the method, route pattern and outcome code (no ids, no tokens, no bodies). - **Several instances**: share the key file (or `Keys`) and the store; each instance refreshes on its own. - **Listening**: the example listens on loopback (`127.0.0.1`) unless `ALLOWEDBY_BIND` says otherwise (the name the Python SDK reads); in a container set `ALLOWEDBY_BIND=0.0.0.0`, as the repository's Dockerfile does. (`sdks/rust/examples/production.rs`): ```rust //! Production settings: keys kept in a private file, a store shared by every instance (Redis), an optional signed //! trust list, the refresh interval and request logs. Environment: ALLOWEDBY_ORIGIN, ALLOWEDBY_NODE, //! ALLOWEDBY_KEY_FILE, REDIS_URL, ALLOWEDBY_TRUST_LIST (a file, optional), PORT, ALLOWEDBY_BIND (the address to //! listen on: loopback only by default, `0.0.0.0` in a container). use allowedby::{AllowedByContext, Options, Org, RedisStore, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; use std::sync::Arc; async fn notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "for": ctx.human_id})) } #[tokio::main] async fn main() -> Result<(), Box> { let env = |k: &str| std::env::var(k).map_err(|_| format!("{k} is not set")); let mut opts = Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Ltd", "FR").privacy_policy("https://notes.example/privacy")) .route(Route::get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes") // the signing key and the disclosure key: created once (mode 0600), the same on every instance .key_file(env("ALLOWEDBY_KEY_FILE")?) // replay set, single use and counters shared by every instance .store(Arc::new(RedisStore::open(&env("REDIS_URL")?, "notes")?)) // node statements and status lists every 5 s (status lists at least every 60 s whatever you set) .refresh_seconds(5) .log_requests(true); if let Ok(path) = std::env::var("ALLOWEDBY_TRUST_LIST") { // an OAID-5 trust list signed by this service's own key, instead of trust on first use of the node opts = opts.trust_list(std::fs::read_to_string(path)?.trim()); } let aby = Service::new(opts)?; let app = allowedby::axum::protect(Router::new().route("/notes", get(notes)), aby); let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "8080".into()).parse()?; // unset or empty: loopback only let bind = std::env::var("ALLOWEDBY_BIND").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "127.0.0.1".into()); axum::serve(tokio::net::TcpListener::bind((bind.as_str(), port)).await?, app).await?; Ok(()) } ``` ## Agents The Rust SDK is a service SDK only: agents call your API with the Python or TypeScript agent SDKs (see [python.md](https://docs.allowedby.com/sdk/python) and [js.md](https://docs.allowedby.com/sdk/js)), which handle passports, proofs, challenges and approvals. ## Errors Every refusal is an RFC 9457 problem (`application/problem+json`, `type: https://allowedby.org/errors/`); the codes and statuses are the same in every AllowedBy SDK. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed envelope, a body that is not a JSON object, a passport and grants mixed, a header sent twice, a variant of a protected path or a method override. | Fix the request. | | `passport_required` | 401 | No `Allowed-By` header. | The agent gets a passport from its node and retries. | | `invalid_signature` | 401 | A signature, proof, replay, request binding or chain failed. | Sign a fresh proof for this exact request; never replay. | | `untrusted_node` | 401 | The document comes from a node this service does not trust (or not fetched yet). | Use a trusted node; the service checks its trust. | | `insufficient_witnesses` | 401 | The node's log has too few trusted witnesses (trust list `witnesses_min`). | The node operator fixes its witnessing. | | `grant_required` | 401 | The route needs the person's approval (challenge). | Ask the person through the node (or follow `approve`), then retry. | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator, digest). | Ask for an approval that covers it. | | `level_insufficient` | 401 | A higher identity level is needed. | The person verifies their identity at the level named, then approves. | | `qes_required` | 401 | A qualified electronic signature is needed. | Approve with a qualified signature (not available with this SDK yet). | | `authority_required` | 401 | The organisation's co-approvers must approve (extended; never sent by this SDK). | Collect the approvals the policy names. | | `mandate_required` | 401 | The person must act under a company mandate (this SDK refuses every grant acting for an organisation: mandates are not supported yet). No challenge on a route that needs a mandate (no approval could pass there); elsewhere the challenge asks the person to approve as themselves. | Approve as yourself, where no mandate is needed. | | `expired` | 401 | The grant expired. | Ask for a new approval. | | `not_yet_valid` | 401 | The grant is not valid yet. | Retry later or check clocks. | | `revoked` | 401 | The grant, an ancestor or the person's registration was withdrawn. | Ask again; the person may refuse. | | `actor_expired` | 401 | The agent's key in the grant expired (`rebind: true`). | Rebind the grant to the new key (ABY-1 §6) or ask again. | | `class_lifetime_exceeded` | 401 | The grant lasts longer than the route's class allows. | Ask for a shorter approval. | | `single_use_consumed` | 401 | The single-use grant was already used. | Ask for a new approval for this request. | | `capability_denied` | 403 | No such route or capability. | Do not retry. | | `tier_insufficient` | 403 | The agent's key custody or the person's authenticator is too weak. | Use a stronger key custody or authenticator. | | `human_not_linked` | 403 | The person is not linked to the account this route serves (Account linking), or `link_authorize` said no. | Link the account (`aby:link`). | | `budget_exceeded` | 403 | The tenant's budget for this action cannot take this amount, or the request has none in its currency (Tenant budgets). | Wait for the next period or raise the budget. | | `rate_limited` | 429 | Too many calls of this agent or of its operator (Rate limits). | Retry after `Retry-After`. | | `envelope_too_large` | 431 | `Allowed-By` plus `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (a grant and one child). | Send a shorter chain. | | `status_stale` | 503 | The revocation list is too old, or the replay store is unreachable (fail closed). | Retry after `Retry-After`. | The challenge codes (`grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`, `actor_expired`, and `mandate_required` except on a route that needs a mandate) come with `WWW-Authenticate: AllowedBy realm=..., error=..., action=..., scope=..., class=..., level=..., tier=...`; on `write-hard` and `irreversible` routes also `code`, `approve`, `poll`, `request` and `expires` of the approval the service created. ## Testing Run the CONF-1 vectors, the unit and adapter tests, and the interop test against a real node; test your own app with plain values, without a browser. ```bash cd sdks/rust cargo test --all-features --test vectors -- --nocapture # prints "481/481 cases passed" cargo test --all-features # REDIS_URL=redis://127.0.0.1:6379/ runs the Redis tests too cargo build --release --features axum --example interop cd ../.. && pip install -r requirements.txt python sdks/interop/interop.py --cmd "sdks/rust/target/release/examples/interop" --cwd . ``` ```powershell cd sdks/rust cargo test --all-features --test vectors -- --nocapture cargo test --all-features cargo build --release --features axum --example interop cd ../..; pip install -r requirements.txt $env:INTEROP_PORT_BASE = "19800" python sdks/interop/interop.py --cmd "sdks/rust/target/release/examples/interop" --cwd . ``` The vectors are read from `vectors/` at run time (`vectors/profiles.json`, profile `verifier`); the runner fails on any failure or any case it cannot run. The interop test prints `26/26 interop scenarios passed`. Your own app, offline (`sdks/rust/examples/testing.rs`): ```rust //! Test your own app without a browser or a node: the SDK's answers are plain values. //! Runs offline: `cargo run --example testing`. use allowedby::{Class, Code, Options, Org, Outcome, Request, Route, Service}; fn main() -> Result<(), Box> { 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::delete("/notes/{id}").capability("notes:delete").class(Class::WriteHard).level(2)) .template("notes:read", "Read your notes") .template("notes:delete", "Delete note {scope}") .clock(|| 1_761_480_000) // a fixed time: tests are repeatable .background_refresh(false), // no network: install documents yourself if you need them )?; // a call without a passport gets the challenge every agent understands let Outcome::Respond(r) = aby.handle(&Request::new("GET", "/notes")) else { return Err("not refused".into()) }; assert_eq!(r.status, Code::PassportRequired.status()); assert_eq!(r.header("WWW-Authenticate"), Some("AllowedBy realm=\"notes.example\", error=\"passport_required\"")); // a path outside the route map reaches your app unchanged, without a context assert_eq!(aby.handle(&Request::new("GET", "/health")), Outcome::Forward(None)); // the discovery document names every capability and the sentence the person signs let wk = aby.well_known(); assert_eq!(wk["templates"]["notes:read"]["summary"]["en"], "Read your notes"); assert_eq!(wk["capabilities"][1]["class"], "write-hard"); println!("ok: refusals, paths outside the map and discovery behave as expected"); Ok(()) } ``` To accept requests in tests, install a test node's statement and status list with `service.verifier().install_node(..)` and `install_status_list(..)`, and sign passports and proofs with `SigningKey` and `proto::make_proof` (the crate's `tests/common/mod.rs` does exactly this). ## Reference The public API: one service, its options, the route map, the context, the store, and the building blocks the conformance runner uses. | Item | What | |---|---| | `Service::new(Options) -> Result` | The SDK. `Clone` (an `Arc`). Starts the background refresh and returns once its first run is over (at most 5 s). | | `Service::handle(&Request) -> Outcome` | The middleware in one call: endpoints, then the check. | | `Service::check(&Request) -> Result, Response>` | The check alone (`Ok(None)` outside the map). | | `Service::endpoint(&Request) -> Option` | The SDK's own endpoints alone: discovery, and `POST /allowedby/link`. | | `Service::link_start(&account) -> Result`, `link_start_ttl(&account, ttl)` | A linking code for one of your accounts (Account linking). | | `Service::challenge(&Request, &Reject) -> Response` | The answer to a refusal. | | `Service::well_known()`, `openapi()`, `api_catalog()` | The discovery documents as JSON. | | `Service::verifier()`, `refresh_now()`, `origin()`, `kid()`, `sign(typ, payload)` | The verifier, a refresh now, the origin, the signing kid, a JWS signed by this service. | | `Options::new(origin, node)` | `.org`, `.route`, `.routes`, `.template`, `.key_file`, `.keys`, `.store`, `.trust_list`, `.unprotected`, `.unprotected_for`, `.refresh_seconds`, `.node_max_level`, `.clock`, `.title`, `.version`, `.description`, `.rfc9421`, `.http_client`, `.background_refresh`, `.log_requests`, `.link_authorize`, `.nonce`, `.rate`, `.tenants`. | | `Org::new(legal_name, country)` | `.website`, `.support`, `.privacy_policy`. | | `Template::new().lang(lang, summary, line)`, `Template::from(&str)` | A capability's sentences. | | `Route`, `Class`, `Authn`, `Threshold`, `MAX_LIFETIME` | The route map (section Routes and templates); `Route::validate`, `Route::from_json`. | | `Outcome::{Respond(Response), Forward(Option)}` | What to do with a request. | | `Request { method, path, query, headers, body }`, `Response { status, headers, body }` | Framework-neutral HTTP. | | `Context`, `RouteInfo`, `AllowedByContext` | The verified context (section The context); `AllowedByContext` is the extractor. | | `LinkError`, `LinkAuthorize` | Why no linking code was given; the type of `Options::link_authorize`'s rule. | | `Code`, `Reject`, `ConfigError` | Refusal codes (`as_str`, `status`, `is_challenge`), a refusal, a configuration error. | | `Store`, `MemoryStore`, `RedisStore`, `Charge`, `StoreError` | The store interface and its implementations. | | `Keys`, `SigningKey` | The service's keys (`load_or_create`, `generate`, `from_seed`). | | `AllowedByLayer` (feature `tower`), `allowedby::axum::protect` (feature `axum`), `allowedby::actix::AllowedBy` (feature `actix`) | The framework integrations. | | `verifier::Verifier` | `verify`, `node_doc`, `status_bit`, `human`, `registration`, `install_node`, `install_status_list`, `set_nodes`, `nodes`. | | `trust::{Statement, TrustList, Checkpoint}`, `refresh::{Refresher, Trust}` | Node statements, OAID-5 trust lists, signed notes and witnesses, the refresh. | | `jose`, `json`, `proto`, `b64`, `util`, `caps`, `http` | Building blocks: JWS and thumbprints, strict JSON and JCS, grant cores and digests, base64, paths and amounts, constraints and display, the HTTP client trait. | | `SPEC_VERSION` | `"0.2.14"`. | --- # Error codes Every SDK answers the same codes with the same statuses; `tools/docs.py` checks this table and every language guide against the verifier. A refusal is `application/problem+json` with `type: https://allowedby.org/errors/`. A `401` that the agent can resolve also carries a challenge in `WWW-Authenticate: AllowedBy ...` (ABY-2 §6). `429` and `503` carry `Retry-After`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | ## How an agent reacts - **Asks the person, then retries once:** `grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`. - **Gets a new passport or rebinds:** `passport_required`, `actor_expired`. - **Waits, then retries:** `rate_limited`, `status_stale`. - **Signs again, once:** `invalid_signature` (a fresh proof; check the clock and the URL). - **Stops:** every other code. Retrying cannot succeed until someone changes something. --- # Build with an AI assistant Coding assistants integrate AllowedBy well when they read these pages rather than guess. Give them one of the following. ## The documentation as tools (MCP) ```bash claude mcp add --transport http allowedby-docs https://docs.allowedby.com/mcp ``` The assistant can then search the documentation, read a page, get a recipe in your language and look up an error. Any assistant that supports MCP over HTTP can use the same address. ## One file per language Everything needed to accept agents in one language, in one Markdown file: | Language | File | |---|---| | Python | [llms/python.txt](https://docs.allowedby.com/llms/python.txt) | | JavaScript | [llms/js.txt](https://docs.allowedby.com/llms/js.txt) | | Go | [llms/go.txt](https://docs.allowedby.com/llms/go.txt) | | Java | [llms/java.txt](https://docs.allowedby.com/llms/java.txt) | | C# | [llms/dotnet.txt](https://docs.allowedby.com/llms/dotnet.txt) | | PHP | [llms/php.txt](https://docs.allowedby.com/llms/php.txt) | | Ruby | [llms/ruby.txt](https://docs.allowedby.com/llms/ruby.txt) | | Rust | [llms/rust.txt](https://docs.allowedby.com/llms/rust.txt) | The index of every page is [llms.txt](https://docs.allowedby.com/llms.txt), and all guides together are [llms-full.txt](https://docs.allowedby.com/llms-full.txt). Any page is also Markdown at its own address with `.md` added. ## A prompt that works ```text Read https://docs.allowedby.com/llms/python.txt. Then add AllowedBy to this app: - list the routes an agent may call, and propose a capability, class and level for each; ask me before going on; - write the sentence a person will sign for each capability; - add the middleware, and key every query on the person's id from the context; - run the app, show me that a protected route answers 401, and write the tests from the "test" recipe. ``` Change `python` to your language. ## Rules an assistant must keep - Never take the person's identity from the agent's input: use the id in the verified context. - Never catch a refusal and continue. - Never log `Allowed-By`, `AllowedBy-Proof` or a request body. - Use a shared store as soon as there is more than one process, and a key file in production. - Put the middleware outside anything that rewrites the path or the method. A weekly test gives an assistant only these public pages, asks it to integrate AllowedBy in a new app, and runs the end-to-end scenarios on the result. --- # Recipes in Rust (each is run against a real node on every version) ## Quickstart A whole app that lets agents in with the person's approval. ```rust use allowedby::{AllowedByContext, Options, Org, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; use std::env::var; async fn list_notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "person": ctx.human_id})) } #[tokio::main] async fn main() -> Result<(), Box> { // your app's public URL, and the node you trust: people approve there let aby = Options::new(&var("ALLOWEDBY_ORIGIN")?, &var("ALLOWEDBY_NODE")?) .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*")) .template("notes:read", "Read your notes"); // what the person approves let app = Router::new().route("/notes", get(list_notes)); let app = allowedby::axum::protect(app, Service::new(aby)?); let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{}", var("PORT")?)).await?; axum::serve(listener, app).await?; Ok(()) } ``` ## See which agent is calling Know the agent and its verified operator, before any person is involved. ```rust let aby = aby.route(Route::get("/me").level(0).summary("Which agent is calling")); let app = app.route("/me", get(me)); async fn me(ctx: AllowedByContext) -> Json { Json(json!({"agent": ctx.agent, "operator": ctx.operator})) } ``` ## Let an agent read The person approves once with a passkey; the approval is reused until it expires or they withdraw it. ```rust let aby = aby .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .template("notes:read", "Read your notes"); let app = app.route("/notes", get(list_notes)); async fn list_notes(ctx: AllowedByContext, State(notes): State) -> Json { Json(json!({"notes": notes.list(&ctx.human_id)})) } ``` ## Let an agent write A change the person can undo: one approval, reused like a read. ```rust let aby = aby .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:*") .summary("Add a note") .body_field("text", "the note"), ) .template("notes:write", "Add and change your notes"); let app = app.route("/notes", post(add_note)); async fn add_note( ctx: AllowedByContext, State(notes): State, Json(input): Json, ) -> (StatusCode, Json) { (StatusCode::CREATED, Json(notes.add(&ctx.human_id, &input.text))) } ``` ## Ask before deleting A change that is hard to undo: your app asks the person for that exact request, and the approval works once. ```rust let aby = aby .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:delete", "Delete {scope}"); let app = app.route("/notes/{id}", delete(delete_note)); async fn delete_note( ctx: AllowedByContext, State(notes): State, Path(id): Path, ) -> Result, Refusal> { // The person approved this exact request, and it works once. match notes.delete(&ctx.human_id, &id) { Some(note) => Ok(Json(json!({"deleted": note.id}))), None => Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))), } } ``` ## Take a payment The person approves the amount and the payee; any other amount or payee is refused. ```rust let aby = aby .route( Route::post("/payees/{payee}/payments") .capability("payments:send") .class(Class::Irreversible) .level(2) .resource("payee:{payee}") .amount_field("/amount") .summary("Pay someone") .body_field("amount", "a decimal string, e.g. 40.00") .body_field("currency", "e.g. EUR"), ) .template("payments:send", "Pay {amount.max} {amount.currency} to {scope}"); let app = app.route("/payees/{payee}/payments", post(pay)); async fn pay(Path(payee): Path, Json(payment): Json) -> (StatusCode, Json) { // The payee, the amount and the currency are the ones the person approved. (StatusCode::CREATED, Json(json!({"paid": payment.amount, "currency": payment.currency, "to": payee}))) } ``` ## Take a high-value payment Level 3: a verified identity and a hardware passkey. Anything weaker is refused. ```rust let aby = aby .route( Route::post("/payees/{payee}/transfers") .capability("transfers:send") .class(Class::Irreversible) .level(3) .authn(Authn::Hardware) .resource("payee:{payee}") .amount_field("/amount") .summary("Send a bank transfer") .body_field("amount", "a decimal string, e.g. 4000.00") .body_field("currency", "e.g. EUR"), ) .template("transfers:send", "Transfer {amount.max} {amount.currency} to {scope}"); let app = app.route("/payees/{payee}/transfers", post(transfer)); async fn transfer( ctx: AllowedByContext, Path(payee): Path, Json(order): Json, ) -> (StatusCode, Json) { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. let sent = json!({"sent": order.amount, "currency": order.currency, "to": payee, "level": ctx.level}); (StatusCode::CREATED, Json(sent)) } ``` ## Set a spending limit The person approves an amount per month once; the SDK keeps the total and refuses what goes over. ```rust let aby = aby .route( Route::post("/orders") .capability("orders:place") .class(Class::Write) .level(1) .resource("order:new") .amount_field("/total") .summary("Place an order") .body_field("total", "a decimal string, e.g. 60.00") .body_field("currency", "e.g. EUR"), ) .template("orders:place", "Order for up to {amount.max} {amount.currency} per {amount.per}"); let app = app.route("/orders", post(place_order)); async fn place_order(Json(order): Json) -> (StatusCode, Json) { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. (StatusCode::CREATED, Json(json!({"ordered": order.total, "currency": order.currency}))) } ``` ## Start and cancel a subscription The person approves the plan and its monthly price once; you charge it until they cancel. ```rust let aby = aby .route( Route::post("/plans/{plan}/subscription") .capability("plans:subscribe") .class(Class::WriteHard) .level(1) .resource("plan:{plan}") .amount_field("/monthly") .summary("Subscribe to a plan") .body_field("monthly", "the price per month, e.g. 12.00") .body_field("currency", "EUR"), ) .route( Route::get("/subscription") .capability("plans:read") .level(1) .resource("plan:*") .summary("Your subscription"), ) .route( Route::delete("/subscription") .capability("plans:cancel") .class(Class::WriteHard) .level(1) .resource("plan:mine") .summary("Cancel your subscription"), ) .template( "plans:subscribe", "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel", ) .template("plans:read", "See your subscription") .template("plans:cancel", "Cancel your subscription"); let app = app .route("/plans/{plan}/subscription", post(subscribe)) .route("/subscription", get(subscription).delete(cancel)); async fn subscribe( ctx: AllowedByContext, State(subscriptions): State, Path(plan): Path, Json(price): Json, ) -> (StatusCode, Json) { // Approved once, with the price: your billing charges it every month (subscriptions.rs) until it is cancelled. (StatusCode::CREATED, Json(subscriptions.start(&ctx.human_id, plan, price.monthly))) } async fn subscription( ctx: AllowedByContext, State(subscriptions): State, ) -> Result, Refusal> { let found = subscriptions.get(&ctx.human_id); found.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no subscription"})))) } async fn cancel( ctx: AllowedByContext, State(subscriptions): State, ) -> Result, Refusal> { let found = subscriptions.cancel(&ctx.human_id); found.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no subscription"})))) } ``` ## Accept a sub-agent An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first. ```rust let aby = aby.route( Route::get("/notes/{id}/summary") .capability("notes:read") .level(1) .resource("note:{id}") .summary("Summarise one note"), ); let app = app.route("/notes/{id}/summary", get(summarise)); async fn summarise( ctx: AllowedByContext, State(notes): State, Path(id): Path, ) -> Result, Refusal> { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same. match notes.get(&ctx.human_id, &id) { Some(note) => { let words = note.text.split_whitespace().count(); Ok(Json(json!({"words": words, "delegated": ctx.chain.len() > 1}))) } None => Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))), } } ``` ## Let the person withdraw The person takes an approval back on their node; your app refuses it from the next refresh. ```rust let aby = aby .route( Route::get("/export").capability("notes:export").level(1).resource("note:*").summary("Export your notes"), ) .template("notes:export", "Export your notes"); let app = app.route("/export", get(export)); async fn export(ctx: AllowedByContext, State(notes): State) -> Json { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. Json(json!({"approval": ctx.gid, "notes": notes.list(&ctx.human_id)})) } ``` ## Serve only the person's own data human_id is the same person every time at your app: look their data up with it. ```rust let aby = aby.route( Route::get("/notes/{id}").capability("notes:read").level(1).resource("note:{id}").summary("Read one note"), ); let app = app.route("/notes/{id}", get(get_note)); async fn get_note( ctx: AllowedByContext, State(notes): State, Path(id): Path, ) -> Result, Refusal> { // human_id is this person's id at your app, always the same. Look up with it, never by note id alone. let note = notes.get(&ctx.human_id, &id); note.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))) } ``` ## Refuse in your own handler Your rules still apply: the agent receives your status and your JSON, and can correct itself. ```rust let aby = aby.route( Route::put("/notes/{id}") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:{id}") .summary("Change a note") .body_field("text", "1 to 280 characters"), ); let app = app.route("/notes/{id}", put(change_note)); async fn change_note( ctx: AllowedByContext, State(notes): State, Path(id): Path, Json(input): Json, ) -> Result, Refusal> { if !(1..=280).contains(&input.text.chars().count()) { // the agent gets this status and this JSON return Err((StatusCode::UNPROCESSABLE_ENTITY, Json(json!({"error": "text: 1 to 280 characters"})))); } let note = notes.update(&ctx.human_id, &id, &input.text); note.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))) } ``` ## Test your app Run your app's tests without a browser, a phone or a node. ```rust #[cfg(test)] mod tests { use super::*; use allowedby::{Outcome, Request}; fn service() -> Service { let (aby, _) = notes_app("https://notes.example", "https://node.example.org"); Service::new(aby.background_refresh(false)).expect("a valid configuration") } #[test] fn a_request_without_a_passport_is_refused() { let Outcome::Respond(refusal) = service().handle(&Request::new("GET", "/notes")) else { panic!("accepted"); }; assert_eq!(refusal.status, 401); assert!(refusal.header("WWW-Authenticate").is_some_and(|h| h.contains("passport_required"))); } #[test] fn agents_see_the_sentence_the_person_approves() { let discovery = service().well_known(); assert_eq!(discovery["templates"]["notes:read"]["summary"]["en"], "Read your notes"); } } ```