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
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user