Add the route package: plugin routes declare their access

Routes under /api/plugins/<name> take Public, Visitor or Admin. Visitor and
Admin routes check the host-verified identity; a public POST goes through
Form, which requires the host-verified captcha and a per-instance submission
limit. CaptchaWidget returns the CMS widget markup for Go-rendered forms.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Alex Dunmow 2026-11-20 05:52:55 +08:00
parent 4970bf4fa1
commit 754a713b0e
3 changed files with 333 additions and 0 deletions

View File

@ -0,0 +1,48 @@
# Plugin routes declare their access
Website factory plugins are written by a model and reach customer sites with
automatic checks as the only gate (orchestrator ADR 0064, ADR 0085). In the
WO-088 live runs a generated plugin served stored quote requests (names,
emails, phones, addresses) from a plain `http.ServeMux` route with no
authentication, and its public form accepted any POST with no captcha. The
SDK gave a plugin no way to say who a route is for, so check-safety had
nothing to require.
Decision: the new `route` package serves a plugin's HTTP routes under
`/api/plugins/<name>` with an access level on every route.
- `route.New(pluginName)` returns an `http.Handler` for `Registration.HTTPHandler`.
- `Handle(method, path, access, h)` takes `route.Public`, `route.Visitor` or
`route.Admin`. Visitor and Admin routes rebuild the caller from the host's
trusted identity headers and answer 401 or 403 before the handler runs;
Admin needs the `admin` or `superadmin` role. A Public route may only be
GET or HEAD; any other public method panics at registration.
- `Form(path, h)` is the one way to serve a public POST. It answers 403 unless
the host verified the request's captcha (`auth.CaptchaVerified`), 429 past
`FormBurst` submissions at once and `FormsPerMinute` after that per plugin
instance, and caps the body at `MaxFormBytes`.
- `CaptchaWidget()` returns the CMS captcha widget markup, so a Go-rendered
block can put it inside its form.
check-safety requires this package for factory-generated plugins and warns on
hand-built routers in first-party plugins.
Rejected: a host-side access declaration in the manifest. It would need an ABI
change and a CMS release for every route shape, and the guest still has to
check identity because context does not cross the ABI. The submission limit
lives in the guest because the host has no per-route limiter for plugin
routes; it counts per wasm instance, so the real ceiling is the pool size times
the limit. A per-client limit needs a host-verified client address and is
recorded as a remaining gap in orchestrator ADR 0085.
Consequences:
- Released in v0.3.12. The plugin builder image, its module cache and the
factory prompt bundle move to v0.3.12 together.
- Generated plugins get a 401, 403, 405 or 429 from the router itself, which
the runtime acceptance harness checks route by route.
Keywords: route, route.New, route.Handle, route.Form, route.Public,
route.Visitor, route.Admin, CaptchaWidget, FormsPerMinute, FormBurst,
MaxFormBytes, access level, plugin HTTP routes, captcha, rate limit, public
form, WO-097, website factory, generated plugin

187
route/route.go Normal file
View File

