streamd: preview quality picker, dashboard polish, C4 wrap keys
- Preview player can select FHD/HD/SD (or ABR master) from publish links - Embed dashboard screenshots in README; Linux streamd+agent setup guide - C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH - Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
This commit is contained in:
parent
b3955bd81e
commit
066e018749
113 changed files with 19002 additions and 1541 deletions
174
apps/streamd/internal/auth/auth.go
Normal file
174
apps/streamd/internal/auth/auth.go
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
// Package auth provides accounts, sessions, API keys and role-based access
|
||||
// control for streamd. Password hashing uses crypto/pbkdf2 from the standard
|
||||
// library, so no third-party crypto dependency is needed.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Role is an access level. Roles are ordered: viewer < operator < admin.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleViewer Role = "viewer"
|
||||
RoleOperator Role = "operator"
|
||||
RoleAdmin Role = "admin"
|
||||
)
|
||||
|
||||
var roleRank = map[Role]int{
|
||||
RoleViewer: 1,
|
||||
RoleOperator: 2,
|
||||
RoleAdmin: 3,
|
||||
}
|
||||
|
||||
// ParseRole validates a role name, defaulting to viewer for anything unknown.
|
||||
func ParseRole(s string) (Role, error) {
|
||||
r := Role(strings.ToLower(strings.TrimSpace(s)))
|
||||
if _, ok := roleRank[r]; !ok {
|
||||
return RoleViewer, fmt.Errorf("unknown role %q (want viewer, operator or admin)", s)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// AtLeast reports whether r grants everything min does.
|
||||
func (r Role) AtLeast(min Role) bool {
|
||||
return roleRank[r] >= roleRank[min]
|
||||
}
|
||||
|
||||
func (r Role) Valid() bool {
|
||||
_, ok := roleRank[r]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ActorKind distinguishes a logged-in human from a machine credential.
|
||||
type ActorKind string
|
||||
|
||||
const (
|
||||
ActorUser ActorKind = "user"
|
||||
ActorAPIKey ActorKind = "apikey"
|
||||
ActorSystem ActorKind = "system"
|
||||
)
|
||||
|
||||
// Principal is the authenticated identity behind a request.
|
||||
type Principal struct {
|
||||
Kind ActorKind
|
||||
Role Role
|
||||
// Name is the username or the API key's label, used for audit rows.
|
||||
Name string
|
||||
// UserID is set for session principals only.
|
||||
UserID int64
|
||||
// AgentID is the X-Agent-ID a machine caller volunteered, if any.
|
||||
AgentID string
|
||||
// SessionID is the raw session id for session principals (needed to
|
||||
// resolve the CSRF token); empty for bearer principals.
|
||||
SessionID string
|
||||
// CSRFToken is the token a cookie-authenticated caller must echo back.
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
// Actor is the audit-log label for this principal.
|
||||
func (p *Principal) Actor() string {
|
||||
if p == nil {
|
||||
return "anonymous"
|
||||
}
|
||||
if p.AgentID != "" && p.Kind == ActorAPIKey {
|
||||
return p.Name + "@" + p.AgentID
|
||||
}
|
||||
return p.Name
|
||||
}
|
||||
|
||||
// NeedsCSRF is true for ambient (cookie) credentials only. A bearer token is
|
||||
// never sent automatically by a browser, so it carries no CSRF risk.
|
||||
func (p *Principal) NeedsCSRF() bool {
|
||||
return p != nil && p.Kind == ActorUser && p.SessionID != ""
|
||||
}
|
||||
|
||||
const (
|
||||
pbkdf2Iterations = 600_000
|
||||
pbkdf2KeyLen = 32
|
||||
saltLen = 16
|
||||
tokenLen = 32
|
||||
)
|
||||
|
||||
// HashPassword returns an encoded PBKDF2-HMAC-SHA256 hash:
|
||||
//
|
||||
// pbkdf2-sha256$<iterations>$<base64 salt>$<base64 derived key>
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len(password) < 8 {
|
||||
return "", fmt.Errorf("password must be at least 8 characters")
|
||||
}
|
||||
salt := make([]byte, saltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hashWithSalt(password, salt, pbkdf2Iterations)
|
||||
}
|
||||
|
||||
func hashWithSalt(password string, salt []byte, iters int) (string, error) {
|
||||
dk, err := pbkdf2.Key(sha256.New, password, salt, iters, pbkdf2KeyLen)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s",
|
||||
iters,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(dk),
|
||||
), nil
|
||||
}
|
||||
|
||||
// VerifyPassword checks a password against an encoded hash in constant time.
|
||||
// A malformed or empty hash always fails, and never panics.
|
||||
func VerifyPassword(encoded, password string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 4 || parts[0] != "pbkdf2-sha256" {
|
||||
return false
|
||||
}
|
||||
iters, err := strconv.Atoi(parts[1])
|
||||
if err != nil || iters <= 0 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[3])
|
||||
if err != nil || len(want) == 0 {
|
||||
return false
|
||||
}
|
||||
got, err := pbkdf2.Key(sha256.New, password, salt, iters, len(want))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
|
||||
// NewToken returns a URL-safe random secret and its storage hash. Only the
|
||||
// hash is ever persisted, so a database leak does not yield usable credentials.
|
||||
func NewToken() (secret, hash string, err error) {
|
||||
b := make([]byte, tokenLen)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
secret = base64.RawURLEncoding.EncodeToString(b)
|
||||
return secret, HashToken(secret), nil
|
||||
}
|
||||
|
||||
// HashToken is the storage form of a session id or API key.
|
||||
func HashToken(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// SecretEqual compares two secrets in constant time.
|
||||
func SecretEqual(a, b string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
|
||||
}
|
||||
548
apps/streamd/internal/auth/auth_test.go
Normal file
548
apps/streamd/internal/auth/auth_test.go
Normal file
|
|
@ -0,0 +1,548 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func TestHashPasswordRoundTrip(t *testing.T) {
|
||||
h, err := HashPassword("correct horse battery")
|
||||
if err != nil {
|
||||
t.Fatalf("hash: %v", err)
|
||||
}
|
||||
if !VerifyPassword(h, "correct horse battery") {
|
||||
t.Error("correct password rejected")
|
||||
}
|
||||
if VerifyPassword(h, "correct horse batterz") {
|
||||
t.Error("wrong password accepted")
|
||||
}
|
||||
if VerifyPassword(h, "") {
|
||||
t.Error("empty password accepted")
|
||||
}
|
||||
// Two hashes of the same password must differ (unique salt).
|
||||
h2, _ := HashPassword("correct horse battery")
|
||||
if h == h2 {
|
||||
t.Error("salt is not random: identical hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordRejectsShort(t *testing.T) {
|
||||
if _, err := HashPassword("short"); err == nil {
|
||||
t.Error("expected short password to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordMalformed(t *testing.T) {
|
||||
for _, bad := range []string{
|
||||
"", "nonsense", "pbkdf2-sha256$", "pbkdf2-sha256$a$b$c",
|
||||
"pbkdf2-sha256$0$c2FsdA$aGFzaA", "bcrypt$1$x$y",
|
||||
"pbkdf2-sha256$1000$!!!$aGFzaA", "pbkdf2-sha256$1000$c2FsdA$",
|
||||
} {
|
||||
if VerifyPassword(bad, "anything") {
|
||||
t.Errorf("malformed hash %q was accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoleOrdering(t *testing.T) {
|
||||
if !RoleAdmin.AtLeast(RoleOperator) || !RoleAdmin.AtLeast(RoleViewer) {
|
||||
t.Error("admin should outrank operator and viewer")
|
||||
}
|
||||
if RoleViewer.AtLeast(RoleOperator) {
|
||||
t.Error("viewer must not satisfy operator")
|
||||
}
|
||||
if RoleOperator.AtLeast(RoleAdmin) {
|
||||
t.Error("operator must not satisfy admin")
|
||||
}
|
||||
if !RoleViewer.AtLeast(RoleViewer) {
|
||||
t.Error("a role should satisfy itself")
|
||||
}
|
||||
if _, err := ParseRole("root"); err == nil {
|
||||
t.Error("unknown role should error")
|
||||
}
|
||||
if r, err := ParseRole(" ADMIN "); err != nil || r != RoleAdmin {
|
||||
t.Errorf("ParseRole should normalise case and space, got %q %v", r, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTokenHashing(t *testing.T) {
|
||||
secret, hash, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if secret == "" || hash == "" || secret == hash {
|
||||
t.Fatalf("bad token/hash pair: %q %q", secret, hash)
|
||||
}
|
||||
if HashToken(secret) != hash {
|
||||
t.Error("HashToken disagrees with NewToken")
|
||||
}
|
||||
s2, _, _ := NewToken()
|
||||
if s2 == secret {
|
||||
t.Error("tokens are not random")
|
||||
}
|
||||
}
|
||||
|
||||
func newTestStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
// A private temp file rather than :memory:, because the real store runs
|
||||
// with one connection against a file and we want the same semantics.
|
||||
dsn := "file:" + t.TempDir() + "/auth_test.db?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)"
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
s, err := New(db, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestUserLifecycle(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
|
||||
if n, err := s.CountUsers(); err != nil || n != 0 {
|
||||
t.Fatalf("fresh store should have no users, got %d %v", n, err)
|
||||
}
|
||||
u, err := s.CreateUser(" Alice ", "hunter2hunter2", RoleAdmin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.Username != "alice" {
|
||||
t.Errorf("username should be normalised, got %q", u.Username)
|
||||
}
|
||||
if _, err := s.CreateUser("alice", "otherpassword", RoleViewer); err == nil {
|
||||
t.Error("duplicate username should be rejected")
|
||||
}
|
||||
|
||||
if _, err := s.Authenticate("ALICE", "hunter2hunter2"); err != nil {
|
||||
t.Errorf("login should succeed case-insensitively: %v", err)
|
||||
}
|
||||
if _, err := s.Authenticate("alice", "wrong"); err == nil {
|
||||
t.Error("wrong password should fail")
|
||||
}
|
||||
if _, err := s.Authenticate("nobody", "whatever"); err == nil {
|
||||
t.Error("unknown user should fail")
|
||||
}
|
||||
|
||||
// Disabling blocks login.
|
||||
dis := true
|
||||
if _, err := s.UpdateUser(u.ID, nil, &dis); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Authenticate("alice", "hunter2hunter2"); err == nil {
|
||||
t.Error("disabled account should not authenticate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLifecycle(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
u, err := s.CreateUser("bob", "password1234", RoleOperator)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
secret, csrf, err := s.CreateSession(u.ID, time.Hour, "10.0.0.1", "test-agent")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := s.LookupSession(secret, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
if p.Name != "bob" || p.Role != RoleOperator || p.Kind != ActorUser {
|
||||
t.Errorf("unexpected principal %+v", p)
|
||||
}
|
||||
if p.CSRFToken != csrf {
|
||||
t.Error("CSRF token mismatch")
|
||||
}
|
||||
if !p.NeedsCSRF() {
|
||||
t.Error("session principal must require CSRF")
|
||||
}
|
||||
|
||||
// The raw secret must not be stored.
|
||||
var count int
|
||||
if err := s.DB.QueryRow(`SELECT COUNT(*) FROM sessions WHERE id_hash = ?`, secret).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Error("raw session secret found in the database")
|
||||
}
|
||||
|
||||
if _, err := s.LookupSession("not-a-session", time.Hour); err == nil {
|
||||
t.Error("bogus session should not resolve")
|
||||
}
|
||||
|
||||
// Changing the password must revoke sessions.
|
||||
if err := s.SetPassword(u.ID, "newpassword12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.LookupSession(secret, time.Hour); err == nil {
|
||||
t.Error("session should be revoked after a password change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
u, _ := s.CreateUser("carol", "password1234", RoleViewer)
|
||||
secret, _, err := s.CreateSession(u.ID, -time.Hour, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// CreateSession clamps a non-positive TTL to the default, so force the row
|
||||
// into the past to exercise the expiry branch.
|
||||
if _, err := s.DB.Exec(`UPDATE sessions SET expires_at = ?`,
|
||||
time.Now().UTC().Add(-time.Minute).Format(time.RFC3339)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.LookupSession(secret, time.Hour); err == nil {
|
||||
t.Error("expired session should not resolve")
|
||||
}
|
||||
if n, err := s.ExpireSessions(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if n < 0 {
|
||||
t.Error("unexpected negative expiry count")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIKeyLifecycle(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
k, err := s.CreateAPIKey("phone-agent", RoleOperator)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k.Secret == "" {
|
||||
t.Fatal("create must return the secret once")
|
||||
}
|
||||
p, err := s.LookupAPIKey(k.Secret)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
if p.Role != RoleOperator || p.Kind != ActorAPIKey || p.Name != "phone-agent" {
|
||||
t.Errorf("unexpected principal %+v", p)
|
||||
}
|
||||
if p.NeedsCSRF() {
|
||||
t.Error("bearer principals must be exempt from CSRF")
|
||||
}
|
||||
|
||||
// Listing never exposes the secret.
|
||||
list, err := s.ListAPIKeys()
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("list: %v %d", err, len(list))
|
||||
}
|
||||
if list[0].Secret != "" {
|
||||
t.Error("list must not expose key secrets")
|
||||
}
|
||||
|
||||
if err := s.RevokeAPIKey(k.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.LookupAPIKey(k.Secret); err == nil {
|
||||
t.Error("revoked key should not authenticate")
|
||||
}
|
||||
if err := s.RevokeAPIKey(k.ID); err == nil {
|
||||
t.Error("revoking twice should report not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyTokenActsAsAdminKey(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
s.LegacyToken = "SECRET-FROM-ENV"
|
||||
p, err := s.LookupAPIKey("SECRET-FROM-ENV")
|
||||
if err != nil {
|
||||
t.Fatalf("legacy token should resolve: %v", err)
|
||||
}
|
||||
if p.Role != RoleAdmin {
|
||||
t.Errorf("legacy token should be admin, got %q", p.Role)
|
||||
}
|
||||
if _, err := s.LookupAPIKey("SECRET-FROM-EN"); err == nil {
|
||||
t.Error("near-miss token should not resolve")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditBufferFlush(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
for i := 0; i < 5; i++ {
|
||||
s.Audit(AuditEntry{Actor: "alice", ActorKind: ActorUser, Method: "POST",
|
||||
Path: "/api/streams", Status: 200, Note: "created"})
|
||||
}
|
||||
// Nothing is written until a flush, by design — the DB has a single
|
||||
// connection and must not be hit per request.
|
||||
var n int
|
||||
_ = s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Errorf("audit rows written before flush: %d", n)
|
||||
}
|
||||
if err := s.FlushAudit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 5 {
|
||||
t.Errorf("want 5 audit rows after flush, got %d", n)
|
||||
}
|
||||
list, err := s.ListAudit(10, "")
|
||||
if err != nil || len(list) != 5 {
|
||||
t.Fatalf("list audit: %v %d", err, len(list))
|
||||
}
|
||||
if list[0].Actor != "alice" {
|
||||
t.Errorf("unexpected actor %q", list[0].Actor)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- middleware ----------
|
||||
|
||||
func testMW(t *testing.T) (*Middleware, *Store) {
|
||||
t.Helper()
|
||||
s := newTestStore(t)
|
||||
mw := NewMiddleware(s, httpx.Trust{}, false)
|
||||
return mw, s
|
||||
}
|
||||
|
||||
// probe is a handler that reports the principal the middleware attached.
|
||||
func probe(w http.ResponseWriter, r *http.Request) {
|
||||
p := From(r)
|
||||
if p == nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("anonymous"))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(p.Name + ":" + string(p.Role)))
|
||||
}
|
||||
|
||||
func TestAttachResolvesBearer(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("agent", RoleOperator)
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+k.Secret)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if got := rec.Body.String(); got != "agent:operator" {
|
||||
t.Errorf("want agent:operator, got %q", got)
|
||||
}
|
||||
|
||||
// X-Streamd-Token is still honoured.
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.Header.Set("X-Streamd-Token", k.Secret)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if got := rec.Body.String(); got != "agent:operator" {
|
||||
t.Errorf("X-Streamd-Token: want agent:operator, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The ?token= query parameter used to authenticate. It must not any more: it
|
||||
// leaked the shared secret into proxy access logs and Referer headers.
|
||||
func TestQueryTokenIsRejected(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("agent", RoleOperator)
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams?token="+k.Secret, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if got := rec.Body.String(); got != "anonymous" {
|
||||
t.Errorf("?token= must not authenticate, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFRequiredForCookieMutation(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
u, _ := s.CreateUser("dave", "password1234", RoleOperator)
|
||||
secret, csrf, err := s.CreateSession(u.ID, time.Hour, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
|
||||
// GET needs no CSRF.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("GET with cookie should pass, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// POST without the header is refused.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("POST without CSRF should be 403, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// POST with a wrong header is refused.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
req.Header.Set(CSRFHeader, "wrong")
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("POST with bad CSRF should be 403, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// POST with the right header passes.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
req.Header.Set(CSRFHeader, csrf)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("POST with valid CSRF should pass, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFNotRequiredForBearerMutation(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("agent", RoleOperator)
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/streams/1/credentials", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+k.Secret)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("bearer POST should not need CSRF, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardRoles(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("viewer-key", RoleViewer)
|
||||
|
||||
guarded := mw.Attach(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := Guard(w, r, RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte("allowed"))
|
||||
}))
|
||||
|
||||
// Anonymous → 401.
|
||||
rec := httptest.NewRecorder()
|
||||
guarded.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/streams", nil))
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous should be 401, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// Under-privileged → 403.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+k.Secret)
|
||||
rec = httptest.NewRecorder()
|
||||
guarded.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("viewer should be 403 for operator route, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginThrottleLocksOut(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
if _, err := s.CreateUser("erin", "password1234", RoleAdmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := NewHandler(s, mw, nil)
|
||||
mux := http.NewServeMux()
|
||||
h.Mount(mux)
|
||||
srv := mw.Attach(mux)
|
||||
|
||||
post := func(body string) int {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/login", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.RemoteAddr = "203.0.113.9:1234"
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
sawLockout := false
|
||||
for i := 0; i < 12; i++ {
|
||||
if post(`{"username":"erin","password":"wrong"}`) == http.StatusTooManyRequests {
|
||||
sawLockout = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !sawLockout {
|
||||
t.Error("repeated bad logins should eventually be throttled")
|
||||
}
|
||||
// And the lockout applies to the correct password too, so guessing cannot
|
||||
// be continued by getting lucky.
|
||||
if code := post(`{"username":"erin","password":"password1234"}`); code != http.StatusTooManyRequests {
|
||||
t.Errorf("throttle should also hold off a correct password, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSucceedsAndSetsCookies(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
if _, err := s.CreateUser("frank", "password1234", RoleAdmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := NewHandler(s, mw, nil)
|
||||
mux := http.NewServeMux()
|
||||
h.Mount(mux)
|
||||
srv := mw.Attach(mux)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/login", strings.NewReader(`{"username":"frank","password":"password1234"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login failed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var sessionCookie, csrfCookie *http.Cookie
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
switch c.Name {
|
||||
case SessionCookie:
|
||||
sessionCookie = c
|
||||
case CSRFCookie:
|
||||
csrfCookie = c
|
||||
}
|
||||
}
|
||||
if sessionCookie == nil || csrfCookie == nil {
|
||||
t.Fatal("login must set both cookies")
|
||||
}
|
||||
if !sessionCookie.HttpOnly {
|
||||
t.Error("session cookie must be HttpOnly")
|
||||
}
|
||||
if csrfCookie.HttpOnly {
|
||||
t.Error("CSRF cookie must be readable by the page script")
|
||||
}
|
||||
if sessionCookie.SameSite != http.SameSiteLaxMode {
|
||||
t.Error("session cookie should be SameSite=Lax")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiterRefills(t *testing.T) {
|
||||
l := NewLimiter(2, 100) // 2 burst, refills fast
|
||||
if !l.Allow("k") || !l.Allow("k") {
|
||||
t.Fatal("burst should allow two")
|
||||
}
|
||||
if l.Allow("k") {
|
||||
t.Error("third call should be denied immediately")
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if !l.Allow("k") {
|
||||
t.Error("bucket should refill")
|
||||
}
|
||||
// Distinct keys are independent.
|
||||
if !l.Allow("other") {
|
||||
t.Error("a different key should have its own bucket")
|
||||
}
|
||||
// Empty key is never limited (used for "no IP known").
|
||||
for i := 0; i < 10; i++ {
|
||||
if !l.Allow("") {
|
||||
t.Fatal("empty key should not be limited")
|
||||
}
|
||||
}
|
||||
}
|
||||
586
apps/streamd/internal/auth/handlers.go
Normal file
586
apps/streamd/internal/auth/handlers.go
Normal file
|
|
@ -0,0 +1,586 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/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
|
||||
}
|
||||
238
apps/streamd/internal/auth/middleware.go
Normal file
238
apps/streamd/internal/auth/middleware.go
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/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})
|
||||
}
|
||||
140
apps/streamd/internal/auth/ratelimit.go
Normal file
140
apps/streamd/internal/auth/ratelimit.go
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limiter is a keyed token bucket. Keys are usually a client IP, or an
|
||||
// IP+username pair for login attempts.
|
||||
type Limiter struct {
|
||||
// Burst is the bucket capacity.
|
||||
Burst float64
|
||||
// PerSecond is the refill rate.
|
||||
PerSecond float64
|
||||
|
||||
mu sync.Mutex
|
||||
buckets map[string]*bucket
|
||||
lastGC time.Time
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
seen time.Time
|
||||
}
|
||||
|
||||
func NewLimiter(burst, perSecond float64) *Limiter {
|
||||
if burst <= 0 {
|
||||
burst = 1
|
||||
}
|
||||
if perSecond <= 0 {
|
||||
perSecond = 1
|
||||
}
|
||||
return &Limiter{
|
||||
Burst: burst,
|
||||
PerSecond: perSecond,
|
||||
buckets: map[string]*bucket{},
|
||||
lastGC: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// Allow consumes a token for key, reporting whether the request may proceed.
|
||||
func (l *Limiter) Allow(key string) bool {
|
||||
return l.AllowN(key, 1)
|
||||
}
|
||||
|
||||
// AllowN consumes n tokens, for operations that should cost more than one.
|
||||
func (l *Limiter) AllowN(key string, n float64) bool {
|
||||
if l == nil || key == "" {
|
||||
return true
|
||||
}
|
||||
nowT := time.Now()
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.gcLocked(nowT)
|
||||
|
||||
b, ok := l.buckets[key]
|
||||
if !ok {
|
||||
b = &bucket{tokens: l.Burst, seen: nowT}
|
||||
l.buckets[key] = b
|
||||
}
|
||||
// Refill for the elapsed time, capped at Burst.
|
||||
elapsed := nowT.Sub(b.seen).Seconds()
|
||||
if elapsed > 0 {
|
||||
b.tokens += elapsed * l.PerSecond
|
||||
if b.tokens > l.Burst {
|
||||
b.tokens = l.Burst
|
||||
}
|
||||
}
|
||||
b.seen = nowT
|
||||
if b.tokens < n {
|
||||
return false
|
||||
}
|
||||
b.tokens -= n
|
||||
return true
|
||||
}
|
||||
|
||||
// Penalise drains a bucket so repeated failures cost more than one attempt.
|
||||
func (l *Limiter) Penalise(key string, tokens float64) {
|
||||
if l == nil || key == "" {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
b, ok := l.buckets[key]
|
||||
if !ok {
|
||||
b = &bucket{tokens: l.Burst, seen: time.Now()}
|
||||
l.buckets[key] = b
|
||||
}
|
||||
b.tokens -= tokens
|
||||
if b.tokens < -l.Burst {
|
||||
b.tokens = -l.Burst
|
||||
}
|
||||
}
|
||||
|
||||
// Reset clears a key, used after a successful login.
|
||||
func (l *Limiter) Reset(key string) {
|
||||
if l == nil || key == "" {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
delete(l.buckets, key)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// RetryAfter estimates the seconds until key has a token again.
|
||||
func (l *Limiter) RetryAfter(key string) int {
|
||||
if l == nil {
|
||||
return 0
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
b, ok := l.buckets[key]
|
||||
if !ok || b.tokens >= 1 {
|
||||
return 0
|
||||
}
|
||||
need := 1 - b.tokens
|
||||
secs := int(need/l.PerSecond) + 1
|
||||
if secs < 1 {
|
||||
secs = 1
|
||||
}
|
||||
return secs
|
||||
}
|
||||
|
||||
// gcLocked drops idle buckets so the map cannot grow without bound under a
|
||||
// spray of distinct source addresses.
|
||||
func (l *Limiter) gcLocked(nowT time.Time) {
|
||||
if nowT.Sub(l.lastGC) < time.Minute {
|
||||
return
|
||||
}
|
||||
l.lastGC = nowT
|
||||
idle := time.Duration(float64(time.Second) * (2 * l.Burst / l.PerSecond))
|
||||
if idle < 5*time.Minute {
|
||||
idle = 5 * time.Minute
|
||||
}
|
||||
for k, b := range l.buckets {
|
||||
if nowT.Sub(b.seen) > idle {
|
||||
delete(l.buckets, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
639
apps/streamd/internal/auth/store.go
Normal file
639
apps/streamd/internal/auth/store.go
Normal file
|
|
@ -0,0 +1,639 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultSessionTTL is how long a login lasts without activity.
|
||||
const DefaultSessionTTL = 12 * time.Hour
|
||||
|
||||
// ErrNotFound is returned when a user, key or session does not exist.
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
// Store owns the auth tables. It shares streamd's single *sql.DB, so every
|
||||
// write here serialises with the stream writes — audit rows and key
|
||||
// last-used stamps are therefore buffered rather than written per request.
|
||||
type Store struct {
|
||||
DB *sql.DB
|
||||
|
||||
// LegacyToken keeps --token / STREAMD_TOKEN working as an implicit admin
|
||||
// API key so existing agents and scripts do not break.
|
||||
LegacyToken string
|
||||
|
||||
mu sync.Mutex
|
||||
// auditBuf accumulates rows between flushes.
|
||||
auditBuf []AuditEntry
|
||||
// keyTouch throttles api_keys.last_used_at writes to one per minute.
|
||||
keyTouch map[int64]time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role Role `json:"role"`
|
||||
Disabled bool `json:"disabled"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastLoginAt string `json:"last_login_at,omitempty"`
|
||||
}
|
||||
|
||||
type APIKey struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Role Role `json:"role"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastUsedAt string `json:"last_used_at,omitempty"`
|
||||
RevokedAt string `json:"revoked_at,omitempty"`
|
||||
// Secret is populated only in the response that creates the key; it is
|
||||
// never stored and never shown again.
|
||||
Secret string `json:"secret,omitempty"`
|
||||
}
|
||||
|
||||
type AuditEntry struct {
|
||||
ID int64 `json:"id"`
|
||||
At string `json:"at"`
|
||||
Actor string `json:"actor"`
|
||||
ActorKind ActorKind `json:"actor_kind"`
|
||||
IP string `json:"ip"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Status int `json:"status"`
|
||||
Note string `json:"note,omitempty"`
|
||||
}
|
||||
|
||||
func New(db *sql.DB, legacyToken string) (*Store, error) {
|
||||
s := &Store{DB: db, LegacyToken: strings.TrimSpace(legacyToken), keyTouch: map[int64]time.Time{}}
|
||||
if err := s.Migrate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func now() string { return time.Now().UTC().Format(time.RFC3339) }
|
||||
|
||||
func (s *Store) Migrate() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
pass_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'viewer',
|
||||
disabled INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
last_login_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id_hash TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
csrf TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL DEFAULT '',
|
||||
ip TEXT NOT NULL DEFAULT '',
|
||||
user_agent TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
key_hash TEXT NOT NULL UNIQUE,
|
||||
role TEXT NOT NULL DEFAULT 'operator',
|
||||
created_at TEXT NOT NULL,
|
||||
last_used_at TEXT NOT NULL DEFAULT '',
|
||||
revoked_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL,
|
||||
actor TEXT NOT NULL DEFAULT '',
|
||||
actor_kind TEXT NOT NULL DEFAULT '',
|
||||
ip TEXT NOT NULL DEFAULT '',
|
||||
method TEXT NOT NULL DEFAULT '',
|
||||
path TEXT NOT NULL DEFAULT '',
|
||||
status INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_at ON audit_log(at);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// ---------- users ----------
|
||||
|
||||
func (s *Store) CountUsers() (int, error) {
|
||||
var n int
|
||||
err := s.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func normalizeUsername(u string) string {
|
||||
return strings.ToLower(strings.TrimSpace(u))
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(username, password string, role Role) (User, error) {
|
||||
username = normalizeUsername(username)
|
||||
if username == "" {
|
||||
return User{}, fmt.Errorf("username required")
|
||||
}
|
||||
if !role.Valid() {
|
||||
return User{}, fmt.Errorf("invalid role %q", role)
|
||||
}
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
res, err := s.DB.Exec(`INSERT INTO users(username,pass_hash,role,disabled,created_at) VALUES(?,?,?,0,?)`,
|
||||
username, hash, string(role), now())
|
||||
if err != nil {
|
||||
if strings.Contains(strings.ToLower(err.Error()), "unique") {
|
||||
return User{}, fmt.Errorf("user %q already exists", username)
|
||||
}
|
||||
return User{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetUser(id)
|
||||
}
|
||||
|
||||
const userSelect = `SELECT id, username, role, disabled, created_at, last_login_at FROM users`
|
||||
|
||||
type rowScanner interface{ Scan(...any) error }
|
||||
|
||||
func scanUser(row rowScanner) (User, error) {
|
||||
var u User
|
||||
var disabled int
|
||||
var role string
|
||||
if err := row.Scan(&u.ID, &u.Username, &role, &disabled, &u.CreatedAt, &u.LastLoginAt); err != nil {
|
||||
return u, err
|
||||
}
|
||||
u.Role = Role(role)
|
||||
u.Disabled = disabled != 0
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUser(id int64) (User, error) {
|
||||
u, err := scanUser(s.DB.QueryRow(userSelect+` WHERE id=?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return u, ErrNotFound
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *Store) ListUsers() ([]User, error) {
|
||||
rows, err := s.DB.Query(userSelect + ` ORDER BY username`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []User{}
|
||||
for rows.Next() {
|
||||
u, err := scanUser(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, u)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Authenticate verifies a username and password. It always performs a hash
|
||||
// comparison, even for an unknown user, so a missing account and a wrong
|
||||
// password take the same time.
|
||||
func (s *Store) Authenticate(username, password string) (User, error) {
|
||||
username = normalizeUsername(username)
|
||||
var id int64
|
||||
var hash, role string
|
||||
var disabled int
|
||||
err := s.DB.QueryRow(`SELECT id, pass_hash, role, disabled FROM users WHERE username=?`, username).
|
||||
Scan(&id, &hash, &role, &disabled)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
// Decoy verify against a well-formed hash to equalise timing.
|
||||
VerifyPassword(decoyHash, password)
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if !VerifyPassword(hash, password) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if disabled != 0 {
|
||||
return User{}, fmt.Errorf("account disabled")
|
||||
}
|
||||
_, _ = s.DB.Exec(`UPDATE users SET last_login_at=? WHERE id=?`, now(), id)
|
||||
return s.GetUser(id)
|
||||
}
|
||||
|
||||
// decoyHash is a real PBKDF2 hash of an unguessable value, used only to burn
|
||||
// the same CPU on a missing account as on a wrong password.
|
||||
var decoyHash = func() string {
|
||||
secret, _, err := NewToken()
|
||||
if err != nil {
|
||||
secret = "streamd-decoy-value"
|
||||
}
|
||||
h, err := hashWithSalt(secret, []byte("streamd-decoy-sa"), pbkdf2Iterations)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return h
|
||||
}()
|
||||
|
||||
func (s *Store) SetPassword(id int64, password string) error {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := s.DB.Exec(`UPDATE users SET pass_hash=? WHERE id=?`, hash, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
// Changing a password invalidates every existing session for that user.
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateUser(id int64, role *Role, disabled *bool) (User, error) {
|
||||
cur, err := s.GetUser(id)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if role != nil {
|
||||
if !role.Valid() {
|
||||
return User{}, fmt.Errorf("invalid role %q", *role)
|
||||
}
|
||||
cur.Role = *role
|
||||
}
|
||||
if disabled != nil {
|
||||
cur.Disabled = *disabled
|
||||
}
|
||||
d := 0
|
||||
if cur.Disabled {
|
||||
d = 1
|
||||
}
|
||||
if _, err := s.DB.Exec(`UPDATE users SET role=?, disabled=? WHERE id=?`, string(cur.Role), d, id); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if cur.Disabled {
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
|
||||
}
|
||||
return s.GetUser(id)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteUser(id int64) error {
|
||||
res, err := s.DB.Exec(`DELETE FROM users WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountOtherAdmins counts enabled admins other than excludeID. Used to refuse
|
||||
// deleting, disabling or demoting the last admin.
|
||||
func (s *Store) CountOtherAdmins(excludeID int64) (int, error) {
|
||||
var n int
|
||||
err := s.DB.QueryRow(
|
||||
`SELECT COUNT(*) FROM users WHERE role = 'admin' AND disabled = 0 AND id <> ?`,
|
||||
excludeID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ---------- sessions ----------
|
||||
|
||||
// CreateSession returns the raw session secret and its CSRF token. Only
|
||||
// hashes of the secret reach the database.
|
||||
func (s *Store) CreateSession(userID int64, ttl time.Duration, ip, ua string) (secret, csrf string, err error) {
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultSessionTTL
|
||||
}
|
||||
secret, hash, err := NewToken()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
csrf, _, err = NewToken()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
_, err = s.DB.Exec(`
|
||||
INSERT INTO sessions(id_hash,user_id,csrf,created_at,expires_at,last_seen_at,ip,user_agent)
|
||||
VALUES(?,?,?,?,?,?,?,?)`,
|
||||
hash, userID, csrf, nowT.Format(time.RFC3339), nowT.Add(ttl).Format(time.RFC3339),
|
||||
nowT.Format(time.RFC3339), ip, truncate(ua, 200))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return secret, csrf, nil
|
||||
}
|
||||
|
||||
// LookupSession resolves a raw session secret to a principal, sliding the
|
||||
// expiry forward on use.
|
||||
func (s *Store) LookupSession(secret string, ttl time.Duration) (*Principal, error) {
|
||||
if secret == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultSessionTTL
|
||||
}
|
||||
hash := HashToken(secret)
|
||||
var userID int64
|
||||
var csrf, expires, username, role string
|
||||
var disabled int
|
||||
err := s.DB.QueryRow(`
|
||||
SELECT s.user_id, s.csrf, s.expires_at, u.username, u.role, u.disabled
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.id_hash = ?`, hash).Scan(&userID, &csrf, &expires, &username, &role, &disabled)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if disabled != 0 {
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, hash)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if exp, e := time.Parse(time.RFC3339, expires); e == nil && !exp.After(time.Now().UTC()) {
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, hash)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
_, _ = s.DB.Exec(`UPDATE sessions SET last_seen_at=?, expires_at=? WHERE id_hash=?`,
|
||||
nowT.Format(time.RFC3339), nowT.Add(ttl).Format(time.RFC3339), hash)
|
||||
return &Principal{
|
||||
Kind: ActorUser,
|
||||
Role: Role(role),
|
||||
Name: username,
|
||||
UserID: userID,
|
||||
SessionID: secret,
|
||||
CSRFToken: csrf,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSession(secret string) error {
|
||||
if secret == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, HashToken(secret))
|
||||
return err
|
||||
}
|
||||
|
||||
// ExpireSessions drops sessions past their expiry. Returns rows removed.
|
||||
func (s *Store) ExpireSessions() (int64, error) {
|
||||
res, err := s.DB.Exec(`DELETE FROM sessions WHERE expires_at <> '' AND expires_at < ?`, now())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// ---------- api keys ----------
|
||||
|
||||
func (s *Store) CreateAPIKey(name string, role Role) (APIKey, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return APIKey{}, fmt.Errorf("name required")
|
||||
}
|
||||
if !role.Valid() {
|
||||
return APIKey{}, fmt.Errorf("invalid role %q", role)
|
||||
}
|
||||
secret, hash, err := NewToken()
|
||||
if err != nil {
|
||||
return APIKey{}, err
|
||||
}
|
||||
res, err := s.DB.Exec(`INSERT INTO api_keys(name,key_hash,role,created_at) VALUES(?,?,?,?)`,
|
||||
name, hash, string(role), now())
|
||||
if err != nil {
|
||||
return APIKey{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
k, err := s.getAPIKey(id)
|
||||
if err != nil {
|
||||
return APIKey{}, err
|
||||
}
|
||||
k.Secret = secret
|
||||
return k, nil
|
||||
}
|
||||
|
||||
const keySelect = `SELECT id, name, role, created_at, last_used_at, revoked_at FROM api_keys`
|
||||
|
||||
func scanKey(row rowScanner) (APIKey, error) {
|
||||
var k APIKey
|
||||
var role string
|
||||
if err := row.Scan(&k.ID, &k.Name, &role, &k.CreatedAt, &k.LastUsedAt, &k.RevokedAt); err != nil {
|
||||
return k, err
|
||||
}
|
||||
k.Role = Role(role)
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func (s *Store) getAPIKey(id int64) (APIKey, error) {
|
||||
k, err := scanKey(s.DB.QueryRow(keySelect+` WHERE id=?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return k, ErrNotFound
|
||||
}
|
||||
return k, err
|
||||
}
|
||||
|
||||
func (s *Store) ListAPIKeys() ([]APIKey, error) {
|
||||
rows, err := s.DB.Query(keySelect + ` ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []APIKey{}
|
||||
for rows.Next() {
|
||||
k, err := scanKey(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RevokeAPIKey(id int64) error {
|
||||
res, err := s.DB.Exec(`UPDATE api_keys SET revoked_at=? WHERE id=? AND revoked_at = ''`, now(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LookupAPIKey resolves a bearer secret to a principal. The legacy shared
|
||||
// token is accepted first, as an implicit admin key.
|
||||
func (s *Store) LookupAPIKey(secret string) (*Principal, error) {
|
||||
if secret == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if s.LegacyToken != "" && SecretEqual(secret, s.LegacyToken) {
|
||||
return &Principal{Kind: ActorAPIKey, Role: RoleAdmin, Name: "legacy-token"}, nil
|
||||
}
|
||||
var id int64
|
||||
var name, role, revoked string
|
||||
err := s.DB.QueryRow(`SELECT id, name, role, revoked_at FROM api_keys WHERE key_hash=?`,
|
||||
HashToken(secret)).Scan(&id, &name, &role, &revoked)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if revoked != "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
s.touchKey(id)
|
||||
return &Principal{Kind: ActorAPIKey, Role: Role(role), Name: name}, nil
|
||||
}
|
||||
|
||||
// touchKey records last_used_at at most once a minute per key, so a polling
|
||||
// agent does not serialise a write behind every request.
|
||||
func (s *Store) touchKey(id int64) {
|
||||
s.mu.Lock()
|
||||
last, ok := s.keyTouch[id]
|
||||
if ok && time.Since(last) < time.Minute {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.keyTouch[id] = time.Now()
|
||||
s.mu.Unlock()
|
||||
_, _ = s.DB.Exec(`UPDATE api_keys SET last_used_at=? WHERE id=?`, now(), id)
|
||||
}
|
||||
|
||||
// ---------- audit ----------
|
||||
|
||||
// maxAuditBuffer bounds the in-memory audit queue so a wedged flush loop
|
||||
// cannot grow without limit.
|
||||
const maxAuditBuffer = 10_000
|
||||
|
||||
// Audit buffers one audit row. Call FlushAudit to persist.
|
||||
func (s *Store) Audit(e AuditEntry) {
|
||||
if e.At == "" {
|
||||
e.At = now()
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.auditBuf) >= maxAuditBuffer {
|
||||
s.auditBuf = s.auditBuf[1:]
|
||||
}
|
||||
s.auditBuf = append(s.auditBuf, e)
|
||||
}
|
||||
|
||||
// FlushAudit writes buffered audit rows in one transaction.
|
||||
func (s *Store) FlushAudit() error {
|
||||
s.mu.Lock()
|
||||
batch := s.auditBuf
|
||||
s.auditBuf = nil
|
||||
s.mu.Unlock()
|
||||
if len(batch) == 0 {
|
||||
return nil
|
||||
}
|
||||
requeue := func() {
|
||||
s.mu.Lock()
|
||||
s.auditBuf = append(batch, s.auditBuf...)
|
||||
if len(s.auditBuf) > maxAuditBuffer {
|
||||
s.auditBuf = s.auditBuf[len(s.auditBuf)-maxAuditBuffer:]
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
stmt, err := tx.Prepare(`INSERT INTO audit_log(at,actor,actor_kind,ip,method,path,status,note) VALUES(?,?,?,?,?,?,?,?)`)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
defer stmt.Close()
|
||||
for _, e := range batch {
|
||||
if _, err := stmt.Exec(e.At, e.Actor, string(e.ActorKind), e.IP, e.Method, e.Path, e.Status, truncate(e.Note, 500)); err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunMaintenance flushes audit rows, expires sessions and prunes old audit
|
||||
// history until stop is closed.
|
||||
func (s *Store) RunMaintenance(stop <-chan struct{}, retain time.Duration) {
|
||||
t := time.NewTicker(5 * time.Second)
|
||||
defer t.Stop()
|
||||
prune := time.NewTicker(1 * time.Hour)
|
||||
defer prune.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
_ = s.FlushAudit()
|
||||
return
|
||||
case <-t.C:
|
||||
_ = s.FlushAudit()
|
||||
_, _ = s.ExpireSessions()
|
||||
case <-prune.C:
|
||||
if retain > 0 {
|
||||
cutoff := time.Now().UTC().Add(-retain).Format(time.RFC3339)
|
||||
_, _ = s.DB.Exec(`DELETE FROM audit_log WHERE at < ?`, cutoff)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) ListAudit(limit int, actor string) ([]AuditEntry, error) {
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
q := `SELECT id,at,actor,actor_kind,ip,method,path,status,note FROM audit_log`
|
||||
args := []any{}
|
||||
if strings.TrimSpace(actor) != "" {
|
||||
q += ` WHERE actor = ?`
|
||||
args = append(args, strings.TrimSpace(actor))
|
||||
}
|
||||
q += ` ORDER BY id DESC LIMIT ?`
|
||||
args = append(args, limit)
|
||||
rows, err := s.DB.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AuditEntry{}
|
||||
for rows.Next() {
|
||||
var e AuditEntry
|
||||
var kind string
|
||||
if err := rows.Scan(&e.ID, &e.At, &e.Actor, &kind, &e.IP, &e.Method, &e.Path, &e.Status, &e.Note); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.ActorKind = ActorKind(kind)
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue