Null-DRM-Official/apps/streamd/internal/auth/handlers.go
404errordeveloper da8e1123ec
All checks were successful
release / build-and-upload (push) Successful in 7m5s
Streamd v0.2.0: rename, modules panel, stable/beta channels
- 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
2026-10-10 15:58:26 +02:00

586 lines
16 KiB
Go

package auth
import (
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
"sync"
"time"
"streamd/apps/streamd/internal/httpx"
)
// Handler serves the auth routes: login/logout/me, user administration, API
// keys and the audit log.
type Handler struct {
Store *Store
MW *Middleware
Log *slog.Logger
mu sync.Mutex
// setupToken gates creation of the very first admin account. It is
// generated at startup when the users table is empty and cleared the
// moment an account exists.
setupToken string
}
func NewHandler(store *Store, mw *Middleware, lg *slog.Logger) *Handler {
if lg == nil {
lg = slog.Default()
}
return &Handler{Store: store, MW: mw, Log: lg}
}
// SetSetupToken installs the first-run token. Pass "" to disable setup.
func (h *Handler) SetSetupToken(tok string) {
h.mu.Lock()
h.setupToken = tok
h.mu.Unlock()
}
func (h *Handler) currentSetupToken() string {
h.mu.Lock()
defer h.mu.Unlock()
return h.setupToken
}
// NeedsSetup reports whether no account exists yet.
func (h *Handler) NeedsSetup() bool {
n, err := h.Store.CountUsers()
return err == nil && n == 0
}
func (h *Handler) Mount(mux *http.ServeMux) {
mux.HandleFunc("/api/login", h.login)
mux.HandleFunc("/api/logout", h.logout)
mux.HandleFunc("/api/me", h.me)
mux.HandleFunc("/api/setup", h.setup)
mux.HandleFunc("/api/users", h.users)
mux.HandleFunc("/api/users/", h.userByID)
mux.HandleFunc("/api/apikeys", h.apiKeys)
mux.HandleFunc("/api/apikeys/", h.apiKeyByID)
mux.HandleFunc("/api/audit", h.audit)
}
// ---------- session routes ----------
func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
var in struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
ip := h.MW.Trust.ClientIP(r)
user := normalizeUsername(in.Username)
// Two buckets: one per source address, one per account, so neither a
// single host nor a single account can be hammered.
keys := []string{"ip:" + ip, "user:" + user}
for _, k := range keys {
if !h.MW.LoginLimiter.Allow(k) {
retry := h.MW.LoginLimiter.RetryAfter(k)
w.Header().Set("Retry-After", strconv.Itoa(max(retry, 1)))
h.Store.Audit(AuditEntry{Actor: user, ActorKind: ActorUser, IP: ip,
Method: r.Method, Path: r.URL.Path, Status: http.StatusTooManyRequests,
Note: "login throttled"})
writeErr(w, http.StatusTooManyRequests, "too many login attempts — wait and try again")
return
}
}
u, err := h.Store.Authenticate(in.Username, in.Password)
if err != nil {
// Burn extra budget on a failure so guessing is expensive.
for _, k := range keys {
h.MW.LoginLimiter.Penalise(k, 2)
}
h.Store.Audit(AuditEntry{Actor: user, ActorKind: ActorUser, IP: ip,
Method: r.Method, Path: r.URL.Path, Status: http.StatusUnauthorized,
Note: "login failed"})
h.Log.Info("login failed", "user", user, "ip", ip)
writeErr(w, http.StatusUnauthorized, "invalid username or password")
return
}
secret, csrf, err := h.Store.CreateSession(u.ID, h.MW.SessionTTL, ip, r.UserAgent())
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
for _, k := range keys {
h.MW.LoginLimiter.Reset(k)
}
h.MW.SetSessionCookies(w, r, secret, csrf)
h.Store.Audit(AuditEntry{Actor: u.Username, ActorKind: ActorUser, IP: ip,
Method: r.Method, Path: r.URL.Path, Status: http.StatusOK, Note: "login ok"})
h.Log.Info("login", "user", u.Username, "role", string(u.Role), "ip", ip)
writeJSON(w, http.StatusOK, map[string]any{"user": u, "csrf_token": csrf})
}
func (h *Handler) logout(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
if secret := SessionSecret(r); secret != "" {
_ = h.Store.DeleteSession(secret)
}
h.MW.ClearSessionCookies(w, r)
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// me is the agent's and the dashboard's credential preflight: it says who you
// are, or 401s clearly if your credential is bad or revoked.
func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
p := From(r)
if p == nil {
resp := map[string]any{"error": "authentication required"}
if h.NeedsSetup() {
resp["needs_setup"] = true
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
_ = json.NewEncoder(w).Encode(resp)
return
}
out := map[string]any{
"name": p.Name,
"role": string(p.Role),
"actor_kind": string(p.Kind),
}
if p.Kind == ActorUser {
out["user_id"] = p.UserID
out["csrf_token"] = p.CSRFToken
}
if p.AgentID != "" {
out["agent_id"] = p.AgentID
}
writeJSON(w, http.StatusOK, out)
}
// setup creates the first admin account, gated by the one-time token printed
// to the server log at startup.
func (h *Handler) setup(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
writeJSON(w, http.StatusOK, map[string]any{"needs_setup": h.NeedsSetup()})
case http.MethodPost:
if !h.NeedsSetup() {
writeErr(w, http.StatusConflict, "setup already complete")
return
}
tok := h.currentSetupToken()
if tok == "" {
writeErr(w, http.StatusForbidden, "setup is disabled on this server")
return
}
var in struct {
SetupToken string `json:"setup_token"`
Username string `json:"username"`
Password string `json:"password"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
ip := h.MW.Trust.ClientIP(r)
if !h.MW.LoginLimiter.Allow("setup:" + ip) {
writeErr(w, http.StatusTooManyRequests, "too many attempts")
return
}
if !SecretEqual(strings.TrimSpace(in.SetupToken), tok) {
h.MW.LoginLimiter.Penalise("setup:"+ip, 3)
writeErr(w, http.StatusForbidden, "invalid setup token — see the streamd startup log")
return
}
u, err := h.Store.CreateUser(in.Username, in.Password, RoleAdmin)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.SetSetupToken("")
secret, csrf, err := h.Store.CreateSession(u.ID, h.MW.SessionTTL, ip, r.UserAgent())
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
h.MW.SetSessionCookies(w, r, secret, csrf)
h.Store.Audit(AuditEntry{Actor: u.Username, ActorKind: ActorUser, IP: ip,
Method: r.Method, Path: r.URL.Path, Status: http.StatusCreated,
Note: "first admin created"})
h.Log.Info("first admin account created", "user", u.Username)
writeJSON(w, http.StatusCreated, map[string]any{"user": u, "csrf_token": csrf})
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
// ---------- users ----------
func (h *Handler) users(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if _, ok := Guard(w, r, RoleAdmin); !ok {
return
}
list, err := h.Store.ListUsers()
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"users": list})
case http.MethodPost:
p, ok := Guard(w, r, RoleAdmin)
if !ok {
return
}
var in struct {
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
role, err := ParseRole(in.Role)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
u, err := h.Store.CreateUser(in.Username, in.Password, role)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.auditAction(r, p, http.StatusCreated, "created user "+u.Username+" as "+string(u.Role))
writeJSON(w, http.StatusCreated, u)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) userByID(w http.ResponseWriter, r *http.Request) {
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/users/"), "/")
if rest == "" {
h.users(w, r)
return
}
parts := strings.Split(rest, "/")
id, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "invalid user id")
return
}
action := ""
if len(parts) > 1 {
action = parts[1]
}
// Changing your own password needs only a valid session; everything else
// about an account is admin-only.
if action == "password" && r.Method == http.MethodPost {
p := From(r)
if p == nil {
writeErr(w, http.StatusUnauthorized, "authentication required")
return
}
self := p.Kind == ActorUser && p.UserID == id
if !self && !p.Role.AtLeast(RoleAdmin) {
writeErr(w, http.StatusForbidden, "only an admin can change another account's password")
return
}
var in struct {
Current string `json:"current_password"`
Password string `json:"password"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// A user changing their own password must prove they know the old one,
// so a stolen session cannot be made permanent.
if self {
if _, err := h.Store.Authenticate(p.Name, in.Current); err != nil {
writeErr(w, http.StatusForbidden, "current password is incorrect")
return
}
}
if err := h.Store.SetPassword(id, in.Password); err != nil {
if errors.Is(err, ErrNotFound) {
writeErr(w, http.StatusNotFound, "user not found")
return
}
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.auditAction(r, p, http.StatusOK, "password changed for user id "+parts[0])
// Every session for that user was dropped, including this one if it
// was their own, so the dashboard must log in again.
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "sessions_revoked": true})
return
}
p, ok := Guard(w, r, RoleAdmin)
if !ok {
return
}
switch {
case action == "" && r.Method == http.MethodGet:
u, err := h.Store.GetUser(id)
if err != nil {
writeErr(w, http.StatusNotFound, "user not found")
return
}
writeJSON(w, http.StatusOK, u)
case action == "" && (r.Method == http.MethodPatch || r.Method == http.MethodPut):
var in struct {
Role *string `json:"role"`
Disabled *bool `json:"disabled"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
var role *Role
if in.Role != nil {
rr, err := ParseRole(*in.Role)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
role = &rr
}
// Refuse to strand the installation with no usable admin.
demoting := role != nil && *role != RoleAdmin
disabling := in.Disabled != nil && *in.Disabled
if demoting || disabling {
if err := h.ensureAnotherAdmin(id); err != nil {
writeErr(w, http.StatusConflict, err.Error())
return
}
}
u, err := h.Store.UpdateUser(id, role, in.Disabled)
if err != nil {
if errors.Is(err, ErrNotFound) {
writeErr(w, http.StatusNotFound, "user not found")
return
}
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.auditAction(r, p, http.StatusOK, "updated user "+u.Username)
writeJSON(w, http.StatusOK, u)
case action == "" && r.Method == http.MethodDelete:
if err := h.ensureAnotherAdmin(id); err != nil {
writeErr(w, http.StatusConflict, err.Error())
return
}
if err := h.Store.DeleteUser(id); err != nil {
if errors.Is(err, ErrNotFound) {
writeErr(w, http.StatusNotFound, "user not found")
return
}
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
h.auditAction(r, p, http.StatusOK, "deleted user id "+parts[0])
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
default:
writeErr(w, http.StatusNotFound, "not found")
}
}
// ensureAnotherAdmin fails when id is the last enabled admin.
func (h *Handler) ensureAnotherAdmin(id int64) error {
u, err := h.Store.GetUser(id)
if err != nil {
return nil // let the caller's own lookup report "not found"
}
if u.Role != RoleAdmin || u.Disabled {
return nil
}
n, err := h.Store.CountOtherAdmins(id)
if err != nil {
return err
}
if n == 0 {
return errors.New("this is the last enabled admin — promote another account first")
}
return nil
}
// ---------- api keys ----------
func (h *Handler) apiKeys(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if _, ok := Guard(w, r, RoleAdmin); !ok {
return
}
list, err := h.Store.ListAPIKeys()
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"api_keys": list})
case http.MethodPost:
p, ok := Guard(w, r, RoleAdmin)
if !ok {
return
}
var in struct {
Name string `json:"name"`
Role string `json:"role"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if strings.TrimSpace(in.Role) == "" {
in.Role = string(RoleOperator)
}
role, err := ParseRole(in.Role)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
k, err := h.Store.CreateAPIKey(in.Name, role)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.auditAction(r, p, http.StatusCreated, "created api key "+k.Name+" as "+string(k.Role))
h.Log.Info("api key created", "name", k.Name, "role", string(k.Role), "by", p.Actor())
// The secret appears in this response only, and is never stored.
writeJSON(w, http.StatusCreated, k)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) apiKeyByID(w http.ResponseWriter, r *http.Request) {
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/apikeys/"), "/")
if rest == "" {
h.apiKeys(w, r)
return
}
id, err := strconv.ParseInt(strings.Split(rest, "/")[0], 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "invalid key id")
return
}
p, ok := Guard(w, r, RoleAdmin)
if !ok {
return
}
if r.Method != http.MethodDelete {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
if err := h.Store.RevokeAPIKey(id); err != nil {
if errors.Is(err, ErrNotFound) {
writeErr(w, http.StatusNotFound, "key not found or already revoked")
return
}
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
h.auditAction(r, p, http.StatusOK, "revoked api key id "+rest)
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// ---------- audit ----------
func (h *Handler) audit(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
if _, ok := Guard(w, r, RoleAdmin); !ok {
return
}
// Flush first so the caller sees their own just-made changes.
_ = h.Store.FlushAudit()
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
list, err := h.Store.ListAudit(limit, r.URL.Query().Get("actor"))
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"audit": list})
}
// AuditRequest records one mutating request against the calling principal.
func (s *Store) AuditRequest(p *Principal, trust httpx.Trust, r *http.Request, status int, note string) {
kind := ActorKind("")
if p != nil {
kind = p.Kind
}
s.Audit(AuditEntry{
Actor: p.Actor(),
ActorKind: kind,
IP: trust.ClientIP(r),
Method: r.Method,
Path: r.URL.Path,
Status: status,
Note: note,
})
}
func (h *Handler) auditAction(r *http.Request, p *Principal, status int, note string) {
h.Store.AuditRequest(p, h.MW.Trust, r, status, note)
}
// ---------- helpers ----------
func readJSON(r *http.Request, dst any) error {
defer r.Body.Close()
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
return err
}
if len(b) == 0 {
return errors.New("empty body")
}
return json.Unmarshal(b, dst)
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
_ = enc.Encode(v)
}
func writeErr(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]any{"error": msg})
}
// NewSetupToken makes the one-time first-run token.
func NewSetupToken() string {
secret, _, err := NewToken()
if err != nil {
return "setup-" + strconv.FormatInt(time.Now().UnixNano(), 36)
}
return secret
}