View as Markdown

AllowedBy Go SDK#

The Go SDK lets AI agents call your Go service with a person's approval. The person approves with a passkey tap on their node's approval page; your service checks every agent request offline (no network call on the request path) and answers with a challenge when an approval is missing. Concepts (routes, classes, levels, the approval flow) are explained once in docs/deploy-saas.md; this guide shows them in Go.

Terms used here: a node issues agent passports and runs the approval page; a grant is a person's signed approval; a proof (JWS, JSON Web Signature) signs each request; JCS is RFC 8785 canonical JSON.

Install#

go get github.com/yannUpTo/allowedby/sdks/go adds the SDK; it needs Go 1.22 or later and nothing but the standard library.

The SDK is not published yet (publishing is a separate step). Until then, point Go at a clone of the repository.

Linux and macOS:

git clone https://github.com/yannUpTo/allowedby.git
cd your-app
go mod edit -replace github.com/yannUpTo/allowedby/sdks/go=../allowedby/sdks/go
go get github.com/yannUpTo/allowedby/sdks/go

Windows (PowerShell):

git clone https://github.com/yannUpTo/allowedby.git
cd your-app
go mod edit -replace github.com/yannUpTo/allowedby/sdks/go=../allowedby/sdks/go
go get github.com/yannUpTo/allowedby/sdks/go

Framework adapters and the Redis store are separate modules, so the core stays dependency-free. Add only the one you use, with the same -replace for its directory:

Module For Dependency (pinned, why)
github.com/yannUpTo/allowedby/sdks/go net/http none: crypto/ed25519, crypto/ecdsa, crypto/ecdh, compress/zlib cover every algorithm
.../sdks/go/allowedbygin Gin github.com/gin-gonic/gin v1.12.0: the framework itself
.../sdks/go/allowedbyecho Echo github.com/labstack/echo/v4 v4.16.3: the framework itself
.../sdks/go/allowedbychi chi github.com/go-chi/chi/v5 v5.5.0: the framework itself
.../sdks/go/allowedbyredis several instances github.com/redis/go-redis/v9 v9.23.0: the shared replay set and counters

With Docker, nothing is installed on the machine:

docker run --rm -v "$PWD":/src -w /src/sdks/go golang:1.27.2@sha256:820153096fda4de6ac1b7194d12e416b7dd8f4e9a33d17e0345b111b945162d8 go test ./...
docker run --rm -v "${PWD}:/src" -w /src/sdks/go golang:1.27.2@sha256:820153096fda4de6ac1b7194d12e416b7dd8f4e9a33d17e0345b111b945162d8 go test ./...

Quick start#

allowedby.New with your origin, your node, your organisation, a route map and a sentence per capability, then aby.Handler(mux): that is a service that accepts agents.

package main

import (
	"fmt"
	"log"
	"net/http"

	allowedby "github.com/yannUpTo/allowedby/sdks/go"
)

func main() {
	aby, err := allowedby.New(allowedby.Options{
		Origin: "http://localhost:8081", // your public origin, as agents call it
		Node:   "http://localhost:8080", // the AllowedBy node you trust (here: python demo/run.py)
		Org:    allowedby.Org{LegalName: "Notes Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1},
		},
		Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")},
	})
	if err != nil {
		log.Fatal(err)
	}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context()) // the person's pairwise id, level, agent...
		person, ok := who.Human()                    // false at level 0: an agent, no person
		if !ok {
			http.Error(w, "no person", http.StatusForbidden)
			return
		}
		fmt.Fprintf(w, `{"notes": [], "for": %q}`, person)
	})
	log.Fatal(http.ListenAndServe("127.0.0.1:8081", aby.Handler(mux)))
}

From sdks/go/examples/quickstart/main.go. See it work against the local demo node:

pip install -r requirements.txt ./sdks/python     # once
python demo/run.py --reset --port 8080            # terminal 1: the node on http://localhost:8080
cd sdks/go && go run ./examples/quickstart         # terminal 2: the service on http://localhost:8081
python -c "from allowedby.agent import Agent; print(Agent('http://localhost:8080', tell=print).call('GET', 'http://localhost:8081/notes', action='notes:read'))"
pip install -r requirements.txt ./sdks/python     # once
python demo/run.py --reset --port 8080            # terminal 1: the node on http://localhost:8080
cd sdks/go; go run ./examples/quickstart         # terminal 2: the service on http://localhost:8081
python -c "from allowedby.agent import Agent; print(Agent('http://localhost:8080', tell=print).call('GET', 'http://localhost:8081/notes', action='notes:read'))"

The agent prints the approval link and its code (terminal 3); open the link, approve with the demo passkey, and the call returns 200.

Without a passport the service answers 401 passport_required; with a passport and no approval, 401 grant_required and a challenge; the agent asks the node, the person taps the passkey, the agent retries and gets 200. Against a hosted node, set Node to its origin and Origin to your public https origin.

Routes and templates#

Each allowedby.Route says what an agent needs before it may call one method and path; the person signs the sentence of the capability's Template.

A Route is a struct literal, not a function with options: it reads like the route map table of ABY-3 §4.1, every field is named at the call site, and New validates the whole map at once (what route() checks in Python). Zero values are never silently weaker than meant: a route with a Capability must set Class and Level 1 to 3, or New fails.

Field Meaning Default
Method, Path GET, POST, PUT, PATCH, DELETE; /notes/{id} (a {param} is one segment, whatever the router's syntax: New refuses :id, * and {path...}). HEAD uses the GET route. required
Capability What the person allows, namespace:action. Empty: an identity route, the passport is enough (level 0). none
Class allowedby.Read, Write, WriteHard, Irreversible. For WriteHard and Irreversible the SDK creates the approval itself, bound to the exact request, used once. required with a capability
Classes A class by amount: []allowedby.Threshold{{UpTo: "1000.00", Class: allowedby.WriteHard}, {Class: allowedby.Irreversible}}, read at AmountField. none
Level 1 passkey, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey. required with a capability
Resource What the route acts on, with path parameters: note:{id}. The grant's scope must cover it; New refuses a character a scope cannot hold (a space, a quote, non-ASCII). <namespace>:*
AmountField, CurrencyField JSON Pointers to the amount (a decimal string) and currency in the body; the grant must cap the amount. none, /currency
Authn "synced" or "hardware": the passkey class required. any
Tier The agent key custody tier required (OAID-6). 0
MaxLifetime How long an approval for this route may last, 60 s to 30 days. the class's
LevelProfile "eu" or "na" on level-3 routes (OAID-7 §5.3, see Reference): a grant whose registration has another profile, or none, is refused with 401 level_insufficient. none: any level 3
Nonce An AllowedBy-Nonce on this route (ABY-2 §3.2, see Reference). Needs Options.Nonce, or New fails. off
Summary, Body What the route does and each JSON body member, for /openapi.json. none
RequireLink The person must be linked to one of your accounts (account linking, see Reference): 403 human_not_linked otherwise; when the path has the AccountParam parameter, linked to that account. Routes with a capability only: New refuses it on a level-0 route. off
AccountParam The path parameter that names one of your accounts. With RequireLink, the person must be linked to it; approvals the service asks for on a linked account name its person (human_hint, AMH-1 §7). account
Mandate, Disclose, DiscloseOptional, Authority, QES Options of the Python SDK the Go SDK does not enforce yet: New refuses them, naming the option. off

Templates: allowedby.Text("Read your notes") is English only. For several languages, give the full form, allowedby.Template{Summary: map[string]string{"en": "...", "fr": "..."}, Lines: map[string]string{...}}. Placeholders: {scope}, {fields}, {amount.max}, {amount.currency}, {amount.per}, {count.max}; nothing else from the agent reaches the sentence. New refuses a route map whose capabilities have no template.

Framework recipes#

aby.Handler is net/http middleware; Gin, Echo and chi have adapters (allowedbygin.Middleware, allowedbyecho.Middleware, allowedbychi.Middleware).

In every framework: register the middleware for all routes (so it also serves /.well-known/allowedby, /openapi.json and /.well-known/api-catalog), write paths in the route map with {param} whatever the router's own syntax, and read the context in handlers. The middleware reads the body once and gives it back intact.

Each app below is complete: the notes API of the interop test, at levels 0, 1 and 2. CI runs all of them against a real node, agent and person (26 of 26 scenarios), on the oldest Go version claimed for the framework and on the current one (sdks/go/examples/frameworks.json, python sdks/go/examples/run_frameworks.py).

net/http (Go 1.22 patterns):

// Command nethttp is the notes app of sdks/interop/reference_app.py on net/http. CI runs it against a real node, agent
// and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py nethttp`.
//
//	GET    /me           the agent's passport is enough (level 0)
//	GET    /health       outside the route map: the app's own
//	GET    /notes        read, level 1: the person's own notes
//	POST   /notes        write, level 1: body {"text": string}
//	DELETE /notes/{id}   write-hard, level 2: one approval for exactly this request
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"slices"
	"strconv"
	"sync"
	"time"
	"unicode/utf8"

	allowedby "github.com/yannUpTo/allowedby/sdks/go"
)

func main() {
	aby, err := service()
	if err != nil {
		log.Fatal(err)
	}
	notes := &store{by: map[string][]note{}}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) {
		reply(w, http.StatusOK, map[string]bool{"ok": true})
	})
	// the routes of the map: registered with the SDK, which then knows each one's handler (rule 5)
	aby.HandleFunc(mux, "GET /me", func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		reply(w, http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level})
	})
	aby.HandleFunc(mux, "GET /notes", func(w http.ResponseWriter, r *http.Request) {
		me, ok := person(w, r)
		if !ok {
			return
		}
		reply(w, http.StatusOK, map[string]any{"notes": notes.list(me)})
	})
	aby.HandleFunc(mux, "POST /notes", func(w http.ResponseWriter, r *http.Request) {
		me, ok := person(w, r)
		if !ok {
			return
		}
		var in struct {
			Text string `json:"text"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil || !validText(in.Text) {
			reply(w, http.StatusBadRequest, map[string]string{"error": badText})
			return
		}
		reply(w, http.StatusCreated, map[string]string{"id": notes.add(me, in.Text)})
	})
	aby.HandleFunc(mux, "DELETE /notes/{id}", func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		me, ok := person(w, r)
		if !ok {
			return
		}
		id := who.Params["id"] // the id as the SDK checked it, never the app's own reading of the raw path
		notes.remove(me, id)
		reply(w, http.StatusOK, map[string]string{"deleted": id})
	})
	mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
		reply(w, http.StatusNotFound, map[string]string{"error": "not found"})
	})
	srv := &http.Server{Addr: "127.0.0.1:" + getenv("PORT", "8081"), Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

// service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability.
func service() (*allowedby.Service, error) {
	refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s")
	if err != nil {
		return nil, err
	}
	return allowedby.New(allowedby.Options{
		Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"),
		Node:   getenv("ALLOWEDBY_NODE", "http://localhost:8080"),
		Org:    allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/me", Summary: "Who is calling"},
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1,
				Resource: "note:*", Summary: "List your notes"},
			{Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1,
				Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}},
			{Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2,
				Resource: "note:{id}", Summary: "Delete a note"},
		},
		Templates: map[string]allowedby.Template{
			"notes:read":   allowedby.Text("Read your notes"),
			"notes:write":  allowedby.Text("Write new notes"),
			"notes:delete": allowedby.Text("Delete note {scope}"),
		},
		Title:           "Notes Interop API",
		RefreshInterval: refresh,
	})
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

type note struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

// store keeps each person's notes, by the pairwise id AllowedBy gives this service for them.
type store struct {
	mu   sync.Mutex
	last int
	by   map[string][]note
}

func (s *store) list(person string) []note {
	s.mu.Lock()
	defer s.mu.Unlock()
	return append([]note{}, s.by[person]...)
}

func (s *store) add(person, text string) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.last++
	id := strconv.Itoa(s.last)
	s.by[person] = append(s.by[person], note{ID: id, Text: text})
	return id
}

func (s *store) remove(person, id string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id })
}

const badText = "text: a string of 1 to 2000 characters"

// noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for.
const noPerson = "this route has no person: map it at level 1 or more"

// person is the id of the person the notes belong to, or a 403: never notes kept under an empty id.
func person(w http.ResponseWriter, r *http.Request) (string, bool) {
	who, _ := allowedby.ContextFrom(r.Context())
	id, ok := who.Human()
	if !ok {
		reply(w, http.StatusForbidden, map[string]string{"error": noPerson})
	}
	return id, ok
}

func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 }

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

From sdks/go/examples/frameworks/nethttp/main.go.

Gin:

// Command gin is the notes app of sdks/interop/reference_app.py on Gin. CI runs it against a real node, agent
// and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py gin`.
//
//	GET    /me           the agent's passport is enough (level 0)
//	GET    /health       outside the route map: the app's own
//	GET    /notes        read, level 1: the person's own notes
//	POST   /notes        write, level 1: body {"text": string}
//	DELETE /notes/{id}   write-hard, level 2: one approval for exactly this request
package main

import (
	"log"
	"net/http"
	"os"
	"slices"
	"strconv"
	"sync"
	"time"
	"unicode/utf8"

	"github.com/gin-gonic/gin"
	allowedby "github.com/yannUpTo/allowedby/sdks/go"
	"github.com/yannUpTo/allowedby/sdks/go/allowedbygin"
)

func main() {
	aby, err := service()
	if err != nil {
		log.Fatal(err)
	}
	notes := &store{by: map[string][]note{}}
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery(), allowedbygin.Middleware(aby, r)) // with Use, it also serves /.well-known/allowedby
	r.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) })
	r.GET("/me", func(c *gin.Context) {
		who, _ := allowedbygin.Context(c)
		c.JSON(http.StatusOK, gin.H{"agent": who.Agent, "operator": who.Operator, "level": who.Level})
	})
	r.GET("/notes", func(c *gin.Context) {
		me, ok := person(c)
		if !ok {
			return
		}
		c.JSON(http.StatusOK, gin.H{"notes": notes.list(me)})
	})
	r.POST("/notes", func(c *gin.Context) {
		me, ok := person(c)
		if !ok {
			return
		}
		var in struct {
			Text string `json:"text"`
		}
		if err := c.ShouldBindJSON(&in); err != nil || !validText(in.Text) {
			c.JSON(http.StatusBadRequest, gin.H{"error": badText})
			return
		}
		c.JSON(http.StatusCreated, gin.H{"id": notes.add(me, in.Text)})
	})
	r.DELETE("/notes/:id", func(c *gin.Context) { // the route map writes it /notes/{id}
		me, ok := person(c)
		if !ok {
			return
		}
		notes.remove(me, c.Param("id"))
		c.JSON(http.StatusOK, gin.H{"deleted": c.Param("id")})
	})
	r.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"error": "not found"}) })
	srv := &http.Server{Addr: "127.0.0.1:" + getenv("PORT", "8081"), Handler: r, ReadHeaderTimeout: 10 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

// service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability.
func service() (*allowedby.Service, error) {
	refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s")
	if err != nil {
		return nil, err
	}
	return allowedby.New(allowedby.Options{
		Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"),
		Node:   getenv("ALLOWEDBY_NODE", "http://localhost:8080"),
		Org:    allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/me", Summary: "Who is calling"},
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1,
				Resource: "note:*", Summary: "List your notes"},
			{Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1,
				Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}},
			{Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2,
				Resource: "note:{id}", Summary: "Delete a note"},
		},
		Templates: map[string]allowedby.Template{
			"notes:read":   allowedby.Text("Read your notes"),
			"notes:write":  allowedby.Text("Write new notes"),
			"notes:delete": allowedby.Text("Delete note {scope}"),
		},
		Title:           "Notes Interop API",
		RefreshInterval: refresh,
	})
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

type note struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

// store keeps each person's notes, by the pairwise id AllowedBy gives this service for them.
type store struct {
	mu   sync.Mutex
	last int
	by   map[string][]note
}

func (s *store) list(person string) []note {
	s.mu.Lock()
	defer s.mu.Unlock()
	return append([]note{}, s.by[person]...)
}

func (s *store) add(person, text string) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.last++
	id := strconv.Itoa(s.last)
	s.by[person] = append(s.by[person], note{ID: id, Text: text})
	return id
}

func (s *store) remove(person, id string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id })
}

const badText = "text: a string of 1 to 2000 characters"

// noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for.
const noPerson = "this route has no person: map it at level 1 or more"

// person is the id of the person the notes belong to, or a 403: never notes kept under an empty id.
func person(c *gin.Context) (string, bool) {
	who, _ := allowedbygin.Context(c)
	id, ok := who.Human()
	if !ok {
		c.JSON(http.StatusForbidden, gin.H{"error": noPerson})
	}
	return id, ok
}

func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 }

From sdks/go/examples/frameworks/gin/main.go; tested in sdks/go/allowedbygin/allowedbygin_test.go.

Echo:

// Command echo is the notes app of sdks/interop/reference_app.py on Echo. CI runs it against a real node, agent
// and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py echo`.
//
//	GET    /me           the agent's passport is enough (level 0)
//	GET    /health       outside the route map: the app's own
//	GET    /notes        read, level 1: the person's own notes
//	POST   /notes        write, level 1: body {"text": string}
//	DELETE /notes/{id}   write-hard, level 2: one approval for exactly this request
package main

import (
	"log"
	"net/http"
	"os"
	"slices"
	"strconv"
	"sync"
	"time"
	"unicode/utf8"

	"github.com/labstack/echo/v4"
	allowedby "github.com/yannUpTo/allowedby/sdks/go"
	"github.com/yannUpTo/allowedby/sdks/go/allowedbyecho"
)

