Refuse in your own handler#
Your rules still apply: the agent receives your status and your JSON, and can correct itself.
| Level | 1: A person approves with a passkey. |
| Class | write: Something changes and can be undone. The approval can be reused. |
routes.append(route("PUT", "/notes/{id}", "notes:write", cls="write", level=1, resource="note:{id}",
summary="Change a note", body={"text": "1 to 280 characters"}))
@app.put("/notes/<note_id>")
def change_note(note_id):
text = str(request.json.get("text", ""))
if not 1 <= len(text) <= 280:
return {"error": "text: 1 to 280 characters"}, 422 # the agent gets this status and this JSON
note = notes.update(g.allowedby.human_id, note_id, text)
return note or ({"error": "no such note"}, 404)routes.push(route("PUT", "/notes/{id}", "notes:write", {
class: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: { text: "1 to 280 characters" },
}));
api.put("/notes/:id", (req, res) => {
const person = req.allowedby.humanId;
if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by
const text = String(req.body?.text ?? "");
const length = [...text].length; // characters, not UTF-16 units: an emoji counts as one
if (length < 1 || length > 280) {
return res.status(422).json({ error: "text: 1 to 280 characters" }); // the agent gets this status and this JSON
}
const note = notes.update(person, req.params.id, text);
if (!note) return res.status(404).json({ error: "no such note" });
res.json(note);
});routes = append(routes, allowedby.Route{Method: "PUT", Path: "/notes/{id}", Capability: "notes:write",
Class: allowedby.Write, Level: 1, Resource: "note:{id}", Summary: "Change a note",
Body: map[string]string{"text": "1 to 280 characters"}})
mux.HandleFunc("PUT /notes/{id}", func(w http.ResponseWriter, r *http.Request) {
who, _ := allowedby.ContextFrom(r.Context())
me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for
if !ok {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"})
return
}
var input struct{ Text string }
err := json.NewDecoder(r.Body).Decode(&input)
if n := utf8.RuneCountInString(input.Text); err != nil || n < 1 || n > 280 {
// the agent gets this status and this JSON
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "text: 1 to 280 characters"})
return
}
note, found := notes.Update(me, r.PathValue("id"), input.Text)
if !found {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"})
return
}
writeJSON(w, http.StatusOK, note)
})@Bean
AllowedByCustomizer refuse() {
return aby -> aby.route(Route.put("/notes/{id}").capability("notes:write").actionClass(ActionClass.WRITE)
.level(1).resource("note:{id}").summary("Change a note").body(Map.of("text", "1 to 280 characters")));
}
@PutMapping("/notes/{id}")
ResponseEntity<Object> changeNote(@AllowedByContext Context ctx, @PathVariable String id,
@RequestBody NoteInput input) {
String person = ctx.getHumanId();
if (person == null) { // level 0: no person, and never a key
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0");
}
String text = input.text() == null ? "" : input.text();
int length = text.codePointCount(0, text.length()); // characters: an emoji counts as one
if (length < 1 || length > 280) {
// the agent gets this status and this JSON
return ResponseEntity.status(422).body(Map.of("error", "text: 1 to 280 characters"));
}
return notes.update(person, id, text).<ResponseEntity<Object>>map(ResponseEntity::ok)
.orElse(ResponseEntity.status(404).body(Map.of("error", "no such note")));
}routes.Add(Route("PUT", "/notes/{id}", "notes:write", cls: "write", level: 1, resource: "note:{id}",
summary: "Change a note", body: new Dictionary<string, string> { ["text"] = "1 to 280 characters" }));
app.MapPut("/notes/{id}", (string id, NoteInput input, AllowedByContext ctx) =>
{
var text = input.Text ?? "";
if (text.EnumerateRunes().Count() is < 1 or > 280) // characters: an emoji counts as one
{
return Results.Json(new { error = "text: 1 to 280 characters" }, statusCode: 422); // the agent gets this
}
return notes.Update(Person(ctx), id, text) is { } note
? Results.Json(note)
: Results.Json(new { error = "no such note" }, statusCode: 404);
});$routes[] = route('PUT', '/notes/{id}', 'notes:write', class: 'write', level: 1, resource: 'note:{id}',
summary: 'Change a note', body: ['text' => '1 to 280 characters']);
$app->put('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) {
$person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0');
$text = (string) (json_decode((string) $request->getBody(), true)['text'] ?? '');
if (1 !== preg_match('/\A.{1,280}\z/su', $text)) {
return $json($response, ['error' => 'text: 1 to 280 characters'], 422); // the agent gets this status and this JSON
}
$note = $notes->update($person, $args['id'], $text);
return null === $note ? $json($response, ['error' => 'no such note'], 404) : $json($response, $note);
});ROUTES << AllowedBy.route(
"PUT", "/notes/{id}", "notes:write",
class: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: { text: "1 to 280 characters" }
)
put "/notes/:id" do
text = JSON.parse(request.body.read)["text"].to_s
# the agent gets this status and this JSON
halt 422, { error: "text: 1 to 280 characters" }.to_json unless text.length.between?(1, 280)
person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json
note = notes.update(person, params["id"], text)
halt 404, { error: "no such note" }.to_json unless note
note.to_json
endlet 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<Notes>,
Path(id): Path<String>,
Json(input): Json<NoteInput>,
) -> Result<Json<Note>, 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"}))))
}Run in 8 languages on this version. See the results
What the test proves#
- the app's own refusal reaches the agent as it is: 422 and its JSON; nothing changed
- a body that is not a JSON object never reaches the app (400); no body at all is a 4xx
- a note that is not there: the app's 404
- corrected, the same request is accepted under the same approval: 200
- 280 emoji are 280 characters in every language: 200; 281: 422