busweb: web UIs over the YAPL bus; httpsec.BearerTokens
busweb.Serve runs a <name>.web@N request (verse/web, D-200) against a UI's http.Handler; Prefix/User/FromBus tell the handler where it is mounted and who yasta says is logged in; WithPrefix serves the same handler on a TCP port. httpsec.BearerTokens is the access control of a UI without user management (a reverse proxy or yasta sends the token). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fb2cb7bcfa
commit
7afb6a022a
7 files changed
+365
No files matched your search
@@ -175,6 +175,41 @@ the standard library, wrapped inside `Headers`.
|
||||
Order: `Headers(Gate(cop.Handler(app)))` -- the headers also reach a 421
|
||||
or 403.
|
||||
|
||||
- `BearerTokens(h, tokens)` (v0.4.0) -- for a UI without user
|
||||
management of its own: only requests with `Authorization: Bearer <one
|
||||
of tokens>` pass (constant-time compare), others get 401. A reverse
|
||||
proxy in front sets the header (Traefik `headers.customRequestHeaders`),
|
||||
or yasta for a UI shown over the bus. No tokens: everything passes --
|
||||
bind such a UI to loopback only.
|
||||
|
||||
## Web UI over the YAPL bus: package `busweb` (v0.4.0)
|
||||
|
||||
`teruna.dev/yetano/yetano-webui-template/busweb` (meta-repo
|
||||
`docs/verse/protocols.md` §18, D-200; types in `yetano.dev/yetano/verse/web`).
|
||||
A YAPL participant provides `<name>.web@1`; yasta mounts its UI at
|
||||
`/apps/<service>/` of yasta's web UI and sends each HTTP request as one
|
||||
call. The same `http.Handler` serves both ways:
|
||||
|
||||
```go
|
||||
app := myUI() // links/redirects use busweb.Prefix(r)
|
||||
// over the bus: in the capability handler
|
||||
resp := busweb.Serve(ctx, httpsec.BearerTokens(app, tokens), req) // req web.Request
|
||||
// on a TCP port (optional), e.g. behind Traefik
|
||||
h := busweb.WithPrefix(app, basePath)
|
||||
h = httpsec.BearerTokens(h, tokens)
|
||||
h = httpsec.Headers(httpsec.Gate(http.NewCrossOriginProtection().Handler(h), hosts, "web.allowed_hosts"), httpsec.HeaderOptions{})
|
||||
```
|
||||
|
||||
- `Prefix(r)` -- where the UI is mounted; set `PageHeader.BasePath` to it
|
||||
per request (it differs between the bus, the TCP port and yasta's web
|
||||
relay).
|
||||
- `User(r)` -- the yasta web user for a request over the bus (yasta's
|
||||
claim; require yasta's token if other participants may call the
|
||||
capability), `FromBus(r)`.
|
||||
- `Serve` hands the handler the path below the prefix with `RequestURI`
|
||||
as the browser sent it (so `ApplyAppearance` works), keeps only the
|
||||
allowed response headers and cuts bodies over 512 KiB.
|
||||
|
||||
## Migration status
|
||||
|
||||
Eight projects use it, all on `v0.3.0` (2026-10-31): the built-in theme
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// Package busweb serves a web UI over the YAPL bus (meta-repository
|
||||
// docs/verse/protocols.md §18, D-200): yasta mounts a participant's UI in
|
||||
// its own web UI and sends each HTTP request as one call of the
|
||||
// participant's "<name>.web@N" capability. Serve runs such a request
|
||||
// against the UI's ordinary http.Handler, so the same handler can also
|
||||
// listen on a TCP port (behind a reverse proxy, see httpsec.BearerTokens).
|
||||
//
|
||||
// The handler learns where it is mounted from Prefix(r) -- it writes its
|
||||
// links and redirects with it, as with a layout.PageHeader BasePath --
|
||||
// and, over the bus, the web user yasta reports from User(r).
|
||||
package busweb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/verse/web"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
keyPrefix ctxKey = iota
|
||||
keyUser
|
||||
keyBus
|
||||
)
|
||||
|
||||
// Prefix is where the UI serving r is mounted ("" at the root), set by
|
||||
// Serve or WithPrefix.
|
||||
func Prefix(r *http.Request) string {
|
||||
p, _ := r.Context().Value(keyPrefix).(string)
|
||||
return p
|
||||
}
|
||||
|
||||
// User is the logged-in user of yasta's web UI for a request that came
|
||||
// over the bus ("" otherwise, or when yasta's login is off). It is yasta's
|
||||
// claim: trust it as far as yasta's "calls" gate for the capability (or
|
||||
// require yasta's bearer token).
|
||||
func User(r *http.Request) string {
|
||||
u, _ := r.Context().Value(keyUser).(string)
|
||||
return u
|
||||
}
|
||||
|
||||
// FromBus reports whether r came over the bus (Serve).
|
||||
func FromBus(r *http.Request) bool {
|
||||
b, _ := r.Context().Value(keyBus).(bool)
|
||||
return b
|
||||
}
|
||||
|
||||
// WithPrefix serves next below prefix ("" or "/..." without trailing
|
||||
// slash) on a TCP listener: it strips the prefix and records it for
|
||||
// Prefix. Requests outside it get 404.
|
||||
func WithPrefix(next http.Handler, prefix string) http.Handler {
|
||||
prefix = strings.TrimSuffix(prefix, "/")
|
||||
set := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), keyPrefix, prefix)))
|
||||
})
|
||||
if prefix == "" {
|
||||
return set
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle(prefix+"/", http.StripPrefix(prefix, set))
|
||||
mux.Handle(prefix, http.RedirectHandler(prefix+"/", http.StatusMovedPermanently))
|
||||
return mux
|
||||
}
|
||||
|
||||
// Serve runs req against h and returns its response. An invalid request
|
||||
// gets 400. The handler sees the path below the prefix (as after
|
||||
// http.StripPrefix), RequestURI as the browser sent it, Host "yapl" and
|
||||
// RemoteAddr "yapl"; headers outside web.ResponseHeaders are dropped and
|
||||
// a body over web.MaxResponseBody is cut (Truncated).
|
||||
func Serve(ctx context.Context, h http.Handler, req web.Request) web.Response {
|
||||
if err := req.Validate(); err != nil {
|
||||
return text(http.StatusBadRequest, err.Error())
|
||||
}
|
||||
u, err := url.ParseRequestURI(req.URL)
|
||||
if err != nil {
|
||||
return text(http.StatusBadRequest, "bad url")
|
||||
}
|
||||
ctx = context.WithValue(ctx, keyPrefix, req.Prefix)
|
||||
ctx = context.WithValue(ctx, keyUser, req.User)
|
||||
ctx = context.WithValue(ctx, keyBus, true)
|
||||
r, err := http.NewRequestWithContext(ctx, req.Method, req.URL, bytes.NewReader(req.Body))
|
||||
if err != nil {
|
||||
return text(http.StatusBadRequest, "bad request")
|
||||
}
|
||||
r.URL = u
|
||||
r.RequestURI = req.Prefix + req.URL
|
||||
r.Host = "yapl"
|
||||
r.RemoteAddr = "yapl"
|
||||
r.ContentLength = int64(len(req.Body))
|
||||
for k, vs := range req.Header {
|
||||
for _, v := range vs {
|
||||
r.Header.Add(k, v)
|
||||
}
|
||||
}
|
||||
rec := &recorder{header: http.Header{}}
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.status == 0 {
|
||||
rec.status = http.StatusOK
|
||||
}
|
||||
resp := web.Response{Status: rec.status, Header: web.FilterHeader(rec.header, web.ResponseHeaders),
|
||||
Truncated: rec.truncated}
|
||||
if req.Method != http.MethodHead {
|
||||
resp.Body = rec.body.Bytes()
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func text(status int, msg string) web.Response {
|
||||
return web.Response{Status: status, Header: map[string][]string{"Content-Type": {"text/plain; charset=utf-8"}},
|
||||
Body: []byte(msg + "\n")}
|
||||
}
|
||||
|
||||
// recorder is an http.ResponseWriter that keeps at most
|
||||
// web.MaxResponseBody bytes.
|
||||
type recorder struct {
|
||||
header http.Header
|
||||
status int
|
||||
body bytes.Buffer
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (r *recorder) Header() http.Header { return r.header }
|
||||
|
||||
func (r *recorder) WriteHeader(code int) {
|
||||
if r.status == 0 {
|
||||
r.status = code
|
||||
}
|
||||
}
|
||||
|
||||
func (r *recorder) Write(b []byte) (int, error) {
|
||||
r.WriteHeader(http.StatusOK)
|
||||
room := web.MaxResponseBody - r.body.Len()
|
||||
if len(b) > room {
|
||||
r.body.Write(b[:max(room, 0)])
|
||||
r.truncated = true
|
||||
return len(b), nil
|
||||
}
|
||||
return r.body.Write(b)
|
||||
}
|
||||
|
||||
// Flush is a no-op: the response leaves as one message.
|
||||
func (r *recorder) Flush() {}
|
||||
@@ -0,0 +1,104 @@
|
||||
package busweb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
layout "teruna.dev/yetano/yetano-webui-template"
|
||||
"yetano.dev/yetano/verse/web"
|
||||
)
|
||||
|
||||
func echo() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Header().Set("Server", "secret")
|
||||
w.Header().Set("Set-Cookie", "a=b")
|
||||
io.WriteString(w, "prefix="+Prefix(r)+" user="+User(r)+" path="+r.URL.Path+" q="+r.URL.Query().Get("q")+" ua="+r.UserAgent())
|
||||
})
|
||||
mux.HandleFunc("POST /form", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, Prefix(r)+"/hello?q="+r.FormValue("v"), http.StatusSeeOther)
|
||||
})
|
||||
mux.HandleFunc("GET /big", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(make([]byte, web.MaxResponseBody+10))
|
||||
})
|
||||
mux.HandleFunc("GET /appearance-back", func(w http.ResponseWriter, r *http.Request) {
|
||||
h := layout.PageHeader{BasePath: Prefix(r)}
|
||||
h.ApplyAppearance(r)
|
||||
io.WriteString(w, h.AppearanceBack)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
func TestServe(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/hello?q=1", Prefix: "/apps/x",
|
||||
User: "alice", Header: map[string][]string{"User-Agent": {"t"}}})
|
||||
if resp.Status != 200 || string(resp.Body) != "prefix=/apps/x user=alice path=/hello q=1 ua=t" {
|
||||
t.Fatalf("%d %q", resp.Status, resp.Body)
|
||||
}
|
||||
if resp.Header["Server"] != nil || resp.Header["Set-Cookie"][0] != "a=b" {
|
||||
t.Fatalf("headers %v", resp.Header)
|
||||
}
|
||||
if err := resp.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServePostRedirect(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "POST", URL: "/form", Prefix: "/p",
|
||||
Header: map[string][]string{"Content-Type": {"application/x-www-form-urlencoded"}}, Body: []byte("v=7")})
|
||||
if resp.Status != http.StatusSeeOther || resp.Header["Location"][0] != "/p/hello?q=7" {
|
||||
t.Fatalf("%d %v", resp.Status, resp.Header)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeTruncatesAndRejects(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/big"})
|
||||
if !resp.Truncated || len(resp.Body) != web.MaxResponseBody {
|
||||
t.Fatalf("truncated %v len %d", resp.Truncated, len(resp.Body))
|
||||
}
|
||||
if resp := Serve(context.Background(), echo(), web.Request{Method: "PUT", URL: "/hello"}); resp.Status != 400 {
|
||||
t.Fatalf("PUT: %d", resp.Status)
|
||||
}
|
||||
if resp := Serve(context.Background(), echo(), web.Request{Method: "HEAD", URL: "/hello"}); resp.Status != 405 && len(resp.Body) != 0 {
|
||||
t.Fatalf("HEAD body: %q", resp.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// The layout's appearance menu returns to the page below the prefix, not
|
||||
// to the prefix stripped twice.
|
||||
func TestServeAppearanceBack(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/appearance-back?x=1", Prefix: "/appearance-back"})
|
||||
if string(resp.Body) != "/appearance-back?x=1" {
|
||||
t.Fatalf("%q", resp.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithPrefix(t *testing.T) {
|
||||
srv := httptest.NewServer(WithPrefix(echo(), "/ui/"))
|
||||
defer srv.Close()
|
||||
res, err := http.Get(srv.URL + "/ui/hello?q=2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if !strings.HasPrefix(string(b), "prefix=/ui user= path=/hello q=2") {
|
||||
t.Fatalf("%q", b)
|
||||
}
|
||||
if res, _ := http.Get(srv.URL + "/hello"); res.StatusCode != 404 {
|
||||
t.Fatalf("outside prefix: %d", res.StatusCode)
|
||||
}
|
||||
root := httptest.NewServer(WithPrefix(echo(), ""))
|
||||
defer root.Close()
|
||||
res, _ = http.Get(root.URL + "/hello")
|
||||
b, _ = io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if !strings.HasPrefix(string(b), "prefix= user= path=/hello") {
|
||||
t.Fatalf("root: %q", b)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,10 @@
|
||||
module teruna.dev/yetano/yetano-webui-template
|
||||
|
||||
go 1.26.3
|
||||
|
||||
require yetano.dev/yetano/verse v0.10.0
|
||||
|
||||
require (
|
||||
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
|
||||
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
yetano.dev/yetano/verse v0.10.0 h1:NP7drY+nGW7R59CtDp30k0m+lvYj18GzyQ89oZ7LBVE=
|
||||
yetano.dev/yetano/verse v0.10.0/go.mod h1:TzVydtH9ljDTzhD98uufRW8V2OZECktqIcPxiaWH6p4=
|
||||
@@ -6,6 +6,7 @@
|
||||
package httpsec
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -174,3 +175,42 @@ func CookiePath(basePath string) string {
|
||||
func SecureCookies(r *http.Request, publicURL string) bool {
|
||||
return r.TLS != nil || strings.HasPrefix(strings.ToLower(publicURL), "https://")
|
||||
}
|
||||
|
||||
// BearerTokens lets a request through only when it carries
|
||||
// "Authorization: Bearer <token>" with one of tokens (compared in
|
||||
// constant time); others get 401. It is the access control of a UI
|
||||
// without user management of its own: a reverse proxy in front of it
|
||||
// (or yasta, for a UI shown over the YAPL bus) sets the header. Empty
|
||||
// tokens are ignored; with none left every request passes.
|
||||
func BearerTokens(next http.Handler, tokens []string) http.Handler {
|
||||
var keep [][]byte
|
||||
for _, t := range tokens {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
keep = append(keep, []byte(t))
|
||||
}
|
||||
}
|
||||
if len(keep) == 0 {
|
||||
return next
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if tokenAllowed(r.Header.Get("Authorization"), keep) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="web UI"`)
|
||||
http.Error(w, "missing or wrong bearer token", http.StatusUnauthorized)
|
||||
})
|
||||
}
|
||||
|
||||
func tokenAllowed(header string, tokens [][]byte) bool {
|
||||
scheme, got, ok := strings.Cut(header, " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return false
|
||||
}
|
||||
g := []byte(strings.TrimSpace(got))
|
||||
match := 0
|
||||
for _, t := range tokens {
|
||||
match |= subtle.ConstantTimeCompare(g, t)
|
||||
}
|
||||
return match == 1
|
||||
}
|
||||
@@ -132,3 +132,29 @@ func TestSecureCookies(t *testing.T) {
|
||||
t.Fatal("TLS")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokens(t *testing.T) {
|
||||
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
|
||||
h := BearerTokens(ok, []string{" one ", "", "two"})
|
||||
for auth, want := range map[string]int{
|
||||
"": 401, "Bearer one": 204, "bearer two": 204, "Bearer three": 401, "Basic one": 401, "Bearer": 401, "Bearer onex": 401,
|
||||
} {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
if auth != "" {
|
||||
r.Header.Set("Authorization", auth)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Errorf("%q: %d, want %d", auth, w.Code, want)
|
||||
}
|
||||
if want == 401 && w.Header().Get("WWW-Authenticate") == "" {
|
||||
t.Errorf("%q: no WWW-Authenticate", auth)
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
BearerTokens(ok, []string{" ", ""}).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
||||
if w.Code != 204 {
|
||||
t.Errorf("no tokens: %d", w.Code)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user