func main() {
	aby, err := service()
	if err != nil {
		log.Fatal(err)
	}
	notes := &store{by: map[string][]note{}}
	e := echo.New()
	e.HideBanner = true
	e.Use(allowedbyecho.Middleware(aby)) // Use also runs for /.well-known/allowedby
	e.GET("/health", func(c echo.Context) error { return c.JSON(http.StatusOK, map[string]bool{"ok": true}) })
	e.GET("/me", func(c echo.Context) error {
		who, _ := allowedbyecho.Context(c)
		return c.JSON(http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level})
	})
	e.GET("/notes", func(c echo.Context) error {
		me, err := person(c)
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]any{"notes": notes.list(me)})
	})
	e.POST("/notes", func(c echo.Context) error {
		me, err := person(c)
		if err != nil {
			return err
		}
		var in struct {
			Text string `json:"text"`
		}
		if err := c.Bind(&in); err != nil || !validText(in.Text) {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": badText})
		}
		return c.JSON(http.StatusCreated, map[string]string{"id": notes.add(me, in.Text)})
	})
	e.DELETE("/notes/:id", func(c echo.Context) error { // the route map writes it /notes/{id}
		me, err := person(c)
		if err != nil {
			return err
		}
		notes.remove(me, c.Param("id"))
		return c.JSON(http.StatusOK, map[string]string{"deleted": c.Param("id")})
	})
	e.RouteNotFound("/*", func(c echo.Context) error {
		return c.JSON(http.StatusNotFound, map[string]string{"error": "not found"})
	})
	e.Server.ReadHeaderTimeout = 10 * time.Second
	log.Fatal(e.Start("127.0.0.1:" + getenv("PORT", "8081")))
}

// service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability.
func service() (*allowedby.Service, error) {
	refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s")
	if err != nil {
		return nil, err
	}
	return allowedby.New(allowedby.Options{
		Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"),
		Node:   getenv("ALLOWEDBY_NODE", "http://localhost:8080"),
		Org:    allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/me", Summary: "Who is calling"},
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1,
				Resource: "note:*", Summary: "List your notes"},
			{Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1,
				Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}},
			{Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2,
				Resource: "note:{id}", Summary: "Delete a note"},
		},
		Templates: map[string]allowedby.Template{
			"notes:read":   allowedby.Text("Read your notes"),
			"notes:write":  allowedby.Text("Write new notes"),
			"notes:delete": allowedby.Text("Delete note {scope}"),
		},
		Title:           "Notes Interop API",
		RefreshInterval: refresh,
	})
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

type note struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

// store keeps each person's notes, by the pairwise id AllowedBy gives this service for them.
type store struct {
	mu   sync.Mutex
	last int
	by   map[string][]note
}

func (s *store) list(person string) []note {
	s.mu.Lock()
	defer s.mu.Unlock()
	return append([]note{}, s.by[person]...)
}

func (s *store) add(person, text string) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.last++
	id := strconv.Itoa(s.last)
	s.by[person] = append(s.by[person], note{ID: id, Text: text})
	return id
}

func (s *store) remove(person, id string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id })
}

const badText = "text: a string of 1 to 2000 characters"

// noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for.
const noPerson = "this route has no person: map it at level 1 or more"

// person is the id of the person the notes belong to, or a 403: never notes kept under an empty id.
func person(c echo.Context) (string, error) {
	who, _ := allowedbyecho.Context(c)
	id, ok := who.Human()
	if !ok {
		return "", echo.NewHTTPError(http.StatusForbidden, noPerson)
	}
	return id, nil
}

func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 }

From sdks/go/examples/frameworks/echo/main.go; tested in sdks/go/allowedbyecho/allowedbyecho_test.go.

chi:

// Command chi is the notes app of sdks/interop/reference_app.py on chi. CI runs it against a real node, agent
// and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py chi`.
//
//	GET    /me           the agent's passport is enough (level 0)
//	GET    /health       outside the route map: the app's own
//	GET    /notes        read, level 1: the person's own notes
//	POST   /notes        write, level 1: body {"text": string}
//	DELETE /notes/{id}   write-hard, level 2: one approval for exactly this request
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"slices"
	"strconv"
	"sync"
	"time"
	"unicode/utf8"

	"github.com/go-chi/chi/v5"
	allowedby "github.com/yannUpTo/allowedby/sdks/go"
	"github.com/yannUpTo/allowedby/sdks/go/allowedbychi"
)

