Fix critical and high audit findings

Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE):
- P-001 · Dashboard re-downloads the entire dataset every 5 seconds

Re-synced the vendored shared/ snapshot from shared commit 199a5ef.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Haiku 5.5 committed 2026-10-19 07:48:07 +00:00
1 parent 7dd0d34383
commit a84a36349b
31 files changed
+653 -6055

No files matched your search

+57 -10
View File
@@ -85,16 +85,16 @@ func (c *Core) Mount(r chi.Router) {
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
r.With(c.auth.Optional).Put("/sync", c.putSyncState)
r.With(c.auth.Require).Put("/sync", c.putSyncState)
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
r.Get("/media/stream", c.streamMediaByQuery)
r.Head("/media/stream", c.streamMediaByQuery)
r.Get("/media/thumb", c.thumbnailMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Get("/media/stream", c.streamMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Head("/media/stream", c.streamMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Get("/media/thumb", c.thumbnailMediaByQuery)
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
@@ -132,10 +132,15 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "clientId is required")
return
}
mediaID, ok := syncScalar(input["mediaId"])
if !ok {
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
state := map[string]any{
"sessionId": sessionID,
"mediaId": input["mediaId"],
"mediaId": mediaID,
"timeMs": syncInt(input, "timeMs", 0),
"paused": syncBool(input, "paused"),
"fps": syncFPS(input),
@@ -144,7 +149,12 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
if value, ok := input["playAt"]; ok {
state["playAt"] = value
playAt, valid := syncScalar(value)
if !valid {
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
return
}
state["playAt"] = playAt
}
c.sync.SetHTTPState(sessionID, state)
c.sync.Broadcast(sessionID)
@@ -179,7 +189,7 @@ func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
}
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
record, err := c.findMedia(r.Context(), identifier)
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
if err != nil {
writeError(w, http.StatusNotFound, "media not found")
return
@@ -197,6 +207,11 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusBadRequest, "invalid media id")
return
}
includeHidden := canSeeHidden(r)
if !includeHidden && c.isHiddenMedia(r.Context(), id) {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
return
@@ -216,7 +231,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
return
}
}
record, err := c.findMedia(r.Context(), id)
record, err := c.findMedia(r.Context(), id, includeHidden)
if err != nil || !isImagePath(record.FilePath) {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
@@ -723,7 +738,25 @@ func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"user": user})
}
func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, error) {
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
// been hidden (active = FALSE). Everyone else gets hidden media as not found.
func canSeeHidden(r *http.Request) bool {
return sharedauth.IsAdmin(sharedauth.UserFromContext(r.Context()))
}
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
// error counts as hidden, so a database fault never exposes hidden media.
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool
err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
strings.TrimSpace(identifier)).Scan(&hidden)
return err != nil || hidden
}
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
// when includeHidden is set.
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
identifier = strings.TrimSpace(identifier)
var record MediaRecord
row := c.db.QueryRow(ctx, `
@@ -732,7 +765,7 @@ func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, e
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
FROM media WHERE media_key=$1 OR CAST(id AS TEXT)=$1 LIMIT 1`, identifier)
FROM media WHERE (media_key=$1 OR CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden)
var title, description string
var width, height int
var duration, size int64
@@ -1084,6 +1117,20 @@ func syncBool(message map[string]any, key string) bool {
return value
}
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
// shared session state.
func syncScalar(value any) (any, bool) {
switch typed := value.(type) {
case nil, float64:
return typed, true
case string:
return boundedSyncString(typed), true
default:
return nil, false
}
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok {
+164
View File
@@ -0,0 +1,164 @@
package mediacore
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
// exercised without a database.
type loginRequiredStore struct{}
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
// loginOffStore is loginRequiredStore with login switched off for the whole application.
type loginOffStore struct{ loginRequiredStore }
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
// TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and
// thumbnail routes are refused when login is required, before any database lookup or CarrierNode
// call. The Core in this test has no database and no CarrierNode client, so reaching either would
// panic.
func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
for _, request := range []struct{ method, target string }{
{http.MethodGet, "/media/stream?mediaKey=1"},
{http.MethodHead, "/media/stream?mediaKey=1"},
{http.MethodGet, "/media/thumb?mediaKey=1"},
} {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
if response.Code != http.StatusUnauthorized {
t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized)
}
}
}
// TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes
// use: with login disabled an anonymous request reaches the handler, as it does for the rest of
// the application. The handler here is a stub, so no database or CarrierNode call is made.
func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) {
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject")
reached := false
gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reached = true
}))
for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} {
reached = false
response := httptest.NewRecorder()
gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
if !reached || response.Code != http.StatusOK {
t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code)
}
}
}
// newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a
// test can act as a viewer, a moderator or an admin without a database.
func newRoleAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
}))
t.Cleanup(server.Close)
return server
}
// TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all.
// Anonymous callers and viewers may not; moderators and admins may. With login off every caller
// is the placeholder superadmin, as for the rest of the application. The active = FALSE filter
// itself needs a database and is not exercised here.
func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
guard := newRoleAuthGuard(t)
login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject")
for _, tc := range []struct {
name string
auth *sharedauth.Service
token string
want string
}{
{"anonymous with login required", login, "", "false"},
{"viewer", login, "viewer-token", "false"},
{"moderator", login, "moderator-token", "true"},
{"admin", login, "admin-token", "true"},
{"anonymous with login off", loginOff, "", "true"},
} {
router := chi.NewRouter()
router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, canSeeHidden(r))
})
request := httptest.NewRequest(http.MethodGet, "/probe", nil)
if tc.token != "" {
request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token})
}
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if got := response.Body.String(); got != tc.want {
t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want)
}
}
}
// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change
// shared playback state. The Core has no sync hub, so reaching the handler would panic.
func TestSyncWriteRequiresLogin(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`))
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized {
t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized)
}
}
// TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and
// bounded strings, so objects, arrays and booleans are never stored as session state.
func TestSyncScalarKeepsOnlyScalars(t *testing.T) {
if value, ok := syncScalar(nil); !ok || value != nil {
t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok)
}
if value, ok := syncScalar(float64(7)); !ok || value != float64(7) {
t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok)
}
if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" {
t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok)
}
long, ok := syncScalar(strings.Repeat("x", 500))
if text, isText := long.(string); !ok || !isText || len(text) != 128 {
t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok)
}
for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} {
if _, ok := syncScalar(refused); ok {
t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused)
}
}
}
+29 -5
View File
@@ -31,8 +31,9 @@ import (
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
)
type peer struct {
@@ -73,10 +74,15 @@ func NewHub() *Hub {
}
}
func (h *Hub) add(p *peer) {
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
func (h *Hub) add(p *peer) bool {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.peers) >= maxSyncConnections {
return false
}
h.peers[p] = struct{}{}
h.mu.Unlock()
return true
}
func (h *Hub) remove(p *peer) string {
@@ -300,7 +306,10 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
}
h.add(p)
if !h.add(p) {
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
return
}
defer func() {
sessionID := h.remove(p)
_ = conn.Close(websocket.StatusNormalClosure, "")
@@ -453,6 +462,9 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
h.capturedAtMs[sessionID] = captured
}
trimSessionMap(h.playAt)
trimSessionMap(h.playAtLocalMs)
trimSessionMap(h.capturedAtMs)
if toClientID == "" {
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
@@ -571,6 +583,18 @@ func cloneMap(value map[string]any) map[string]any {
return result
}
// trimSessionMap keeps a per-session map within maxSyncSessions by dropping entries, the same
// bound the states map uses. Session IDs come from clients, so without it each map would grow
// for every ID ever seen.
func trimSessionMap[V any](values map[string]V) {
for len(values) > maxSyncSessions {
for key := range values {
delete(values, key)
break
}
}
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
@@ -0,0 +1,46 @@
package syncsocket
import (
"fmt"
"testing"
)
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
// per-session timing maps past maxSyncSessions.
func TestSessionTimingMapsStayBounded(t *testing.T) {
hub := NewHub()
p := &peer{clientID: "client-1"}
for i := 0; i < maxSyncSessions+100; i++ {
hub.handleSyncUpdate(p, map[string]any{
"clientId": "client-1",
"sessionId": fmt.Sprintf("session-%d", i),
"paused": false,
"playAt": "2026-10-19T10:00:00Z",
"playAtLocalMs": float64(1),
"capturedAtLocalMs": float64(1),
})
}
if n := len(hub.playAt); n > maxSyncSessions {
t.Errorf("playAt holds %d sessions, want at most %d", n, maxSyncSessions)
}
if n := len(hub.playAtLocalMs); n > maxSyncSessions {
t.Errorf("playAtLocalMs holds %d sessions, want at most %d", n, maxSyncSessions)
}
if n := len(hub.capturedAtMs); n > maxSyncSessions {
t.Errorf("capturedAtMs holds %d sessions, want at most %d", n, maxSyncSessions)
}
}
// TestHubRefusesPeersBeyondTheConnectionCap checks that the hub stops registering connections
// once it holds maxSyncConnections peers.
func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
hub := NewHub()
for i := 0; i < maxSyncConnections; i++ {
if !hub.add(&peer{}) {
t.Fatalf("add refused peer %d, below the cap", i)
}
}
if hub.add(&peer{}) {
t.Fatal("add accepted a peer beyond maxSyncConnections")
}
}