Null-DRM-Official/apps/streamd/internal/auth/auth_test.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

548 lines
16 KiB
Go

package auth
import (
"database/sql"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"streamd/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")
}
}
}