func main() {
	aby, err := service()
	if err != nil {
		log.Fatal(err)
	}
	notes := &store{by: map[string][]note{}}
	r := chi.NewRouter()
	r.Use(allowedbychi.Middleware(aby))
	r.Get("/health", func(w http.ResponseWriter, _ *http.Request) {
		reply(w, http.StatusOK, map[string]bool{"ok": true})
	})
	// the routes of the map: registered with the SDK, which then knows each one's handler (rule 5)
	r.Method("GET", "/me", aby.Registered("GET /me", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		reply(w, http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level})
	})))
	r.Method("GET", "/notes", aby.Registered("GET /notes", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		me, ok := person(w, r)
		if !ok {
			return
		}
		reply(w, http.StatusOK, map[string]any{"notes": notes.list(me)})
	})))
	r.Method("POST", "/notes", aby.Registered("POST /notes", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		me, ok := person(w, r)
		if !ok {
			return
		}
		var in struct {
			Text string `json:"text"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil || !validText(in.Text) {
			reply(w, http.StatusBadRequest, map[string]string{"error": badText})
			return
		}
		reply(w, http.StatusCreated, map[string]string{"id": notes.add(me, in.Text)})
	})))
	r.Method("DELETE", "/notes/{id}", aby.Registered("DELETE /notes/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		me, ok := person(w, r)
		if !ok {
			return
		}
		notes.remove(me, chi.URLParam(r, "id"))
		reply(w, http.StatusOK, map[string]string{"deleted": chi.URLParam(r, "id")})
	})))
	r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
		reply(w, http.StatusNotFound, map[string]string{"error": "not found"})
	})
	srv := &http.Server{Addr: "127.0.0.1:" + getenv("PORT", "8081"), Handler: r, ReadHeaderTimeout: 10 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

// service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability.
func service() (*allowedby.Service, error) {
	refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s")
	if err != nil {
		return nil, err
	}
	return allowedby.New(allowedby.Options{
		Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"),
		Node:   getenv("ALLOWEDBY_NODE", "http://localhost:8080"),
		Org:    allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/me", Summary: "Who is calling"},
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1,
				Resource: "note:*", Summary: "List your notes"},
			{Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1,
				Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}},
			{Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2,
				Resource: "note:{id}", Summary: "Delete a note"},
		},
		Templates: map[string]allowedby.Template{
			"notes:read":   allowedby.Text("Read your notes"),
			"notes:write":  allowedby.Text("Write new notes"),
			"notes:delete": allowedby.Text("Delete note {scope}"),
		},
		Title:           "Notes Interop API",
		RefreshInterval: refresh,
	})
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

type note struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

// store keeps each person's notes, by the pairwise id AllowedBy gives this service for them.
type store struct {
	mu   sync.Mutex
	last int
	by   map[string][]note
}

func (s *store) list(person string) []note {
	s.mu.Lock()
	defer s.mu.Unlock()
	return append([]note{}, s.by[person]...)
}

func (s *store) add(person, text string) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.last++
	id := strconv.Itoa(s.last)
	s.by[person] = append(s.by[person], note{ID: id, Text: text})
	return id
}

func (s *store) remove(person, id string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id })
}

const badText = "text: a string of 1 to 2000 characters"

// noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for.
const noPerson = "this route has no person: map it at level 1 or more"

// person is the id of the person the notes belong to, or a 403: never notes kept under an empty id.
func person(w http.ResponseWriter, r *http.Request) (string, bool) {
	who, _ := allowedby.ContextFrom(r.Context())
	id, ok := who.Human()
	if !ok {
		reply(w, http.StatusForbidden, map[string]string{"error": noPerson})
	}
	return id, ok
}

func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 }

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

From sdks/go/examples/frameworks/chi/main.go; tested in sdks/go/allowedbychi/allowedbychi_test.go.

The SDK checks a request when its path names a route of the map either as decoded (how Gin routes) or segment by segment as escaped (how ServeMux, chi and Echo route), after RFC 3986 normalisation; a mapped route reached through an encoded / or \ in a segment (/notes/a%2Fb) is refused with 400 invalid_request, and so is a . or .. segment (/notes/., %2E included) where the path before dot removal names a route (those routers do not clean paths), and so is a path whose readings name two different routes, or that still holds a % once decoded (double encoding, /notes/%2564rafts). Variants of a protected route are refused too (CONTRACT §2.10): a doubled or trailing / (/notes/, //notes) and a method override (X-HTTP-Method-Override, X-HTTP-Method, X-Method-Override, _method in the query or a form body) that would turn the request into a mapped one.

After that, the middleware asks the router which of its routes and handlers the request goes to, and refuses (400) a request it did not verify that would run the handler of any route of the map, wherever the router uses that handler (another path, a catch-all), or a protected route: Echo gives the rest of the path to a last :param (/notes/7/x is /notes/:id for it), and a wildcard may serve a protected route (/notes/{id...}, /notes/*). The handler of each route of the map is found once with sample values (and from chi's own routes), then learnt from checked requests (CONTRACT §2.10 rule 5). A handler that also serves the route's path with a word replaced is a catch-all, not the route's own handler, and the route counts as not known until a checked request runs a handler of its own. A site-wide catch-all (the router chose it for the route's path with a word replaced through a site-wide wildcard rule: /*, an SPA fallback) is the site's own, never protected, while the routes it reaches have known handlers of their own; a route served only by it makes it that route's handler (a / handler that dispatches itself, a mounted router): protected, and the log names the route at the first request. A prefix catch-all (/notes/{id}/{rest...}) that the route's samples reach stays protected, its own handler known or not: it can only be another handler of that route, so an alias of it on another path is refused. A fallback the router chose through a site-wide wildcard rule is protected only while the route's own handler is not known (this is what keeps a tenant-first app's fallback pages working, under /{org}/notes/{id} too). Neither is ever learnt. A checked request runs a catch-all of its route only while the route has no known handler of its own (a dispatcher, a mounted router: it is the route's handler); next to the route's own handler it is refused, unless the router names a matched rule of the route's own shape (the pattern each adapter reports: Gin's FullPath, Echo's Path, the ServeMux pattern, chi's route pattern). Near a route whose handler is not known, a request the SDK did not check is refused (it cannot tell). A site-wide catch-all that is a protected route's only handler refuses every request the SDK did not check that it would serve. 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. One handler for several mapped methods of a route, such as the pre-1.22 pattern of one HandlerFunc for /notes/{id} that switches on r.Method, runs only for a request checked as a method that covers the others: the weaker method is refused (400), and the log names both routes at the first request. Register one handler per method instead: Go 1.22 method patterns (mux.HandleFunc("GET /notes/{id}", get) and mux.HandleFunc("DELETE /notes/{id}", del)), or the router's per-method registration (r.Get and r.Delete on chi, e.GET and e.DELETE on Echo, r.GET and r.DELETE on Gin). Closures made by one wrapper count as one handler (see below): requireLogin(get) on GET and requireLogin(del) on DELETE of /notes/{id} refuse checked requests to the method that does not cover the other, so give each method a named handler, register the handlers (below), or apply the wrapper as router middleware (r.Use, or a http.Handler around the mux). What checked requests teach lives in the process: it is lost on restart and not shared between instances, so until an instance has served a checked request for a route whose handler the samples miss, an alias of that handler far from the route is not refused there. The handlers are resolved, and these warnings logged, at the first request for each router (an adapter's routes are registered until then), not when the service is built. Make every protected route's handler known from the first request: patterns its sample values reach (0 or a in each parameter), or chi, whose routes the adapter lists. A func handler is known by its code (Echo: by its default name; a route given a Name of its own hides its handler, so a request the SDK did not check is refused on that route, and on every route when it is a route of the map), a pointer by its address: a method value written twice (h.Archive) is one handler, and so is every closure made by one wrapper or factory (a handle(fn) helper, echo.WrapHandler; a wrapper the compiler inlines, such as gin.WrapF, may give each call its own code). A route whose handler shares that code with a protected route's is refused when the SDK did not verify the request (fail closed), and so is a checked request for a route whose handler is also another route's (any template, any method) that it does not cover: one del on a level-3 DELETE /notes/{id} and a level-1 DELETE /items/{id} refuses DELETE /items/7. Give protected routes handlers of their own, not a wrapper your other routes use, or register them (below). Where the SDK does not see the router (aby.Handler around anything but a *http.ServeMux), every path that goes on below a protected parameter is refused, for the methods the map uses there.

Registered handlers (CONTRACT §2.10 rule 5, 1.9). Rather than let the SDK infer each route's handler, you can register it with the method and path it serves:

  • aby.HandleFunc(mux, "GET /notes/{id}", get) and aby.Handle(mux, pattern, h) register on a ServeMux;
  • aby.Registered("GET /notes/{id}", h) is the handler for a router that takes an http.Handler, such as chi: r.Method("GET", "/notes/{id}", aby.Registered("GET /notes/{id}", h)).

The pattern is METHOD /path (HEAD is read as GET), or a path alone for every method. The path is the route's path as the map writes it, with {param} and any mount prefix included, and no host. A pattern with a method must name a route of the map: one that names none (a host before the path, a chi path without its mount prefix) panics when it is registered, naming the nearest route. Register a page of your own with its path alone, or through the router. A registered handler of a route of the map runs only for a request the SDK checked for that route. Every other request is refused with 400 invalid_request:

  • one the SDK did not check (the SDK is not in front, or another method);
  • one checked for another route;
  • one checked for a route that does not cover every other route of the map the handler is registered on (the weaker is refused, and the log names the two routes once).

A registered closure is known by its value, so aby.HandleFunc(mux, "GET /notes/{id}", requireLogin(get)) and aby.HandleFunc(mux, "DELETE /notes/{id}", requireLogin(del)) no longer count as one handler, while one closure registered on two routes is one handler. (Telling closures apart by value reads how the Go toolchain represents a func value, which the language does not specify: a self-test at start-up checks it, and if it ever fails, a closure is known by its code as without registration, which refuses rather than allows, and the log says so once.) A named function, or one handler value, registered twice is one handler. A method value (store.Del) is a new value each time it is written, so it is known by its code, as the router checks know it: two method values of one method are one handler, whatever their receivers (give each route a closure or a function of its own). On a path the map does not have, a route's handler is its alias and is refused there. A registered handler that serves no route of the map runs as before.

The router checks above still run, and see each registration as its handler. A use registered through the router's own API (mux.HandleFunc, or r.Get with the bare handler) is known by its code, as without registration: a bare use of a registered closure stays protected (an unchecked request to it is refused, and so is one checked for a route that does not cover the registered one's), and so does a bare closure of the same wrapper. Gin and Echo, whose handlers are not http.Handler, have no registration yet. A refusal names the fix, never the request. Options.Unprotected lists your own pages that these rules refuse: {Method: "GET", Path: "/notes/{id}/comments"} (a template, for pages below a protected route: it has a word of its own, and names its method when it lies below a route of the map), or {Method: "GET", Path: "/notes/new/"} (an exact path, with no ;, encoded or control character); where the SDK sees the router, a declared page never opens a protected handler; elsewhere the entry is your word that the router runs your page for that path, except an exact path that is a protected route but for its last / (/notes/new/ next to /notes/{id}): that one has no effect there, the request stays refused, and the log says so once. A protected handler never runs unchecked, for any method, and no entry lifts that: the refusal says to map that method too, or to give it a handler of its own. Also refused: a control character in a protected path, and a protected path seen without its prefix (below http.StripPrefix): write the map with the paths the SDK sees, and mount it where those are the paths agents call. Do not give one handler to every method (Any) unless it checks the method: the map protects the methods it lists. Put the SDK after any middleware that rewrites the path (Echo Pre rewrites, chi StripSlashes). Make sure your router does not serve a protected handler under another spelling of a mapped path (a trailing slash, other letter case). HEAD is read as GET in all these rules: a ServeMux, chi's GetHead or an explicit HEAD route given a GET handler run it for HEAD. A refusal names no part of the request (path, query, headers), and the log names only the route template and the code: paths may hold personal data or tokens. (An approval challenge on a mapped route carries its scope, the route's Resource with its parameters, built from the path normalised as for htu (/notes/%61b gives note:ab), as ABY-2 §6 defines it, and only when each value is 1 to 64 of A-Z a-z 0-9 . _ - and the whole at most 256 bytes, so it is safe in a header and an approval of it satisfies the route; otherwise the request is refused with 400, and the scope is never logged.) On a ServeMux, a protected handler registered only under a host pattern (notes.example/notes/{id}) is known as protected for requests to that host; give it to no hostless pattern.

The context#

allowedby.ContextFrom(r.Context()) returns who called and with which approval; ok is false on paths outside the route map.

Field Type Meaning
HumanID string The person's pairwise id for your service: stable here, different at every other service. Empty at level 0 (identity routes), where an agent calls with no person.
Level int The identity level proven: 0 (agent only) to 3.
Agent string The agent's passport subject, did:oaid:<node>:<id>.
Operator string Who runs the agent: its verified domain, or a node-scoped id.
Capabilities []string What the approval allows.
Display *allowedby.Display The sentence the person signed: Summary, Lines, Lang.
GID, Rev, JTI string, int64, string The approval's id, revision and document id.
Chain []allowedby.ChainLink The grant chain, leaf first (GID, Rev).
HumanIssuer string The person's home node.
Route string The route that matched, e.g. DELETE /notes/{id}.
ProofJTI, Run, Call string, string, *int64 The request proof's id and the agent's own audit labels.
ActingFor *allowedby.ActingFor Company mandates: always nil in the Go SDK for now.
Tenant string The {tenant} path parameter when the route has one, decoded once as in Params (Options.Tenants tightens the route for it, and caps its amounts).
Params map[string]string The route's path values as the SDK checked them: each {name} of the route, from the normalised path, decoded once. Empty, never nil, without parameters.
LinkedAccount string On a RequireLink route, the account of yours the person is linked to (account linking). Empty elsewhere.

The context is a copy: changing it changes nothing else.

Key a person's data by who.Human(), which returns the id and false when there is no person (a level-0 route proves an agent only, and HumanID is then empty). When it is false, refuse or store nothing: never keep data under an empty id, which every level-0 caller would share. The examples answer 403 (their person helper).

Act on Params, never on your own reading of the raw path: the two can differ (/notes/%37 is checked as note 7, DELETE /notes/7/. as /notes/7). Each value is decoded once (acme%20co gives acme co), and the SDK refuses a path that a router could read another way: an encoded /, or a value that still holds a % once decoded (%2561). A router hands your handler the values it matched (r.PathValue on a ServeMux, c.Param on Gin and Echo, chi.URLParam); a handler with no router behind aby.Handler or aby.Check sees only the raw path, and takes the values from Params (examples/frameworks/nethttp/main.go uses it for the note id).

Changed after the check. A step after the SDK (a middleware, a wrapper inside a handler) that rewrites an accepted request's path or method, or passes on another request (r.WithContext or r.Clone with another URL), would have the handler act on values the person never approved. The SDK records the method and the normalised path it accepted (another spelling of the same path, or HEAD for GET, is the same request), and:

  • allowedbygin.Context(c) and allowedbyecho.Context(c) refuse a changed request (400 invalid_request, the path never repeated) and give no context: return when ok is false. Gin, and Echo with Use, route before their middleware runs, so the handler and its c.Param are the ones checked; only the request was changed. With e.Pre, a Pre middleware after the SDK's (middleware.Rewrite) makes Echo route the rewritten request to another route or value: allowedbyecho.Context(c) refuses it there too, since it compares the request the handler got.
  • On chi, allowedby.ContextFrom gives no context to a handler that chi routed to another method, route or value (the route context tells), and allowedby.RequireUnchanged as the router's last Use refuses the request with 400: it asks chi how it would route the request now, so a middleware that sets the route context's RoutePath (chi's own rewrite) is refused too.
  • On a ServeMux (aby.Handler(mux) runs the mux right after the check), allowedby.ContextFrom gives no context when the accepted request was changed in place, and allowedby.ContextOf(r) also compares the request the handler got. Behind a step of your own, put the step and allowedby.RequireUnchanged around the handler, inside the mux: mux.Handle("GET /notes/{id}", step(allowedby.RequireUnchanged(h))). Never put anything between aby.Handler and the mux (aby.Handler(step(mux))): the SDK then no longer sees the mux, and its router checks (CONTRACT §2.10 rules 2 and 5) are off. The SDK sees through RequireUnchanged: h is still known as itself, and aby.Handler(allowedby.RequireUnchanged(mux)) still checks the mux.

Limits: where the SDK does not see the router (aby.Handler or aby.Check around anything but a ServeMux), and in a handler that reads allowedby.ContextFrom behind a step that passes on another request, nothing tells the SDK which request the handler runs for: use allowedby.ContextOf(r) or allowedby.RequireUnchanged, or put nothing that changes the method or the path after the SDK. http.StripPrefix after the SDK passes on another path: there, ContextOf and RequireUnchanged refuse, and ContextFrom still answers.

Production#

In production, keep the keys in a key file shared by every instance, share the replay set in Redis, and close the service on shutdown.

// Command production is the production recipe of docs/sdk/go.md: keys kept in a key file, the replay set shared
// in Redis by every instance, and a clean shutdown.
//
// In a container, next to a Redis service named redis (ALLOWEDBY_BIND is the address to listen on: 127.0.0.1, loopback
// only, when it is unset or empty; 0.0.0.0 in a container, so that its port mapping reaches the service):
//
//	ALLOWEDBY_ORIGIN=https://notes.example ALLOWEDBY_NODE=https://node.example.org ALLOWEDBY_BIND=0.0.0.0 PORT=8080 \
//	ALLOWEDBY_KEY_FILE=/var/lib/notes/allowedby-keys.json REDIS_URL=redis://redis:6379/0 ./production
package main

import (
	"cmp"
	"context"
	"errors"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/redis/go-redis/v9"
	allowedby "github.com/yannUpTo/allowedby/sdks/go"
	"github.com/yannUpTo/allowedby/sdks/go/allowedbyredis"
)

func main() {
	ropts, err := redis.ParseURL(os.Getenv("REDIS_URL"))
	if err != nil {
		log.Fatal("REDIS_URL: ", err)
	}
	aby, err := allowedby.New(allowedby.Options{
		Origin:  os.Getenv("ALLOWEDBY_ORIGIN"), // your public https origin
		Node:    os.Getenv("ALLOWEDBY_NODE"),   // the node you trust
		Org:     allowedby.Org{LegalName: "Notes Ltd", Country: "FR", PrivacyPolicy: "https://notes.example/privacy"},
		KeyFile: os.Getenv("ALLOWEDBY_KEY_FILE"), // the same file on every instance (a secret volume)
		Store:   allowedbyredis.New(redis.NewClient(ropts), "notes:allowedby:"),
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1,
				Resource: "note:*"},
		},
		Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")},
	})
	if err != nil {
		log.Fatal(err)
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	mux := http.NewServeMux()
	mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"notes": []}`))
	})
	srv := &http.Server{Addr: net.JoinHostPort(cmp.Or(os.Getenv("ALLOWEDBY_BIND"), "127.0.0.1"), cmp.Or(os.Getenv("PORT"), "8080")), Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()
	<-ctx.Done()
	shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_ = srv.Shutdown(shutdown)
	_ = aby.Close()
}

