Compare commits

..
4 Commits
Author SHA1 Message Date
terminarandClaude Opus 5.5 7afb6a022a 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>
2026-11-04 13:27:48 +01:00
terminarandClaude Opus 5.5 fb2cb7bcfa License: proprietary (LicenseRef-Proprietary)
Owner decision 2026-11-01: all own Yetano code is proprietary. LICENSE
carries the notice, the README says so, and the Yetanofile declares
LicenseRef-Proprietary. Bundled third-party files keep their licenses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:43:34 +01:00
terminarandClaude Opus 5.5 28db4f707f ApplyAppearance: keep a path StripPrefix already made relative
Behind http.StripPrefix the request path is relative to the base path,
so for base path /feeds the page /feeds was cut to / again. A path that
no longer matches RequestURI's is now taken as already stripped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:32:24 +01:00
terminarandClaude Opus 5.5 0f9b40df9f README: every consumer is on v0.3.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:11:21 +01:00
11 changed files with 449 additions and 8 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
This software and its documentation are proprietary
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
publish, distribute, sublicense or sell copies of this software, in whole
or in part, is granted without the prior written permission of the
copyright holder.
Third-party components bundled in this repository keep their own licenses; see NOTICE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+10
View File
@@ -0,0 +1,10 @@
yetano-webui-template
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
yetano-webui-template itself is proprietary, see LICENSE.
This repository bundles the following third-party files, which keep
their own licenses:
- Bootstrap v5.3.3 (https://getbootstrap.com/): static/bootstrap.min.css,
static/bootstrap.bundle.min.js -- MIT, Copyright 2011-2024 The
Bootstrap Authors (https://github.com/twbs/bootstrap/blob/main/LICENSE).
+46 -3
View File
@@ -98,7 +98,11 @@ the cookies `yw_theme`/`yw_palette` (path `BasePath/`, a year,
`HttpOnly`, `SameSite=Lax`) and redirects to `back`, but only to a path `HttpOnly`, `SameSite=Lax`) and redirects to `back`, but only to a path
inside the UI. Any other method gets 405. `ApplyAppearance` ignores inside the UI. Any other method gets 405. `ApplyAppearance` ignores
unknown cookie values, so whatever the consumer set before stays the unknown cookie values, so whatever the consumer set before stays the
default. A consumer whose middleware wants a CSRF token on every POST default. It works with and without `http.StripPrefix` in front of the
UI: a path that differs from the request's `RequestURI` is taken as
already relative and kept as it is (v0.3.1; up to v0.3.0 the page
`/feeds` behind StripPrefix with base path `/feeds` was wrongly cut to
`/`). A consumer whose middleware wants a CSRF token on every POST
puts the hidden field into `AppearanceFormHTML`, which is rendered puts the hidden field into `AppearanceFormHTML`, which is rendered
inside the menu's form. A consumer with its own switch can keep it and inside the menu's form. A consumer with its own switch can keep it and
just set `Theme`/`Palette` (none does today). just set `Theme`/`Palette` (none does today).
@@ -171,10 +175,45 @@ the standard library, wrapped inside `Headers`.
Order: `Headers(Gate(cop.Handler(app)))` -- the headers also reach a 421 Order: `Headers(Gate(cop.Handler(app)))` -- the headers also reach a 421
or 403. 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 ## Migration status
Eight projects use it, all on `v0.2.5` and all with the built-in theme Eight projects use it, all on `v0.3.0` (2026-10-31): the built-in theme
menu (2026-10-30). menu, `httpsec` and the flash helpers.
| Project | Meta-repo | Status | | Project | Meta-repo | Status |
|---|---|---| |---|---|---|
@@ -234,3 +273,7 @@ framework state (e.g. yakwui's Alpine.js collapsible sidebar). A page
without a sidebar (a login page) sets `BodyAttrs` to without a sidebar (a login page) sets `BodyAttrs` to
`` ` class="no-sidebar"` ``: since v0.2.5 `static/style.css` then hides `` ` class="no-sidebar"` ``: since v0.2.5 `static/style.css` then hides
the sidebar column and gives `<main>` the full width. the sidebar column and gives `<main>` the full width.
## License
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE). Third-party components bundled in this repository keep their own licenses; see [NOTICE](NOTICE).
+21 -4
View File
@@ -69,11 +69,9 @@ func (h *PageHeader) ApplyAppearance(r *http.Request) {
if c, err := r.Cookie(PaletteCookie); err == nil && known(Palettes, c.Value) { if c, err := r.Cookie(PaletteCookie); err == nil && known(Palettes, c.Value) {
h.Palette = c.Value h.Palette = c.Value
} }
// Only a whole leading BasePath segment is cut: behind
// http.StripPrefix the path is already relative, and "/r" must not
// eat the start of "/release-notes".
path := r.URL.Path path := r.URL.Path
if h.BasePath != "" && (path == h.BasePath || strings.HasPrefix(path, h.BasePath+"/")) { if h.BasePath != "" && !strippedPath(r) &&
(path == h.BasePath || strings.HasPrefix(path, h.BasePath+"/")) {
path = strings.TrimPrefix(path, h.BasePath) path = strings.TrimPrefix(path, h.BasePath)
} }
if path == "" { if path == "" {
@@ -83,6 +81,25 @@ func (h *PageHeader) ApplyAppearance(r *http.Request) {
h.AppearanceBack = WithoutFlash(back.String()) h.AppearanceBack = WithoutFlash(back.String())
} }
// strippedPath reports whether r.URL.Path is already relative to the
// UI's base path, i.e. a handler such as http.StripPrefix cut it down
// from what the client asked for. Those keep RequestURI as sent, so a
// path that no longer matches RequestURI's was stripped -- and must not
// be stripped again: for base path "/feeds" the relative page "/feeds"
// is a page of its own, not the start page. Without a RequestURI (a
// request built in code) only a whole leading BasePath segment is cut,
// so "/r" never eats the start of "/release-notes".
func strippedPath(r *http.Request) bool {
if r.RequestURI == "" {
return false
}
u, err := url.ParseRequestURI(r.RequestURI)
if err != nil {
return false
}
return u.Path != r.URL.Path
}
// AppearanceHandler stores a theme and/or palette choice from a POST // AppearanceHandler stores a theme and/or palette choice from a POST
// form (fields "theme", "palette", "back") in cookies and redirects to // form (fields "theme", "palette", "back") in cookies and redirects to
// back, a BasePath-relative path inside this UI (anything else goes to // back, a BasePath-relative path inside this UI (anything else goes to
+25 -1
View File
@@ -143,7 +143,7 @@ func TestApplyAppearance(t *testing.T) {
t.Errorf("AppearanceBack = %q, want %q", h.AppearanceBack, "/tasks?f=1") t.Errorf("AppearanceBack = %q, want %q", h.AppearanceBack, "/tasks?f=1")
} }
// Behind http.StripPrefix the path is already relative to BasePath. // Without StripPrefix only a whole leading BasePath segment is cut.
for path, want := range map[string]string{"/release-notes": "/release-notes", "/r": "/", "/r/x": "/x"} { for path, want := range map[string]string{"/release-notes": "/release-notes", "/r": "/", "/r/x": "/x"} {
h := PageHeader{BasePath: "/r"} h := PageHeader{BasePath: "/r"}
h.ApplyAppearance(httptest.NewRequest(http.MethodGet, path, nil)) h.ApplyAppearance(httptest.NewRequest(http.MethodGet, path, nil))
@@ -153,6 +153,30 @@ func TestApplyAppearance(t *testing.T) {
} }
} }
// Behind http.StripPrefix the path is already relative to BasePath and
// must stay as it is, even when it looks like the base path itself.
func TestApplyAppearanceBehindStripPrefix(t *testing.T) {
cases := []struct{ base, request, want string }{
{"/feeds", "/feeds/feeds", "/feeds"},
{"/feeds", "/feeds/feeds/x?a=1", "/feeds/x?a=1"},
{"/feeds", "/feeds/", "/"},
{"/feeds", "/feeds/items", "/items"},
{"/r", "/r/release-notes", "/release-notes"},
}
for _, c := range cases {
var got string
h := http.StripPrefix(c.base, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hdr := PageHeader{BasePath: c.base}
hdr.ApplyAppearance(r)
got = hdr.AppearanceBack
}))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, c.request, nil))
if got != c.want {
t.Errorf("base %s, request %s: AppearanceBack = %q, want %q", c.base, c.request, got, c.want)
}
}
}
func TestAppearanceHandler(t *testing.T) { func TestAppearanceHandler(t *testing.T) {
h := AppearanceHandler("/ui") h := AppearanceHandler("/ui")
post := func(form url.Values) *httptest.ResponseRecorder { post := func(form url.Values) *httptest.ResponseRecorder {
+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)
}
}
+7
View File
@@ -1,3 +1,10 @@
module teruna.dev/yetano/yetano-webui-template module teruna.dev/yetano/yetano-webui-template
go 1.26.3 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
)
+6
View File
@@ -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=
+40
View File
@@ -6,6 +6,7 @@
package httpsec package httpsec
import ( import (
"crypto/subtle"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@@ -174,3 +175,42 @@ func CookiePath(basePath string) string {
func SecureCookies(r *http.Request, publicURL string) bool { func SecureCookies(r *http.Request, publicURL string) bool {
return r.TLS != nil || strings.HasPrefix(strings.ToLower(publicURL), "https://") 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
}
+26
View File
@@ -132,3 +132,29 @@ func TestSecureCookies(t *testing.T) {
t.Fatal("TLS") 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)
}
}