# AllowedBy for Java
# 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 Java and Kotlin
The service SDK for the JVM: your API accepts AI agents that act for a person, and the person approves with a passkey
tap. The SDK publishes your discovery documents, verifies every agent request offline (ABY-2 §5), answers challenges,
and creates the approval itself for serious actions. It follows `sdks/CONTRACT.md`; the
concepts (routes, classes, levels, the approval flow) are explained in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents).
## Install
Build the SDK from `sdks/java` with the Maven wrapper, then depend on `org.allowedby:allowedby-core` and the module of
your framework; Java 17 or later, and no runtime dependency in the core.
The SDK is not published to Maven Central yet (publishing is a separate step), so install it in your local Maven
repository first. Maven itself comes from the wrapper (a script; no binary in git). Linux and macOS:
```bash
cd sdks/java
./mvnw -B install -DskipTests
```
Windows (PowerShell):
```powershell
cd sdks\java
.\mvnw.cmd -B install -DskipTests
```
With Docker only (no local JDK), from the repository root:
```bash
docker run --rm -v "$PWD:/repo" -w /repo/sdks/java maven:3.9.11-eclipse-temurin-21@sha256:6fdc855a6ed81d288ca7ca37ac6ff5e9308b612485c0801d70b25a858c83d237 mvn -B verify
```
Then add the dependency (Maven):
```xml
org.allowedbyallowedby-spring-boot-starter0.1.0
```
Or with Gradle (Kotlin DSL), after `mavenLocal()` in `repositories`:
```kotlin
dependencies {
implementation("org.allowedby:allowedby-core:0.1.0")
}
```
| Module | For | Dependencies |
|---|---|---|
| `allowedby-core` | Configuration, route map, verifier, challenges, context, in-memory store, a filter for the JDK HTTP server | none (JDK only) |
| `allowedby-servlet` | A Jakarta Servlet 6 filter (Tomcat 10.1 and 11, Jetty 12, Undertow 2.3) | `jakarta.servlet-api` (provided by your server) |
| `allowedby-spring-boot-starter` | Auto-configuration from `allowedby.*`, the filter, `@AllowedByContext` | Spring Boot 4.1 (yours) |
| `allowedby-redis` | A store shared by every instance | Jedis 7.5.3 (with commons-pool2) |
Why these choices:
- **JDK crypto only.** Ed25519 (`EdDSA`, JDK 15+), P-256 (ES256, signatures as raw r‖s), ECDH, SHA-256 and zlib come
from the JDK. No Bouncy Castle.
- **A small strict JSON parser of our own, not Jackson**, in the core. The verifier must read JSON exactly as the
reference does for RFC 8785 (JCS): `4200` stays an integer and `4200.00` a decimal. It also refuses a duplicate
member name (so the verifier and your application never read two different values from one body), `NaN`, invalid
UTF-8, lone surrogates and nesting deeper than 64. It is fuzzed in the tests. Your application keeps its own JSON
library.
- **Maven** (not Gradle): a declarative multi-module build, Spring Boot's dependency management imported as a BOM,
and a script-only wrapper. Gradle users consume the jars as shown above.
- **Jedis** for Redis: synchronous, small, no reactive runtime.
## Quick start
Twenty lines on the JDK's own HTTP server accept agents on `GET /notes`; run them next to the local node and call them
with the reference agent.
From `sdks/java/examples/quickstart/src/main/java/org/allowedby/examples/quickstart/QuickStart.java`:
```java
package org.allowedby.examples.quickstart;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.allowedby.AllowedBy;
import org.allowedby.Context;
import org.allowedby.Route;
import org.allowedby.httpserver.AllowedByHttpFilter;
public final class QuickStart {
public static void main(String[] args) throws Exception {
AllowedBy aby = AllowedBy.builder()
.origin("http://localhost:8000") // your public origin (https in production)
.node("http://localhost:8700") // the node you trust: python demo/run.py --port 8700
.org("Notes Ltd", "FR")
.route(Route.get("/notes").capability("notes:read").resource("note:*"))
.template("notes:read", "Read your notes")
.build();
String bind = System.getenv().getOrDefault("ALLOWEDBY_BIND", "").strip(); // unset or blank: loopback only
HttpServer server = HttpServer.create(new InetSocketAddress(bind.isEmpty() ? "127.0.0.1" : bind, 8000), 0);
server.createContext("/", exchange -> {
Context ctx = (Context) exchange.getAttribute(Context.ATTRIBUTE); // null outside the route map
String json = ctx == null ? "{\"error\": \"not found\"}"
: "{\"person\": \"" + ctx.getHumanId() + "\", \"notes\": []}";
byte[] out = json.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(ctx == null ? 404 : 200, out.length);
exchange.getResponseBody().write(out);
exchange.close();
}).getFilters().add(new AllowedByHttpFilter(aby));
server.start();
}
}
```
See it work against the local node (`python demo/run.py --port 8700`). Linux and macOS, from the
repository root:
```bash
pip install -r requirements.txt
(cd sdks/java && ./mvnw -B -q package -DskipTests -pl examples/quickstart -am)
python demo/run.py --reset --port 8700 &
curl -s -o /dev/null --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8700/.well-known/oaid
java -jar sdks/java/examples/quickstart/target/allowedby-quickstart.jar &
curl -is --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8000/notes # 401 passport_required
```
Windows (PowerShell):
```powershell
pip install -r requirements.txt
Push-Location sdks\java; .\mvnw.cmd -B -q package -DskipTests -pl examples/quickstart -am; Pop-Location
Start-Process python -ArgumentList "demo/run.py", "--reset", "--port", "8700"
curl.exe -s -o NUL --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8700/.well-known/oaid
Start-Process java -ArgumentList "-jar", "sdks/java/examples/quickstart/target/allowedby-quickstart.jar"
curl.exe -is --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8000/notes
```
Then an agent calls it: it gets a passport from the node, meets the `401` challenge, asks you (the link is printed),
and retries once you tap Allow:
```python
import sys
sys.path.insert(0, "sdks/python/src")
from allowedby.agent import Agent
agent = Agent("http://localhost:8700", tell=print)
print(agent.call("GET", "http://localhost:8000/notes", action="notes:read"))
```
Against the hosted node, use `node("https://demo.allowedby.com")` once your origin is in its `ALLOWEDBY_AUDIENCES`
([`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents) §15).
## Routes and templates
Each route says which capability a method and path need, how serious the action is (its class) and the identity level
the person must have; each capability has a template, the sentence the person reads and signs.
A route is immutable: every method returns a new one. `AllowedBy.Builder.build()` validates every route and fails
with a `ConfigurationException` that names the route and what to fix.
| Java | Reference name | Meaning | Default |
|---|---|---|---|
| `Route.get(path)`, `post`, `put`, `patch`, `delete`, `route(method, path)` | `method`, `path` | `{param}` matches one path segment | |
| `.capability("notes:read")` | `capability` | `namespace:action`; required above level 0, refused at level 0 | none |
| `.actionClass(ActionClass.WRITE)` | `class` | `read` (30 days), `write` (7 days), `write-hard` and `irreversible` (one approval per request, created by the service) | `read` |
| `.classByAmount(Threshold.upTo("1000.00", WRITE_HARD), Threshold.otherwise(IRREVERSIBLE))` | `class` as a list | The class comes from the amount in the request | |
| `.level(2)` | `level` | 0 passport only, 1 passkey, 2 verified identity, 3 eIDAS high | 1 |
| `.resource("note:{id}")` | `resource` | The resource the grant's `scope` must name; `{param}` from the path | `:*` |
| `.amountField("/total")`, `.currencyField("/currency")` | `amount_field`, `currency_field` | JSON Pointers into the body; the grant caps the amount | none, `/currency` |
| `.authn("hardware")` | `authn` | The weakest passkey: `software`, `synced`, `hardware` | any |
| `.tier(1)` | `tier` | The lowest custody tier of the agent's key (OAID-3) | 0 |
| `.maxLifetime(Duration.ofMinutes(15))` | `max_lifetime` | The longest approval on this route, 60 s to 30 days | the class's |
| `.levelProfile("eu")` | `level_profile` | A level-3 route for one profile of level 3 (`eu`, `na`) | none |
| `.qes(true)` | `qes` | A qualified signature; this SDK has no EU trusted list, so such a route always answers `qes_required` | false |
| `.requireLink(true)` | `require_link` | The person must have linked their account ([Account linking](#account-linking)); level 1 or more | false |
| `.accountParam("acct")` | `account_param` | The path parameter that names one of your accounts, for `requireLink`: a `{name}` of the path | `account` |
| `.nonce(true)` | `nonce` | An AllowedBy-Nonce on this route ([AllowedBy-Nonce](#allowedby-nonce)); needs `Builder.nonce(true)`, or construction fails | false |
| `.summary(...)`, `.body(Map)` | `summary`, `body` | Descriptions for agents (OpenAPI) | none |
The reference's other options (`mandate`, `disclose`, `disclose_optional`, `authority`) are
not enforced by this SDK yet. Setting one (with `Route.option(name, value)` or in Spring properties) makes
construction fail with a message naming it: an option is never accepted and then ignored.
Templates: `template("notes:read", "Read your notes")` is shorthand for one English sentence. A full template gives a
`summary` and the `lines` per language, with placeholders `{scope}`, `{amount.max}`, `{amount.currency}`,
`{amount.per}` and `{fields}`. The display uses one language for every line, and each line is at most 280 characters
(AMH-1 §4). Every capability of the route map needs a template.
From `sdks/java/examples/quickstart/src/main/java/org/allowedby/examples/quickstart/Routes.java`:
```java
package org.allowedby.examples.quickstart;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.allowedby.ActionClass;
import org.allowedby.AllowedBy;
import org.allowedby.Route;
import org.allowedby.Route.Threshold;
/** A route map that uses every route option, and the templates the person reads. */
public final class Routes {
private Routes() {
}
public static List routes() {
return List.of(
// level 0: the agent's passport is enough, no person
Route.get("/me").level(0).summary("Who is calling"),
// read, approved once (up to 30 days), on every note
Route.get("/notes").capability("notes:read").level(1).resource("note:*")
.summary("List your notes"),
// write, the body documented for agents (OpenAPI)
Route.post("/notes").capability("notes:write").actionClass(ActionClass.WRITE).level(1)
.resource("note:new").summary("Add a note").body(Map.of("text", "the note")),
// write-hard: the service asks the person for this exact request, every time; verified identity
Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD).level(2)
.resource("note:{id}").authn("synced"),
// a payment: the class comes from the amount; the approval caps the amount
Route.post("/invoices/{id}/pay").capability("invoices:pay").level(2).resource("invoice:{id}")
.amountField("/total").currencyField("/currency")
.classByAmount(Threshold.upTo("1000.00", ActionClass.WRITE_HARD),
Threshold.otherwise(ActionClass.IRREVERSIBLE))
.maxLifetime(Duration.ofMinutes(15)),
// eIDAS high, EU profile, hardware passkey, an agent key in a TPM or an enclave (tier 1)
Route.post("/contracts/{id}/sign").capability("contracts:sign").actionClass(ActionClass.IRREVERSIBLE)
.level(3).levelProfile("eu").authn("hardware").tier(1).resource("contract:{id}"));
}
public static AllowedBy service() {
return AllowedBy.builder()
.origin("https://notes.example")
.node("https://node.example.org")
.org(Map.of("legal_name", "Notes Ltd", "country", "FR", "website", "https://notes.example",
"privacy_policy", "https://notes.example/privacy"))
.routes(routes())
.template("notes:read", "Read your notes")
.template("notes:write", "Write new notes")
.template("notes:delete", "Delete note {scope}")
.template("invoices:pay", Map.of(
"summary", Map.of("en", "Pay {scope}, up to {amount.max} {amount.currency}",
"fr", "Payer {scope}, jusqu'à {amount.max} {amount.currency}"),
"lines", Map.of("en", "Pay {scope}, up to {amount.max} {amount.currency}",
"fr", "Payer {scope}, jusqu'à {amount.max} {amount.currency}")))
.template("contracts:sign", "Sign contract {scope}")
.title("Notes API")
.version("2.1.0")
.build();
}
public static void main(String[] args) {
try (AllowedBy aby = service()) {
System.out.println(aby.openApi().get("paths"));
}
}
}
```
## Framework recipes
Three thin adapters over the core: a Jakarta Servlet filter, a Spring Boot starter and a filter for the JDK HTTP
server; Kotlin uses the same API.
Every app below is complete and runs in CI: the interop test (26 scenarios against a real node, agent and person) and a
probe of path and method variants, on each server and version of `sdks/java/examples/frameworks.json`
([Testing](#testing)). They read `PORT`, `ALLOWEDBY_ORIGIN` and `ALLOWEDBY_NODE` from the environment. They listen on
127.0.0.1 only, unless `ALLOWEDBY_BIND` names another address (`0.0.0.0` in a container); unset, empty or blank means
127.0.0.1. Spring would listen on every address for an empty `server.address`, so the Spring Boot example and the
recipes do not use a `${ALLOWEDBY_BIND:127.0.0.1}` placeholder: `ListenAddress`, an `EnvironmentPostProcessor`
registered in `META-INF/spring.factories`, sets it in code.
Every adapter does the same, in this order: it serves the SDK's endpoints (`GET|HEAD /.well-known/allowedby`,
`/openapi.json`, `/.well-known/api-catalog`), then checks every request on the route map, then calls your
application. A path outside the map reaches your application unchanged, body unread. On the map, the body (at most
1 MiB) is read once and given back to your application intact; the verified `Context` goes with the request. Servers decode and
normalise the path before they dispatch it: when that path and the raw path the SDK verifies differ on a route of
the map (`/notes;x`, `//notes`, `/notes%2F1`, or `/v1/notes%3Aarchive` for a route `/v1/notes:archive`), the request is refused with `400 invalid_request`, so a protected
handler is never called for a path the SDK did not check.
Variants of a route are refused the same way (CONTRACT §2.10), with `400 invalid_request`, before they can reach a
protected handler: a trailing or doubled `/` (`/notes/`, `//notes`), a format suffix (`/notes.json`), a method
override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, a `_method` query parameter) and, in the
servlet filter, a form body (urlencoded or multipart, which can carry `_method`) on a path of the map. A
request that is itself a route of the map is never a variant: `/notes/report.pdf` on `/notes/{id}` is that route.
A handler that serves a route of the map never runs for a request the SDK did not check for that route:
- **HEAD is read as GET** in every rule: servers answer it with the GET handler.
- **A refusal never repeats the request**: its title names the rule and the option (`unprotected(path)`), never the
path, the query or a header, which may hold personal data or tokens. The debug log names the route template only.
The challenge's `scope` holds the route's resource with its values (`note:7`), built from the normalised path
(`%61b` gives `ab`), as ABY-2 §6 asks. A request whose value, decoded, is not 1 to 64 of `A-Z a-z 0-9 . _ -`, or
whose path holds an escaped control character or `/`, or whose scope would pass 256 bytes, is refused with 400 and
never gets a challenge.
- **A target that is not plain** is refused with 400 on every path: a backslash, a control character (also
percent-encoded), a dot segment, a malformed `%` or an escape that is not UTF-8, or a raw character outside printable ASCII or among
``| ^ " < > ` { }`` (browsers send `|` and `^` as they are: link to such pages percent-encoded, `%7C`, `%5E`). Servers
and routers read these differently.
This is stricter than rule 1 of the contract on purpose: your own paths that are not plain get 400 too, because no
list of the ways a router may read them is complete, and a missed one would reach a protected handler.
- **Spring Boot** sees the handler Spring selected. It refuses with 400 a controller method or functional route that
serves a route of the map when the request was not checked for it: `/notes/{*id}` on `/notes/7/x`, an optional
parameter, a mapping for any method, a forward, a filter that changes the path later. Your own handlers run, and so
does a `/**` catch-all where every route has a handler of its own. `@AllowedByContext(required = false)` only lets the context be null outside the map: it lifts no refusal. The
default `path-pattern-parser` strategy is required: with the ant path matcher the start fails, and so does a
`DispatcherServlet` without Spring MVC's configuration (`WebMvcAutoConfiguration` excluded, no `@EnableWebMvc`). A
functional route counts for the routes of every method its pattern covers, as its methods are not known: another
method of yours on the same path needs a pattern of its own or a controller. A CORS preflight is Spring's own answer
and goes through. Another servlet in the
same application (Jersey, a `ServletRegistrationBean`) gets the rules of the servlet filter below, and so does the
`DispatcherServlet` itself when a handler mapping of your own (a `SimpleUrlHandlerMapping` bean) does not carry the
check: a warning at start names it. A filter after ours
that changes the method is refused too.
- **The handler of any route of the map**, in Spring, runs only for a request checked for that route, whatever its
method (one handler for `GET` and `DELETE` of `/notes/{id}` is the `DELETE` route's):
`@DeleteMapping("/notes/{id}/**")` next to the route `DELETE /notes/{id}/archive` is refused on `/notes/7/archive/x`.
A catch-all, site-wide (`/**`, a front controller, a fallback page) or under a prefix (`/notes/{id}/**`), is protected
for a route only while that route has no handler of its own known: then every unchecked request it gets is refused,
requests near the route, of any method, are refused, and a warning at start names the route. A checked request that
would run it gets 400, unless it is the only handler found for the route and the route covers every other route it is
protected for; it then runs, and is never learnt. Once the route's own handler is known (a mapping or a function of
its shape, or a handler learnt), a site-wide fallback is not that route's, so your fallback pages answer, and one
request with a bad value never locks them out. A catch-all under the route's prefix (`/notes/{id}/**` next to
`/notes/{id:[0-9]+}/archive`) serves that route's paths for other values, so it stays protected. A handler that
dispatches protected actions itself (one handler for every path that deletes or pays, or a legacy controller on a path
no route maps) is not something the SDK can see. A front controller shared by protected routes of different
capabilities or resources runs for none of them. Give each protected route its own handler. A front controller shared
by routes of one capability runs only for a request checked for a route at least as strict as the others it serves. A
handler no route is known to own (registered while the application runs) is learnt from the first checked request that
runs it when the pattern Spring matched has the route's own shape, or when it serves the route's template and that
route is at least as strict as every other route, of any method, whose handler is not known; otherwise it is refused.
A page that takes one value of a route (`/notes/export` beside `/notes/{id}`) is never learnt as that route's handler.
One controller method for several routes, whatever their shapes and methods (`@DeleteMapping({"/notes/{id}",
"/items/{id}"})`, or `GET` and `POST` of `/items/{id}`), runs only for a request checked for a route that covers all
the others, and a warning, at start or on the first request, names each pair that does not cover each other (router
functions too). Functions follow the same rules: a `route(path("/**"), dispatcher)` that alone serves a route is
protected, and beside routes that all have a function or a controller method of their own it is a fallback; a function
runs for a request checked for a route only if that route covers every other route it serves, of the methods it takes
(a `/**` or `/notes/**` function shared by a weak and a strict route runs only for the strict one). A router function
counts as a route's own handler only when it has the route's shape and method. One function instance registered for
several routes is one code; two method references to one method (`h::delete` written twice) are two instances, which
the JVM does not tie to their method, so each route runs it on its own check. A warning at start names routes whose
functions capture the same object; give each protected route its own method. No `unprotected` entry lifts any of this
(CONTRACT §2.10 rule 5).
- **The servlet filter and the JDK filter** do not see your routing. They refuse with 400 a path that a
route matches if a parameter takes several segments, for a method of that route (`DELETE /notes/7/x` with
`DELETE /notes/{id}`, `/n/1/x/c` with `/n/{id}/c`), and any other path of a servlet or JDK context registered for the
prefix of a route (`/notes/*`, `createContext("/notes")`) with the same method. The servlet filter also refuses a form
on such a longer path, whatever its method, and a path whose part below a servlet's prefix is a route that no servlet
with a mapping of its own serves (`/console/me` with the route `/me`): declare such a page with `unprotected`.
`GET /notes/7` with only `GET /notes` on the map goes through a servlet on `/*`.
- **Limit of the servlet and JDK filters.** A route that ends in a literal (`DELETE /notes/{id}/archive`) is protected
on a longer path only where a servlet or JDK context is registered for exactly its prefix (`/notes/*`,
`createContext("/notes")`). When a servlet or JDK context registered for a shorter prefix (`/*`, `/`, `/api/*` for
the route `/api/notes/{id}/archive`) does its own routing (Jersey, a front controller) and gives
`/notes/7/archive/x` to the handler of that route, the filter cannot see it: match the route's own path in that
handler, or use the Spring Boot starter, which sees the handler.
- **Changed after the check** (plan point 14). An accepted request records what it was checked as: its method (HEAD as
GET) and its path, normalised as the check normalises it, in the request attribute `AllowedByFilter.TARGET`. Another
spelling of the same path is the same request. In Spring, the starter compares it again when Spring has chosen the
handler: a filter after ours that rewrites the path (UrlRewriteFilter, Tuckey) or overrides the method
(`HiddenHttpMethodFilter`), a `HttpServletRequestWrapper` that changes `getRequestURI()` or `getMethod()`, and a
forward or an async dispatch (`AsyncContext.dispatch`) that moves it onto the map, to another route or a longer path
of one, get 400 `invalid_request`, never repeating the path, before the handler runs. A dispatch off the map (a view,
a static page) still runs, as an unchecked request would. An include of another route gets the refusal as its body (an
included response cannot set its status). An error page (`ERROR`) of an accepted request still answers; nothing else
passes unchecked. The plain servlet filter checks forwards, includes and async dispatches when it is registered for
them (`EnumSet.allOf(DispatcherType.class)`), and refuses an include of a route of the map from a request that was not
checked; it cannot see where a wrapper or a rewrite after it leads, and neither can the JDK filter, which a later
filter can hand another exchange: put nothing that changes the method or the path after them, and act on
`ctx.getParams()`, the values that were checked.
- **Refunds** (CONTRACT §2 item 10, ABY-2 §5 step 9). The check spends as before: the single-use mark and the grant's
`count` and `amount` totals, atomically. When the Spring Boot starter's interceptor, which runs right before the
handler, refuses that accepted request on its first dispatch (its handler guard of rule 5, or a method or path changed
after acceptance), it gives back exactly what the request spent, once, from the check's receipt: the approval is
usable again for a request its route serves. Only that guard refunds, and only a request the starter's filter held for
it; there is no public refund. An accepted request is held, started or refunded, never both started and refunded
(switched atomically); a refunded one never reaches a handler, even when a layer dispatches it again (400). Nothing is
given back once anything of yours could have acted: after the handler started, for a refusal of your own (a handler,
or a filter after the SDK that answers), for any refusal of a forward, include or async dispatch, by the servlet
filter or the interceptor (code of yours after the SDK, a filter or a framework mounted as one, dispatched it), and
never with the plain servlet filter, the JDK filter or the plain integration, which never hold a request for a guard.
A refund the store does not take (the store down) leaves the approval spent, logged without request data. A `Store`
applies a refund as a charge with negative increments and no maximum, exactly.
- **Your own pages that look like these** are declared: `.unprotected("/notes.txt")`,
`.unprotected("DELETE", "/notes/{id}/comments")`, or `allowedby.unprotected` in Spring. A template needs a literal
segment, and names its method when it is a longer path of a route (`/notes/{id}/comments` next to
`DELETE /notes/{id}`). An entry that overlaps a route of the map, as it is or but for its last `/`, fails at
construction, and so does one a router may read as another path (an encoded character, `;`, a doubled `/`). In
Spring an entry never lifts the refusal of a protected handler. An exact entry without a method lifts every method:
`.unprotected("/notes/7/x")` next to `DELETE /notes/{id}` lets a `DELETE` of that path through too, so name the
method (`.unprotected("GET", "/notes/7/x")`) unless every method of it is yours.
**Context path.** Write the map without it: an application at `/api` with the route `/notes` serves
`https://api.example.com/api/notes`, and `origin` is `https://api.example.com`. The filter takes the prefix from the
server (`server.servlet.context-path`, a WAR's name) and verifies the URL the agent called. A map that names the prefix
(`/api/notes` in an application at `/api`) would protect nothing: such requests are refused with 400 and a message. A
proxy that strips a prefix must be declared to the server, so that it reports the context path. A servlet path is not a
context path: with `spring.mvc.servlet.path=/v1`, write `/v1/notes`. A JDK
context is not one either: with `createContext("/api")`, write `/api/notes`. A request whose path below the context is a
route of the map is refused with 400, unless that path is declared with `unprotected`.
### Jakarta Servlet
Register `AllowedByFilter` on `/*`. The context is the request attribute `Context.ATTRIBUTE`. The service and the
servlet are the same on every server; the three programs after them start Tomcat (10.1 and 11), Jetty 12 and Undertow 2.3.
From `sdks/java/examples/frameworks/servlet-notes/src/main/java/org/allowedby/examples/servlet/NotesService.java`:
```java
package org.allowedby.examples.servlet;
import java.util.Map;
import org.allowedby.ActionClass;
import org.allowedby.AllowedBy;
import org.allowedby.Route;
/** The notes service: its route map and the sentences a person approves. */
public final class NotesService {
private NotesService() {
}
/** Built from ALLOWEDBY_ORIGIN, ALLOWEDBY_NODE and ALLOWEDBY_REFRESH_SECONDS. */
public static AllowedBy fromEnvironment() {
return AllowedBy.builder()
.origin(System.getenv("ALLOWEDBY_ORIGIN"))
.node(System.getenv("ALLOWEDBY_NODE"))
.refreshSeconds(Integer.parseInt(System.getenv().getOrDefault("ALLOWEDBY_REFRESH_SECONDS", "5")))
.org("Notes Interop Ltd", "FR")
.title("Notes Interop API")
.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").actionClass(ActionClass.WRITE).level(1)
.resource("note:new").summary("Add a note").body(Map.of("text", "the note")))
.route(Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD)
.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}")
.build();
}
}
```
From `sdks/java/examples/frameworks/servlet-notes/src/main/java/org/allowedby/examples/servlet/NotesServlet.java`:
```java
package org.allowedby.examples.servlet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.allowedby.Context;
/** The application behind the AllowedBy filter: each person's own notes. */
public final class NotesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final ObjectMapper JSON = new ObjectMapper();
private final transient Map>> notes = new ConcurrentHashMap<>();
private final AtomicInteger ids = new AtomicInteger();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
Context ctx = (Context) req.getAttribute(Context.ATTRIBUTE); // null outside the route map
switch (req.getRequestURI()) {
case "/health" -> send(res, 200, Map.of("ok", true));
case "/me" -> send(res, 200, Map.of("agent", ctx.getAgent(), "operator", ctx.getOperator(),
"level", ctx.getLevel()));
case "/notes" -> {
String person = ctx.getHumanId();
if (person == null) { // level 0: no person, and never a key
send(res, 403, Map.of("error", "no person at level 0"));
return;
}
send(res, 200, Map.of("notes", mine(person)));
}
default -> notFound(res);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
if (!req.getRequestURI().equals("/notes")) {
notFound(res);
return;
}
Context ctx = (Context) req.getAttribute(Context.ATTRIBUTE);
String person = ctx.getHumanId();
if (person == null) { // level 0: no person, and never a key
send(res, 403, Map.of("error", "no person at level 0"));
return;
}
JsonNode text;
try {
text = JSON.readTree(req.getInputStream()).path("text");
} catch (JsonProcessingException e) { // not JSON: the same answer as a missing text
text = MissingNode.getInstance();
}
String t = text.asText(); // its length in characters, as the reference counts it
if (!text.isTextual() || t.isEmpty() || t.codePointCount(0, t.length()) > 2000) {
send(res, 400, Map.of("error", "text: a string of 1 to 2000 characters"));
return;
}
String id = Integer.toString(ids.incrementAndGet());
mine(person).add(Map.of("id", id, "text", text.asText()));
send(res, 201, Map.of("id", id));
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException {
if (!req.getRequestURI().matches("/notes/[^/]+")) { // exactly the protected route
notFound(res);
return;
}
Context ctx = (Context) req.getAttribute(Context.ATTRIBUTE);
String person = ctx.getHumanId();
if (person == null) { // level 0: no person, and never a key
send(res, 403, Map.of("error", "no person at level 0"));
return;
}
String id = ctx.getParams().get("id");
mine(person).removeIf(note -> note.get("id").equals(id));
send(res, 200, Map.of("deleted", id));
}
private List