From sdks/go/examples/production/main.go. CI runs two instances of it with a real Redis and one key file (sdks/go/examples/prove_examples.py), and the trust-list app below.

  • Keys (KeyFile): the Ed25519 signing key (it signs your organisation profile and the approvals you ask for; its kid is the initiator of serious grants) and the P-256 disclosure key. The file is created on first use with mode 0600, atomically, first writer wins, in the same JSON format as every other SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point KeyFile at it, or write it from your secret manager. An existing file works anywhere. Without KeyFile, keys are new at each start and agents re-read /.well-known/allowedby.
  • Listening: the examples listen on ALLOWEDBY_BIND (default 127.0.0.1, loopback only) and PORT (default 8080); an empty value counts as unset (cmp.Or). A container sets ALLOWEDBY_BIND=0.0.0.0 so that its port mapping reaches the service.
  • Store: MemoryStore (the default) is for one process only. With several instances, a proof replayed to another instance would be accepted there: use allowedbyredis.New(client, prefix). Expiry follows the SDK's clock; with Redis Cluster put a hash tag in the prefix ("allowedby:{aby}:"). Any store error refuses the request (503).
  • Handlers: what the adapters learn from checked requests (rule 5) is per process, like MemoryStore: make each protected route's handler known at start-up (see Framework recipes).
  • 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 any handler started, it gives back exactly what the request spent, once, so the approval serves the request on its own route afterwards. That covers a router check (rule 5) in aby.Handler(mux) and the Gin, Echo and chi middleware, and, on chi, allowedby.RequireUnchanged in front of the routing (a request moved by a middleware after the SDK's). RequireUnchanged as the handler a ServeMux chooses, or around the mux, also refunds, and so does a registered handler that refuses (Framework recipes), behind a ServeMux or any other router: behind a router the SDK does not see, aby.Handler starts the request once the router returns. Nothing is refunded once the request was handed to its handler, for a refusal of your own (a handler or a middleware that answers), or for allowedbygin.Context and allowedbyecho.Context, which run inside the handler. A refunded request never reaches a handler, even dispatched again. 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 SDK trusts Node on first use and pins its node key; a changed key is refused and logged. With a signed OAID-5 trust list, allowedby.ParseTrustList(jws, signerJWK) and Options.TrustList decide which nodes count (anchors, program lists, vouching, witnesses):
// Command trustlist is the trust-list recipe of docs/sdk/go.md: trust the nodes of a signed OAID-5 trust list
// instead of trust on first use of one node.
//
// On one host (ALLOWEDBY_BIND is the address to listen on: 127.0.0.1, loopback only, when it is unset or empty; 0.0.0.0
// in a container):
//
//	ALLOWEDBY_ORIGIN=https://notes.example ALLOWEDBY_NODE=https://node.example.org ALLOWEDBY_BIND=127.0.0.1 PORT=8080 \
//	ALLOWEDBY_TRUST_LIST=trust-list.jws ALLOWEDBY_TRUST_LIST_KEY='{"kty":"OKP","crv":"Ed25519","kid":"...","x":"..."}' ./trustlist
package main

import (
	"cmp"
	"encoding/json"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	allowedby "github.com/yannUpTo/allowedby/sdks/go"
)

func main() {
	jws, err := os.ReadFile(os.Getenv("ALLOWEDBY_TRUST_LIST")) // the signed list (oaid-trust+jwt)
	if err != nil {
		log.Fatal(err)
	}
	var signer map[string]any // the public JWK of the key that signed it
	if err := json.Unmarshal([]byte(os.Getenv("ALLOWEDBY_TRUST_LIST_KEY")), &signer); err != nil {
		log.Fatal("ALLOWEDBY_TRUST_LIST_KEY: ", err)
	}
	tl, err := allowedby.ParseTrustList(string(jws), signer)
	if err != nil {
		log.Fatal(err)
	}
	aby, err := allowedby.New(allowedby.Options{
		Origin:    os.Getenv("ALLOWEDBY_ORIGIN"),
		Node:      os.Getenv("ALLOWEDBY_NODE"), // still where the service asks for approvals
		TrustList: tl,                          // which nodes' passports and approvals are accepted
		Org:       allowedby.Org{LegalName: "Notes Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1},
		},
		Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer aby.Close()
	mux := http.NewServeMux()
	mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"notes": []}`))
	})
	srv := &http.Server{Addr: net.JoinHostPort(cmp.Or(os.Getenv("ALLOWEDBY_BIND"), "127.0.0.1"), cmp.Or(os.Getenv("PORT"), "8080")), Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second}
	log.Print(srv.ListenAndServe())
}

From sdks/go/examples/trustlist/main.go.

  • Refresh: node statements and status lists are fetched in the background every RefreshInterval (default 5 s, 1 s to 60 s), never on the request path. 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) trusts its node and holds its status lists before its first request. Status lists older than 60 s (write-hard, irreversible) or 3600 s (read, write) fail closed with 503 status_stale.
  • Logging: Options.Logger (*slog.Logger, default slog.Default()) gets [verifier] refresh failed with the reason at each failed refresh, and one line per refusal with the route pattern and the code. Never tokens, keys, bodies or personal data.
  • Limits: Allowed-By and AllowedBy-Proof together at most 8 KiB and two JWS, a grant and one child (431; a child of a child is refused); request bodies on mapped routes at most MaxBodyBytes (1 MiB) and a JSON object (400) without member names that are equal or differ only in case (encoding/json would read the last one); the memory store holds 200 000 entries and refuses new ones when full of live entries.
  • Behind a proxy: set Origin to the public origin agents call. Forwarded headers are ignored: proofs are checked against Origin and the normalised path.

Agents#

The Go SDK is a service SDK only; agent runtimes use the Python or TypeScript agent SDK (docs/sdk/python.md, docs/sdk/js.md).

For tests, allowedbytest.Agent (section Testing) signs requests the way an agent runtime does: a passport or grant in Allowed-By and a fresh proof in AllowedBy-Proof.

Errors#

Every refusal is an RFC 9457 problem document (application/problem+json, type: https://allowedby.org/errors/<code>), with the same code and status in every SDK.

Code Status Meaning What to do
invalid_request 400 Malformed Allowed-By, a mix of passport and grants, a body that is not a JSON object, a header sent twice. Fix the request.
passport_required 401 No Allowed-By header. The agent gets a passport from its node and sends it.
invalid_signature 401 A signature, proof, human_sig or chain link does not verify, or a proof is replayed or for another URL or body. The agent signs a fresh proof for this exact request.
untrusted_node 401 The document comes from a node this service does not trust (or no refresh has reached it yet: the first one at start failed or took over 5 s). Use a trusted node; wait for the next refresh.
insufficient_witnesses 401 The node's log is not cosigned by enough trusted witnesses (trust list). The node operator fixes its witnessing.
grant_required 401 A passport on a route that needs a person's approval. Follow the challenge: ask the person, retry with the grant.
grant_insufficient 401 The grant does not cover this request (capability, scope, amount, audience, single-use request, initiator). Ask for an approval that covers it.
level_insufficient 401 The person's identity level is below the route's. The person verifies their identity to the level, then approves.
qes_required 401 The route needs a qualified electronic signature. Not available in the Go SDK (refused at configuration).
authority_required 401 The organisation's co-approvers are missing. Not available in the Go SDK.
mandate_required 401 A company mandate is missing or does not cover the request. Ask for a personal approval: the Go SDK accepts no mandates and refuses every grant with acting_for.
expired 401 The grant or passport has expired. Ask again (or renew the passport).
not_yet_valid 401 The grant's nbf is in the future. Check the clocks; retry later.
revoked 401 The person withdrew the approval, or the passport or registration is revoked. Ask the person again.
actor_expired 401 The agent key named in the grant has expired. The agent rebinds the grant or gets a new passport.
class_lifetime_exceeded 401 The grant lasts longer than the route's class allows. Ask for a shorter approval.
single_use_consumed 401 A one-time approval was already used. Ask again for the new request.
capability_denied 403 No such route in the route map. Call a route the service publishes.
tier_insufficient 403 The agent's key custody or the passkey class is too weak for the route. Use a stronger key custody or passkey.
human_not_linked 403 The route needs a person linked to one of your accounts (RequireLink), to the one its path names. Link the account first: aby:link with the code of the account page (see Account linking).
budget_exceeded 403 A company budget is used up. Not available in the Go SDK.
rate_limited 429 Too many calls from this agent or its operator (Options.Rate). Wait (Retry-After: 60).
envelope_too_large 431 Allowed-By and AllowedBy-Proof over 8 KiB, or a chain over two grants (a grant and one child). Send a shorter chain.
status_stale 503 The revocation list is too old, or the replay store is unavailable (fail closed). Retry after Retry-After seconds.

Challenges (401 with WWW-Authenticate: AllowedBy realm=..., error=..., action=..., scope=..., class=..., level=..., tier=...) come with grant_required, grant_insufficient, level_insufficient, expired, revoked, class_lifetime_exceeded, single_use_consumed and actor_expired on routes with a capability. For write-hard and irreversible routes they also carry approve, poll, code, request and expires: the approval the service created at its node (ABY-2 §6).

Testing#

go test ./... in sdks/go runs the CONF-1 vectors (481 cases read from vectors/), the unit tests and the examples; python sdks/interop/interop.py runs the end-to-end interop test (26 scenarios) against the Go app.

Linux and macOS:

cd sdks/go
go test -run TestVectors -v .          # prints "481/481 cases passed"
go test -race ./...
go vet ./...
go install honnef.co/go/tools/cmd/staticcheck@2026.2.2 && "$(go env GOPATH)/bin/staticcheck" ./...
go build -o /tmp/aby-interop ./examples/frameworks/nethttp
cd ../.. && pip install -r requirements.txt
INTEROP_PORT_BASE=19300 python sdks/interop/interop.py --cmd /tmp/aby-interop

Windows (PowerShell):

cd sdks/go
go test -run TestVectors -v .          # prints "481/481 cases passed"
go test ./...
go build -o "$([IO.Path]::GetTempPath())aby-interop.exe" ./examples/frameworks/nethttp
cd ../..; pip install -r requirements.txt
$env:INTEROP_PORT_BASE = "19300"; python sdks/interop/interop.py --cmd "$([IO.Path]::GetTempPath())aby-interop.exe"

Every framework and Go version: python sdks/go/examples/run_frameworks.py. The command blocks of this page: python sdks/go/examples/run_blocks.py.

Set ALLOWEDBY_VECTORS to the vectors/ directory when the tests do not run from sdks/go. Fuzz the parsers with go test -run '^$' -fuzz FuzzVerify . (also FuzzSigInput, FuzzNormPath, and FuzzParseJSON, FuzzParseJWS, FuzzCanon in ./internal/jose).

Test your own app without a browser, a passkey or a node: allowedbytest is a fake node (passports, grants signed with a software passkey, status lists, approvals) and an agent that signs requests.

package notes

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	allowedby "github.com/yannUpTo/allowedby/sdks/go"
	"github.com/yannUpTo/allowedby/sdks/go/allowedbytest"
)

func TestNotesWithAnAgent(t *testing.T) {
	node := allowedbytest.NewNode(t) // a fake node on a local test server
	aby, err := allowedby.New(allowedby.Options{
		Origin: "https://notes.example", Node: node.URL(),
		Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1},
		},
		Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")},
	})
	if err != nil {
		t.Fatal(err)
	}
	defer aby.Close()
	if err := aby.Refresh(context.Background()); err != nil { // trust the node now
		t.Fatal(err)
	}
	app := aby.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		_, _ = w.Write([]byte(who.HumanID))
	}))

	agent := node.NewAgent()
	// Without the person's approval: 401 and a challenge.
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, agent.Request("GET", "https://notes.example/notes", nil, agent.Passport))
	if rec.Code != 401 || rec.Header().Get("WWW-Authenticate") == "" {
		t.Fatalf("without approval: %d", rec.Code)
	}
	// With it: the handler runs and knows who the person is (their pairwise id).
	grant := node.Grant(agent, allowedbytest.GrantSpec{Origin: "https://notes.example", Capability: "notes:read",
		Scope: "notes:*", Class: "read", Level: 1})
	rec = httptest.NewRecorder()
	app.ServeHTTP(rec, agent.Request("GET", "https://notes.example/notes", nil, grant))
	if rec.Code != 200 || rec.Body.String() != allowedbytest.HumanID {
		t.Fatalf("with approval: %d %s", rec.Code, rec.Body)
	}
}

From sdks/go/examples/testing/notes_test.go. node.Revoke(idx) revokes, node.SetStale(true) makes the status list old, node.Approvals() lists the approvals your service asked for, and GrantSpec.SingleUse with allowedbytest.RequestDigest builds the one-time grant of a write-hard route.

Reference#

The public API is New, Options, Service (Handler, Check, Refresh, Close), Route, Template, ContextFrom and Context, Store, and ParseTrustList.

Name What
func New(opts Options) (*Service, error) Validates the configuration, loads or creates the keys, starts the background refresh and waits for its first run (at most 5 s).
type Options struct Origin, Node, Org, Routes, Templates (required); KeyFile, Store, TrustList, RefreshInterval, NodeMaxLevel, Clock, Title, Version, Description, RFC9421, Unprotected, HTTPClient, Logger, MaxBodyBytes, Nonce, Rate, LinkAuthorize.
func (*Service) Handler(next http.Handler) http.Handler The net/http middleware.
func (*Service) Check(w, r) (*http.Request, bool) The middleware as a function, for adapters: false when it wrote the response.
func (*Service) CheckRouted(w, r, router, chosen) (*http.Request, bool), type Router, type HostRouter, type EndpointLister, type Endpoint, type Dispatch, Unknown Check for an adapter that sees the route and the handler its router chose.
type OwnPath struct An entry of Options.Unprotected.
func (*Service) Refresh(ctx) error Fetches node statements and status lists now.
func (*Service) LinkStart(account string, ttl time.Duration) (string, error) A linking code for one of your accounts (account linking).
func (*Service) Unlink(account string) (bool, error) Removes an account's link and its pending codes (account linking).
func (*Service) Close() error Stops the background refresh.
type Route struct, type Class, Read, Write, WriteHard, Irreversible, type Threshold The route map (section Routes and templates).
type Template struct, func Text(en string) Template The sentences people sign.
type Org struct, type Logo struct The organisation profile (ORG-1 §2).
func ContextFrom(ctx) (Context, bool), type Context, Display, ChainLink, ActingFor What a handler learns.
type Store interface, type Charge, type MemoryStore, func NewMemoryStore() Replay set, single use and counters.
type TrustList, func ParseTrustList(jws string, signer map[string]any) (*TrustList, error) OAID-5 trust lists.
const Version, const SpecVersion 0.1.0 and 0.2.14.
allowedbygin.Middleware(aby, engine), allowedbygin.Context Gin.
allowedbyecho.Middleware, allowedbyecho.Context Echo.
allowedbychi.Middleware chi.
allowedbyredis.New(client, prefix) *Store The Redis store.
allowedbytest.NewNode, Node.NewAgent, Node.Grant, Agent.Request, GrantSpec Testing.

What is implemented (sdks/CONTRACT.md §2):

Item Status
Configuration, route map, discovery (/.well-known/allowedby, /openapi.json, /.well-known/api-catalog) core: done
Verification, ABY-2 §5 steps 1-10: proof JWT and RFC 9421, passports, grant chains, human_sig (WebAuthn: ES256, EdDSA, RS256 passkeys), human.reg, initiator, status lists, class and lifetime, scope, amount (per call, grant, day, week, month), count, fields, window, request digest and single use, replay set, TOFU and OAID-5 trust lists, EdDSA and ES256 only core: done
Challenges and service-initiated approvals (ABY-2 §6) core: done
Background refresh, context, store (memory, Redis), key file, net/http, Gin, Echo, chi core: done
Account linking (aby:link at /allowedby/link, RequireLink, AccountParam, LinkStart, Unlink, ABY-3 §6) extended: done (CONTRACT 1.8, 1.17)
AllowedBy-Nonce (Options.Nonce, Route.Nonce, ABY-2 §3.2), level profiles (LevelProfile, OAID-7 §5.3), rate limits (Options.Rate) extended: done (CONTRACT 1.12)
Tenants and tenant budgets (Options.Tenants, RefundBudget, ORG-1 §3.3, §5.3) extended: done (CONTRACT 1.16), mandates enforced fail closed
Disclosure callback and JWE (/allowedby/callback), authority policies, company mandates, QES, audit sink, admin console extended: not yet; the matching route options are refused by New

AllowedBy-Nonce#

A nonce proves that a request was made just now, for this service (ABY-2 §3.2). With Options.Nonce on, a route with Nonce: true, and every Irreversible route, refuses a proof without a current nonce: 401 invalid_signature, with a fresh nonce in the AllowedBy-Nonce header. The agent retries once with it, in the proof (nonce) or, with RFC 9421, in its AllowedBy-Nonce header, which counts only when the signature covers it (a covered value that is not base64url is refused with 401). A route with Nonce while Options.Nonce is off fails in New.

A nonce is stateless: its issue time and a MAC, base64url(t ‖ HMAC-SHA256(nonce key, t)[0:16]), t the time in seconds as 8 bytes big-endian. It is current for 300 s, on every instance that shares the key file (KeyFile), and across a restart. The nonce key is HKDF-SHA256 of the signing key's raw private key (no salt, info allowedby/nonce/v1), so every SDK on one key file takes the others' nonces. Without a key file, each instance has its own keys, and so its own nonces.

Level profiles#

A level-3 route can require the profile of the person's level-3 identity check (OAID-7 §5.3): LevelProfile: "eu" (eIDAS high) or "na" (the North-American profile). A grant whose registration has another profile, or none, is refused with 401 level_insufficient, and the approval the service asks for names the profile, so the person's node offers only sources of it. Without LevelProfile, a level-3 route takes either. New refuses it below level 3.

Rate limits#

Options.Rate limits the calls per agent ("actor", the passport's sub) and per operator ("operator", its operator.id): map[string]allowedby.RateLimit{"actor": {Calls: 20, Per: time.Minute}}. The defaults are 600 and 6000 calls a minute; a key you leave out keeps its default, and any other key, or a limit that is not a positive number of calls in whole seconds, fails in New (a misspelt limit would leave the default in place). The window slides on Clock: a call at t sees those at x with t - x under the window. 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 over either limit gets 429 rate_limited with Retry-After: 60, and counts for neither. The counts are kept in the process, like MemoryStore: behind several instances, each counts its own calls. Each limit keeps at most 10 000 agents (or operators), as the reference: a new one past that pushes out the one used least recently, in constant time, so a flood of new passports can neither grow it nor slow it down.

Tenants and tenant budgets#

Options.Tenants lists the accounts the service hosts, by id, each named by the path parameter {tenant} (ORG-1 §3.3): map[string]allowedby.Tenant{"acme": {Name: "Acme", Routes: map[string]allowedby.TenantRoute{"invoices:pay": {Level: 2, AmountMax: "1000.00"}}}}. An override only tightens the route of that capability for that tenant: the higher Level, the stronger Authn (synced, hardware), RequireLink (and then level 1 at least), the shorter MaxLifetime, a lower ceiling AmountMax (above it, or without an amount, 403 capability_denied, whatever the person approved), and Operators, an allowlist of operator.id (any other operator gets 403 capability_denied). An override that would loosen the route changes nothing. New refuses a tenant id outside [A-Za-z0-9_-]{1,64}, a Name over 200 characters, an Org that is not an https origin with no path, MembersOnly without Org, a capability the route map does not have, a value out of range, and an override or a budget on a capability that has a route without {tenant} (where it would never apply; the error names the route). It copies the option: changing your map afterwards changes nothing.

Until this SDK verifies mandates (CONTRACT: company mandates), such a tenant route refuses every request with mandate_required: a Mandate: true override, and every route of a MembersOnly tenant, its identity routes too (an agent alone acts for no organisation). Such a route never challenges: any refusal an approval would fix there (grant_required, expired, ...) is the same plain 401 mandate_required, with no WWW-Authenticate. QES and Authority overrides are refused by New, as the route options are.

A tenant budget caps the amounts the service accepts on a capability (ORG-1 §5.3): Budgets: map[string]allowedby.Budget{"invoices:pay": {Max: "5000.00", Currency: "EUR", Per: "day", TZ: "Europe/Paris"}}, per day, week or month in TZ (default UTC). Every route of that capability needs an AmountField, or New refuses the budget. The count is kept in the verifier's store, per tenant, capability, currency, time zone and period, so every instance that shares the store (allowedbyredis) shares it; only an accepted request counts, in one store call that checks and adds. A request without an amount in the budget's currency, or over what is left, is refused with 403 budget_exceeded, before any challenge, so no approval is asked for. When the store does not answer, the request gets 503 status_stale with Retry-After, and what the check spent is given back. A refund on the SDK's own refusal gives the amount back too, and so does aby.RefundBudget(r), when your handler refuses an accepted request (a wrong total, an unknown invoice), once.

Account linking#

Account linking (ABY-3 §6) ties a person's AllowedBy identity to one of your accounts, so that a route can require the person who owns the account, not just any approved person.

  1. Your signed-in account page calls aby.LinkStart(account, 0) and shows the code: 96 random bits, single use, valid 600 s (ttl, 1 s to a day). A new code for an account leaves its older ones pending.
  2. The person gives the code to their agent, which sends POST /allowedby/link with {"code": "..."}. The SDK serves this route itself (New refuses an app route at that path), on that exact path only: a variant of it (an encoded letter such as /allowedby/%6Cink, a trailing or doubled slash, a dot segment) goes to your app as a path outside the map, asks for no approval and links nothing (CONTRACT 1.13). It checks the code first, before any approval is asked for: an unknown, used, revoked or expired code gets 400 invalid_request.
  3. The request is then verified on the SDK's own route: aby:link, write, level 1, scope aby:link, single-use approvals only. Without one, the service asks the node for the approval itself, bound to this request (401 with the approve link). The person approves "Link your approvals to your account at " (Templates["aby:link"] overrides it).
  4. Once accepted, the code is spent, the account's other pending codes are revoked, and the person (their home node and their pairwise id here) is linked to the account, replacing whoever was linked to it: 200 {"linked": true}.

A route with RequireLink answers 403 human_not_linked unless the person of the approval is linked, and, when its path has the AccountParam parameter (account by default), linked to that account (compared as Context.Params has it: decoded once). The same pairwise id from another home node is another person. The approvals the service asks for on a linked account name its person (human_home, human_hint), so their node offers them first. On a RequireLink route, Context.LinkedAccount is the account the person is linked to: act for that one, which matters on a route whose path names no account (GET /me/notes). Options.LinkAuthorize, your own rule, is then asked (account, route, params) for a linked person (never for one who is not): only true lets them through; false, or a panic in it (recovered), answers 403 human_not_linked, as Python's link_authorize does. It gets its own copy of params.

aby.Unlink(account) removes an account's link (ABY-3 §6, Removing a link), when you delete the account or the person asks to be forgotten: the linked pair and the account's pending codes go, and a RequireLink route refuses the person (403 human_not_linked) until they link again with a new code. It reports whether the account was linked (false, a no-op, for an account that was not) and fails for an empty account, as LinkStart does.

Codes and links live in the process, in memory, like MemoryStore: at most 10 000 pending codes (LinkStart fails beyond that, it never drops one) and 100 000 links (the oldest goes). Behind several instances, a code links on the instance that issued it, and a link holds on the instance that made it: keep the links with your accounts, or route an account to one instance. /.well-known/allowedby has link and the aby:link capability, and /openapi.json describes the route.

The extended interop app runs these features against a real node, agent and people (sdks/interop/ext/interop_ext.py --features linking,unlink,nonce,level_profiles,rate,tenants,tenant_budgets):

// Command interop_ext is the extended interop app (sdks/interop/ext/reference_app.py, in Go): account linking
// (ABY-3 §6, unlink too), AllowedBy-Nonce (ABY-2 §3.2), level profiles (OAID-7 §5.3), rate limits, tenants and tenant
// budgets (ORG-1 §3.3, §5.3), for sdks/interop/ext/interop_ext.py. CI runs it against a real node, agent and people:
// `python sdks/interop/ext/interop_ext.py --features linking,unlink,nonce,level_profiles,rate,tenants,tenant_budgets
// --cmd <the built examples/interop_ext>`.
//
//	GET  /me                        the agent's passport is enough (level 0)
//	GET  /accounts/{account}/notes  read, level 1: a person linked to that account only
//	POST /allowedby/link            the SDK's own (aby:link, single use)
//	POST /drafts                    write, level 1, with an AllowedBy-Nonce: {"saved": true}
//	GET  /vault/eu/{id}             read, level 3 of the EU profile: {"vault": id}
//	GET  /vault/na/{id}             read, level 3 of the North-America profile: {"vault": id}
//	POST /t/{tenant}/orders         write, level 1, an amount at /total: {"ordered": total, "account": tenant};
//	                                tenants umbrella (as the map says), hooli (a ceiling of 50.00), budget (100.00
//	                                EUR a day)
//	POST /interop/link-code         outside the route map (TEST ONLY: it stands for the signed-in account page,
//	                                which shows the code): body {"account": string} -> {"code": string}
//	POST /interop/unlink            outside the route map (TEST ONLY: the account page removes the link, ABY-3 §6):
//	                                body {"account": string} -> {"was_linked": bool}
//
// Nonces are on; rate limits: 20 calls a minute per agent, 1000 per operator.
package main

import (
	"cmp"
	"encoding/json"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	allowedby "github.com/yannUpTo/allowedby/sdks/go"
)

func main() {
	refresh, err := time.ParseDuration(cmp.Or(os.Getenv("ALLOWEDBY_REFRESH_SECONDS"), "5") + "s")
	if err != nil {
		log.Fatal(err)
	}
	aby, err := allowedby.New(allowedby.Options{
		Origin: os.Getenv("ALLOWEDBY_ORIGIN"),
		Node:   os.Getenv("ALLOWEDBY_NODE"),
		Org:    allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"},
		Routes: []allowedby.Route{
			{Method: "GET", Path: "/me", Summary: "Who is calling"},
			{Method: "GET", Path: "/accounts/{account}/notes", Capability: "notes:read", Class: allowedby.Read,
				Level: 1, Resource: "account:{account}", RequireLink: true, Summary: "List the notes of an account"},
			{Method: "POST", Path: "/drafts", Capability: "drafts:write", Class: allowedby.Write, Level: 1,
				Resource: "draft:new", Nonce: true, Summary: "Save a draft",
				Body: map[string]string{"text": "the draft"}},
			{Method: "GET", Path: "/vault/eu/{id}", Capability: "vault:read", Class: allowedby.Read, Level: 3,
				Resource: "vault:{id}", Authn: "hardware", LevelProfile: "eu", Summary: "Open a vault (EU level 3)"},
			{Method: "GET", Path: "/vault/na/{id}", Capability: "vault:read", Class: allowedby.Read, Level: 3,
				Resource: "vault:{id}", Authn: "hardware", LevelProfile: "na",
				Summary: "Open a vault (North-America level 3)"},
			{Method: "POST", Path: "/t/{tenant}/orders", Capability: "orders:place", Class: allowedby.Write,
				Level: 1, Resource: "tenant:{tenant}:order:new", AmountField: "/total", Summary: "Place an order"},
		},
		Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes"),
			"drafts:write": allowedby.Text("Save your drafts"), "vault:read": allowedby.Text("Open {scope}"),
			"orders:place": allowedby.Text("Place orders on {scope}")},
		Rate: map[string]allowedby.RateLimit{"actor": {Calls: 20, Per: time.Minute},
			"operator": {Calls: 1000, Per: time.Minute}},
		Title:           "Notes Interop API",
		RefreshInterval: refresh,
		Nonce:           true,
		Tenants:         tenants(),
	})
	if err != nil {
		log.Fatal(err)
	}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /interop/link-code", func(w http.ResponseWriter, r *http.Request) { // TEST ONLY
		var in struct {
			Account string `json:"account"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Account == "" {
			reply(w, http.StatusBadRequest, map[string]string{"error": "account"})
			return
		}
		code, err := aby.LinkStart(in.Account, 0) // the account page of the signed-in account in.Account
		if err != nil {
			reply(w, http.StatusServiceUnavailable, map[string]string{"error": "no code"})
			return
		}
		reply(w, http.StatusOK, map[string]string{"code": code})
	})
	mux.HandleFunc("POST /interop/unlink", func(w http.ResponseWriter, r *http.Request) { // TEST ONLY
		var in struct {
			Account string `json:"account"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			reply(w, http.StatusBadRequest, map[string]string{"error": "account"})
			return
		}
		was, err := aby.Unlink(in.Account) // the account page removes the link of in.Account
		if err != nil {
			reply(w, http.StatusBadRequest, map[string]string{"error": "account"})
			return
		}
		reply(w, http.StatusOK, map[string]bool{"was_linked": was})
	})
	mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		reply(w, http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level})
	})
	mux.HandleFunc("GET /accounts/{account}/notes", func(w http.ResponseWriter, r *http.Request) {
		who, ok := allowedby.ContextFrom(r.Context())
		if !ok {
			reply(w, http.StatusNotFound, map[string]string{"error": "not found"})
			return
		}
		// the SDK checked that the person is linked to this account
		reply(w, http.StatusOK, map[string]any{"account": who.Params["account"], "notes": []string{}})
	})
	mux.HandleFunc("POST /drafts", func(w http.ResponseWriter, _ *http.Request) {
		reply(w, http.StatusOK, map[string]bool{"saved": true}) // the SDK checked the nonce
	})
	vault := func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		reply(w, http.StatusOK, map[string]string{"vault": who.Params["id"]})
	}
	mux.HandleFunc("GET /vault/eu/{id}", vault)
	mux.HandleFunc("GET /vault/na/{id}", func(w http.ResponseWriter, r *http.Request) { vault(w, r) })
	mux.HandleFunc("POST /t/{tenant}/orders", func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context())
		var in struct {
			Total string `json:"total"`
		}
		_ = json.NewDecoder(r.Body).Decode(&in) // the SDK checked the amount against the approval and the tenant
		reply(w, http.StatusOK, map[string]string{"ordered": in.Total, "account": who.Tenant})
	})
	mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
		reply(w, http.StatusNotFound, map[string]string{"error": "not found"})
	})
	addr := net.JoinHostPort(cmp.Or(os.Getenv("ALLOWEDBY_BIND"), "127.0.0.1"), cmp.Or(os.Getenv("PORT"), "18790"))
	srv := &http.Server{Addr: addr, Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

// tenants are the accounts of the orders route: umbrella as the map says, hooli with a ceiling of 50.00 a call,
// budget with 100.00 EUR a day in all (ORG-1 §3.3, §5.3).
func tenants() map[string]allowedby.Tenant {
	t := map[string]allowedby.Tenant{}
	t["umbrella"] = allowedby.Tenant{Name: "Umbrella"}
	t["hooli"] = allowedby.Tenant{Name: "Hooli",
		Routes: map[string]allowedby.TenantRoute{"orders:place": {AmountMax: "50.00"}}}
	t["budget"] = allowedby.Tenant{Name: "Budget Co",
		Budgets: map[string]allowedby.Budget{"orders:place": {Max: "100.00", Currency: "EUR", Per: "day"}}}
	return t
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}