All checks were successful
release / build-and-upload (push) Successful in 7m5s
- Rename product/host binary to streamd (drm compat copy still shipped) - Go module path streamd; STREAMD_* env aliases; agent UA streamd-agent - Panel Modules store + agent pull sync (modstore / modsync) - Rolling stable + beta download tags; README/docs channel curl blocks - Release notes in docs/releases/v0.2.0.md attached by Forgejo Actions
238 lines
6.8 KiB
Go
238 lines
6.8 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"streamd/apps/streamd/internal/httpx"
|
|
)
|
|
|
|
const (
|
|
// SessionCookie holds the session secret. HttpOnly, so page scripts
|
|
// cannot read it.
|
|
SessionCookie = "streamd_session"
|
|
// CSRFCookie mirrors the session's CSRF token for the double-submit
|
|
// check. Deliberately readable by scripts.
|
|
CSRFCookie = "streamd_csrf"
|
|
// CSRFHeader is where the dashboard echoes the token back.
|
|
CSRFHeader = "X-CSRF-Token"
|
|
)
|
|
|
|
type ctxKey int
|
|
|
|
const principalKey ctxKey = 1
|
|
|
|
// Middleware resolves the principal for each request, enforces CSRF on
|
|
// cookie-authenticated mutations, and rate-limits the API.
|
|
type Middleware struct {
|
|
Store *Store
|
|
SessionTTL time.Duration
|
|
Trust httpx.Trust
|
|
// CookieSecure forces the Secure attribute even when the request itself
|
|
// arrived over plain HTTP (the usual case behind a TLS-terminating proxy
|
|
// that does not set X-Forwarded-Proto).
|
|
CookieSecure bool
|
|
|
|
// APILimiter throttles mutating API calls per client IP.
|
|
APILimiter *Limiter
|
|
// LoginLimiter throttles login attempts per IP and per username.
|
|
LoginLimiter *Limiter
|
|
}
|
|
|
|
func NewMiddleware(store *Store, trust httpx.Trust, cookieSecure bool) *Middleware {
|
|
return &Middleware{
|
|
Store: store,
|
|
SessionTTL: DefaultSessionTTL,
|
|
Trust: trust,
|
|
CookieSecure: cookieSecure,
|
|
APILimiter: NewLimiter(120, 20),
|
|
LoginLimiter: NewLimiter(8, 0.2),
|
|
}
|
|
}
|
|
|
|
// From returns the principal attached by Attach, or nil when the caller is
|
|
// anonymous.
|
|
func From(r *http.Request) *Principal {
|
|
p, _ := r.Context().Value(principalKey).(*Principal)
|
|
return p
|
|
}
|
|
|
|
// WithPrincipal is exported for tests and for internal callers that need to
|
|
// synthesise an identity.
|
|
func WithPrincipal(ctx context.Context, p *Principal) context.Context {
|
|
return context.WithValue(ctx, principalKey, p)
|
|
}
|
|
|
|
// Attach resolves the principal and stores it on the request context. It does
|
|
// not reject anonymous callers — individual routes decide that via Guard — so
|
|
// that the login page and the public media paths keep working.
|
|
func (m *Middleware) Attach(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p := m.resolve(r)
|
|
if p != nil {
|
|
r = r.WithContext(WithPrincipal(r.Context(), p))
|
|
}
|
|
|
|
if isUnsafe(r.Method) {
|
|
ip := m.Trust.ClientIP(r)
|
|
// Rate-limit mutations per client. Login has its own tighter
|
|
// limiter applied in the handler.
|
|
if strings.HasPrefix(r.URL.Path, "/api/") && !m.APILimiter.Allow(ip) {
|
|
retry := m.APILimiter.RetryAfter(ip)
|
|
w.Header().Set("Retry-After", strconv.Itoa(max(retry, 1)))
|
|
writeJSONError(w, http.StatusTooManyRequests, "too many requests")
|
|
return
|
|
}
|
|
// CSRF applies only to ambient cookie credentials. A bearer token
|
|
// is never attached automatically by a browser.
|
|
if p.NeedsCSRF() && !m.csrfOK(r, p) {
|
|
writeJSONError(w, http.StatusForbidden, "missing or invalid "+CSRFHeader)
|
|
return
|
|
}
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (m *Middleware) resolve(r *http.Request) *Principal {
|
|
// 1. Session cookie.
|
|
if c, err := r.Cookie(SessionCookie); err == nil && c.Value != "" {
|
|
if p, err := m.Store.LookupSession(c.Value, m.SessionTTL); err == nil {
|
|
return p
|
|
}
|
|
}
|
|
// 2. Bearer token / X-Streamd-Token. Note there is deliberately no
|
|
// ?token= fallback any more: it leaked the secret into access logs and
|
|
// referrers. Agents send the header already.
|
|
secret := bearer(r)
|
|
if secret == "" {
|
|
return nil
|
|
}
|
|
p, err := m.Store.LookupAPIKey(secret)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
p.AgentID = sanitiseAgentID(r.Header.Get("X-Agent-ID"))
|
|
return p
|
|
}
|
|
|
|
func bearer(r *http.Request) string {
|
|
if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
|
|
if len(auth) > 7 && strings.EqualFold(auth[:7], "bearer ") {
|
|
return strings.TrimSpace(auth[7:])
|
|
}
|
|
}
|
|
return strings.TrimSpace(r.Header.Get("X-Streamd-Token"))
|
|
}
|
|
|
|
// sanitiseAgentID keeps a volunteered agent label printable and bounded before
|
|
// it reaches an audit row.
|
|
func sanitiseAgentID(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
if len(s) > 64 {
|
|
s = s[:64]
|
|
}
|
|
var b strings.Builder
|
|
for _, r := range s {
|
|
switch {
|
|
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',
|
|
r == '-', r == '_', r == '.':
|
|
b.WriteRune(r)
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func (m *Middleware) csrfOK(r *http.Request, p *Principal) bool {
|
|
sent := strings.TrimSpace(r.Header.Get(CSRFHeader))
|
|
if sent == "" {
|
|
return false
|
|
}
|
|
return SecretEqual(sent, p.CSRFToken)
|
|
}
|
|
|
|
func isUnsafe(method string) bool {
|
|
switch method {
|
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Guard enforces a minimum role, writing the error response itself. It returns
|
|
// the principal and false when the request must not proceed.
|
|
func Guard(w http.ResponseWriter, r *http.Request, min Role) (*Principal, bool) {
|
|
p := From(r)
|
|
if p == nil {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="streamd"`)
|
|
writeJSONError(w, http.StatusUnauthorized, "authentication required")
|
|
return nil, false
|
|
}
|
|
if !p.Role.AtLeast(min) {
|
|
writeJSONError(w, http.StatusForbidden, "role "+string(p.Role)+" cannot perform this action (needs "+string(min)+")")
|
|
return nil, false
|
|
}
|
|
return p, true
|
|
}
|
|
|
|
// SetSessionCookies issues the session and CSRF cookies after a login.
|
|
func (m *Middleware) SetSessionCookies(w http.ResponseWriter, r *http.Request, secret, csrf string) {
|
|
secure := m.CookieSecure || m.Trust.IsHTTPS(r)
|
|
maxAge := int(m.SessionTTL.Seconds())
|
|
if maxAge <= 0 {
|
|
maxAge = int(DefaultSessionTTL.Seconds())
|
|
}
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: SessionCookie,
|
|
Value: secret,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: secure,
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: maxAge,
|
|
})
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: CSRFCookie,
|
|
Value: csrf,
|
|
Path: "/",
|
|
// Readable on purpose: the dashboard copies it into X-CSRF-Token.
|
|
HttpOnly: false,
|
|
Secure: secure,
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: maxAge,
|
|
})
|
|
}
|
|
|
|
// ClearSessionCookies expires both cookies on logout.
|
|
func (m *Middleware) ClearSessionCookies(w http.ResponseWriter, r *http.Request) {
|
|
secure := m.CookieSecure || m.Trust.IsHTTPS(r)
|
|
for _, name := range []string{SessionCookie, CSRFCookie} {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: name,
|
|
Value: "",
|
|
Path: "/",
|
|
HttpOnly: name == SessionCookie,
|
|
Secure: secure,
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: -1,
|
|
})
|
|
}
|
|
}
|
|
|
|
// SessionSecret returns the raw session cookie value, for logout.
|
|
func SessionSecret(r *http.Request) string {
|
|
if c, err := r.Cookie(SessionCookie); err == nil {
|
|
return c.Value
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func writeJSONError(w http.ResponseWriter, code int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"error": msg})
|
|
}
|