@ -0,0 +1,187 @@
// Package route serves a plugin's HTTP routes under /api/plugins/<name> with
// an access level declared for every route. Admin and Visitor routes answer
// only callers the host verified; a public POST goes through Form, which
// requires the host-verified captcha and caps how many submissions a plugin
// instance accepts per minute.
package route
import (
"fmt"
"net/http"
"strings"
"sync"
"time"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
)
// Access is who may call a route.
type Access int
const (
// Public routes answer anyone. Use them for data a visitor may read.
Public Access = iota + 1
// Visitor routes answer a signed-in site visitor (public user session).
Visitor
// Admin routes answer a signed-in CMS admin or superadmin.
Admin
)
func (a Access) String() string {
switch a {
case Public:
return "public"
case Visitor:
return "visitor"
case Admin:
return "admin"
}
return fmt.Sprintf("Access(%d)", int(a))
}
// Form limits: each plugin instance accepts FormBurst submissions at once and
// FormsPerMinute after that, across all of its Form routes.
const (
FormBurst = 10
FormsPerMinute = 30
MaxFormBytes = 64 << 10
)
// Router is an http.Handler for one plugin's routes.
type Router struct {
prefix string
mux *http.ServeMux
forms *limiter
routes []Route
}
// CaptchaWidget is the host's proof-of-work captcha widget. Put it inside a
// form that posts to a Form route: the visitor's browser solves it and the
// form submits a cap-token field, which the host verifies before the plugin
// sees the request. The markup matches the CMS captcha widget, served from the
// site's own origin.
func CaptchaWidget() string { return captchaWidgetHTML }
const captchaWidgetHTML = `<script>
window.CAP_CUSTOM_WASM_URL = "/assets/captcha/cap_wasm_bg.wasm";
window.CAP_PAKO_URL = "/assets/captcha/pako_inflate.min.js";
</script><cap-widget data-cap-api-endpoint="/api/captcha/" data-cap-worker-count="2"></cap-widget><script src="/assets/captcha/cap.min.js" defer></script>`
// Route is one registered route, for tests and host checks.
type Route struct {
Method string
Path string
Access Access
}
// New returns a Router for the plugin named pluginName.
func New(pluginName string) *Router {
return &Router{
prefix: "/api/plugins/" + pluginName,
mux: http.NewServeMux(),
forms: newLimiter(FormBurst, FormsPerMinute, time.Now),
}
}
// Handle serves method on path (below the plugin's address, starting with a
// slash) for callers that access allows. A Public route may only read: GET or
// HEAD. A public POST must use Form. Invalid registrations panic, like
// http.ServeMux does for conflicting patterns.
func (r *Router) Handle(method, path string, access Access, h http.HandlerFunc) {
method = strings.ToUpper(method)
if access == Public && method != http.MethodGet && method != http.MethodHead {
panic(fmt.Sprintf("route: public %s %s must use Form", method, path))
}
r.handle(method, path, access, guard(access, h))
}
// Form serves a public POST on path. The host must have verified the
// request's captcha (render the widget with the ninjatpl captcha tag so the
// form posts a cap-token); a request without it gets 403, and a request past
// the submission limit gets 429. The body is capped at MaxFormBytes.
func (r *Router) Form(path string, h http.HandlerFunc) {
r.handle(http.MethodPost, path, Public, func(w http.ResponseWriter, req *http.Request) {
if !auth.CaptchaVerified(req.Header) {
http.Error(w, "please complete the captcha", http.StatusForbidden)
return
}
if !r.forms.allow() {
http.Error(w, "too many submissions, please try again in a minute", http.StatusTooManyRequests)
return
}
req.Body = http.MaxBytesReader(w, req.Body, MaxFormBytes)
h(w, req)
})
}
// Routes lists the registered routes in registration order.
func (r *Router) Routes() []Route { return append([]Route(nil), r.routes...) }
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.mux.ServeHTTP(w, req)
}
func (r *Router) handle(method, path string, access Access, h http.HandlerFunc) {
if access < Public || access > Admin {
panic(fmt.Sprintf("route: %s %s has no access level", method, path))
}
if !strings.HasPrefix(path, "/") {
panic(fmt.Sprintf("route: path %q must start with a slash", path))
}
pattern := r.prefix + path
if path == "/" {
pattern += "{$}"
}
r.mux.HandleFunc(method+" "+pattern, h)
r.routes = append(r.routes, Route{Method: method, Path: path, Access: access})
}
func guard(access Access, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
ctx := auth.ContextFromTrustedHeaders(req.Context(), req.Header)
switch access {
case Admin:
user, ok := auth.GetUserFromContext(ctx)
if !ok {
http.Error(w, "sign in required", http.StatusUnauthorized)
return
}
if user.Role != "admin" && user.Role != "superadmin" {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
case Visitor:
if _, ok := auth.GetPublicUserFromContext(ctx); !ok {
http.Error(w, "sign in required", http.StatusUnauthorized)
return
}
}
h(w, req.WithContext(ctx))
}
}
type limiter struct {
mu sync.Mutex
tokens float64
burst float64
perSec float64
last time.Time
clockNow func() time.Time
}
func newLimiter(burst, perMinute int, now func() time.Time) *limiter {
return &limiter{tokens: float64(burst), burst: float64(burst), perSec: float64(perMinute) / 60, last: now(), clockNow: now}
}
func (l *limiter) allow() bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clockNow()
l.tokens = min(l.burst, l.tokens+now.Sub(l.last).Seconds()*l.perSec)
l.last = now
if l.tokens < 1 {
return false
}
l.tokens--
return true
}

