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:
terminarandClaude Opus 5.5 committed 2026-11-04 13:27:48 +01:00
1 parent fb2cb7bcfa
commit 7afb6a022a
7 files changed
+365

No files matched your search

+147
View File
@@ -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() {}
+104
View File
@@ -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)
}
}