98
route/route_test.go Normal file
View File

@ -0,0 +1,98 @@
package route
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
)
func serve(r http.Handler, method, path string, headers map[string]string) int {
req := httptest.NewRequest(method, path, strings.NewReader("name=a"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec.Code
}
func ok(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }
func TestAccessLevels(t *testing.T) {
r := New("demo")
r.Handle("GET", "/", Public, ok)
r.Handle("GET", "/mine", Visitor, ok)
r.Handle("GET", "/requests", Admin, ok)
r.Form("/submit", ok)
admin := map[string]string{auth.HeaderVerifiedUserID: "7b0d9a8e-1d0b-4c1b-9a35-0d6f7f3c2a11", auth.HeaderVerifiedRole: "admin"}
viewer := map[string]string{auth.HeaderVerifiedUserID: "7b0d9a8e-1d0b-4c1b-9a35-0d6f7f3c2a11", auth.HeaderVerifiedRole: "viewer"}
visitor := map[string]string{auth.HeaderVerifiedPublicUserID: "7b0d9a8e-1d0b-4c1b-9a35-0d6f7f3c2a11"}
captcha := map[string]string{auth.HeaderVerifiedCaptcha: "1"}
cases := []struct {
method, path string
headers map[string]string
want int
}{
{"GET", "/api/plugins/demo/", nil, 200},
{"GET", "/api/plugins/demo/other", nil, 404},
{"GET", "/api/plugins/demo/mine", nil, 401},
{"GET", "/api/plugins/demo/mine", visitor, 200},
{"GET", "/api/plugins/demo/requests", nil, 401},
{"GET", "/api/plugins/demo/requests", visitor, 401},
{"GET", "/api/plugins/demo/requests", viewer, 403},
{"GET", "/api/plugins/demo/requests", admin, 200},
{"POST", "/api/plugins/demo/submit", nil, 403},
{"POST", "/api/plugins/demo/submit", captcha, 200},
{"GET", "/api/plugins/demo/submit", captcha, 405},
}
for _, c := range cases {
if got := serve(r, c.method, c.path, c.headers); got != c.want {
t.Errorf("%s %s %v = %d, want %d", c.method, c.path, c.headers, got, c.want)
}
}
if got := len(r.Routes()); got != 4 {
t.Errorf("Routes() has %d entries, want 4", got)
}
}
func TestPublicWritesMustUseForm(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("a public POST registered with Handle did not panic")
}
}()
New("demo").Handle("POST", "/submit", Public, ok)
}
func TestMissingAccessPanics(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("a route with no access level did not panic")
}
}()
New("demo").Handle("GET", "/x", 0, ok)
}
func TestFormLimit(t *testing.T) {
now := time.Unix(0, 0)
l := newLimiter(FormBurst, FormsPerMinute, func() time.Time { return now })
for i := range FormBurst {
if !l.allow() {
t.Fatalf("submission %d refused inside the burst", i)
}
}
if l.allow() {
t.Fatal("submission past the burst was allowed")
}
now = now.Add(2 * time.Second)
if !l.allow() {
t.Fatal("a submission two seconds later was refused")
}
}