fix: address performance and security findings
Lint / Lint (push) Successful in 26s
Tests / Go backend (push) Failing after 1m14s
Tests / Dashboard checks (push) Successful in 52s
Docker / Docker Build & Push (push) Successful in 3m41s

- Add PostgreSQL-backed backend and frontend tests to CI
- Harden Android API logging and disable app backups
- Update the performance report with resolved findings
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:16:08 +00:00
1 parent a84a36349b
commit 937f51b4fb
35 files changed
+2566 -332

No files matched your search

+187 -24
View File
@@ -1,12 +1,14 @@
package main
import (
"compress/gzip"
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"path"
@@ -36,8 +38,19 @@ type Server struct {
internalServiceSecret string
coreConfig *coreconfig.Store
carrierNode *carriernodeclient.Client
syncSlots chan struct{}
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
trustedProxies []*net.IPNet
}
// Request body limits per route. Sync pushes can carry many rows at once, so
// they keep the larger limit; single-entity writes get the smaller one.
const (
jsonBodyLimit = 2 << 20
syncBodyLimit = 50 << 20
)
func main() {
port := envOrDefault("PORT", "8080")
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
@@ -47,6 +60,19 @@ func main() {
}
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
if production && len(trustedProxies) == 0 {
fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -104,6 +130,8 @@ func main() {
internalServiceSecret: internalServiceSecret,
coreConfig: coreConfig,
carrierNode: carrierNode,
syncSlots: make(chan struct{}, maxConcurrentSyncs),
trustedProxies: trustedProxies,
}
webRoot, err := fs.Sub(webFS, "web")
@@ -115,9 +143,17 @@ func main() {
mux := http.NewServeMux()
server.registerRoutes(mux, webRoot)
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
if production {
handler = withHTTPSRequired(trustedProxies, handler)
fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
} else {
fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
}
httpServer := &http.Server{
Addr: ":" + port,
Handler: withCORS(mux),
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
@@ -163,6 +199,10 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
}
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// Budgets for setup, login, TOTP and token regeneration, keyed by client IP
// (and by account for failed logins). See ratelimit.go.
limits := newAuthRateLimits(s.trustedProxies)
// Health and auth bootstrap routes are intentionally public.
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /api/info", s.handleInfo)
@@ -170,22 +210,23 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
mux.HandleFunc("POST /api/auth/setup", s.auth.Signup)
mux.HandleFunc("POST /api/auth/login", s.auth.Login)
mux.Handle("POST /api/auth/setup", limits.perClient(http.HandlerFunc(s.auth.Signup)))
mux.Handle("POST /api/auth/login", limits.login(http.HandlerFunc(s.auth.Login)))
mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret))
mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout)))
mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe)))
mux.Handle("GET /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUsers)))
mux.Handle("POST /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedCreateUser)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedDeleteUser)))
mux.Handle("GET /api/auth/totp/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus)))
mux.Handle("POST /api/auth/totp/setup", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate)))
mux.Handle("POST /api/auth/totp/enable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify)))
mux.Handle("POST /api/auth/totp/disable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable)))
// Managed-user routes check the caller's role here, not only in AuthGuard.
mux.Handle("GET /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUsers)))
mux.Handle("POST /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedCreateUser)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedDeleteUser)))
mux.Handle("GET /api/auth/totp/status", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus))))
mux.Handle("POST /api/auth/totp/setup", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate))))
mux.Handle("POST /api/auth/totp/enable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify))))
mux.Handle("POST /api/auth/totp/disable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable))))
mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus)))
mux.Handle("POST /api/auth/token/regenerate", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate)))
mux.Handle("POST /api/auth/token/regenerate", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate))))
// Sync/collaboration API routes use a long-lived bearer token shared by the
// user's devices. This is deliberately separate from browser sessions.
@@ -250,12 +291,24 @@ func envOrDefault(name, fallback string) string {
return fallback
}
func decodeJSON(r *http.Request, target any) error {
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
if err := decoder.Decode(target); err != nil {
return err
func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error {
return decodeJSONLimit(w, r, target, jsonBodyLimit)
}
// decodeJSONLimit decodes a body of at most limit bytes. An oversized body fails
// with *http.MaxBytesError, which writeDecodeError turns into 413.
func decodeJSONLimit(w http.ResponseWriter, r *http.Request, target any, limit int64) error {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
return decoder.Decode(target)
}
func writeDecodeError(w http.ResponseWriter, err error, message string) {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
writeJSONError(w, http.StatusRequestEntityTooLarge, "Request body too large")
return
}
return nil
writeJSONError(w, http.StatusBadRequest, message)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
@@ -271,17 +324,42 @@ func writeJSONError(w http.ResponseWriter, status int, message string) {
})
}
func withCORS(next http.Handler) http.Handler {
// allowedOriginsFromEnv reads ALLOWED_ORIGINS, a comma-separated list of browser
// origins that may call the API cross-origin with credentials. It is empty by
// default: the dashboard is same-origin and needs no CORS headers.
func allowedOriginsFromEnv() []string {
var origins []string
for _, origin := range strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",") {
if origin = strings.TrimSpace(origin); origin != "" {
origins = append(origins, origin)
}
}
return origins
}
// withCORS sends CORS headers only for origins in allowedOrigins. Any other
// origin gets no Access-Control-Allow-Origin and no credentials header, so a
// browser refuses its cross-origin reads.
func withCORS(allowedOrigins []string, next http.Handler) http.Handler {
allowed := make(map[string]bool, len(allowedOrigins))
for _, origin := range allowedOrigins {
allowed[origin] = true
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
permitted := origin != "" && allowed[origin]
if permitted {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
if permitted {
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
}
w.WriteHeader(http.StatusNoContent)
return
}
@@ -289,6 +367,82 @@ func withCORS(next http.Handler) http.Handler {
})
}
// withSecurityHeaders sets headers that stop the dashboard and API from being
// framed (clickjacking) or MIME-sniffed. The dashboard page replaces the
// Content-Security-Policy with the full one from dashboardCSP. HSTS is not set
// here: this process has no TLS, so the TLS proxy sets Strict-Transport-Security.
func withSecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
headers.Set("X-Content-Type-Options", "nosniff")
headers.Set("X-Frame-Options", "DENY")
headers.Set("Content-Security-Policy", "frame-ancestors 'none'")
headers.Set("Referrer-Policy", "strict-origin-when-cross-origin")
next.ServeHTTP(w, r)
})
}
// withHTTPSRequired is the PRODUCTION=true profile: a request that did not
// arrive over TLS, directly or through a trusted proxy, gets 403. The health
// probe is exempt so local container checks keep working.
func withHTTPSRequired(trusted []*net.IPNet, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health" || requestIsHTTPS(r, trusted) {
next.ServeHTTP(w, r)
return
}
writeJSONError(w, http.StatusForbidden, "HTTPS is required on this server")
})
}
// gzipResponseWriter compresses a response body when the client accepts gzip.
// Responses that carry no body (204, 304) are passed through unchanged.
type gzipResponseWriter struct {
http.ResponseWriter
gzipWriter *gzip.Writer
wroteHeader bool
}
func (w *gzipResponseWriter) WriteHeader(status int) {
if w.wroteHeader {
return
}
w.wroteHeader = true
// Partial (206) bodies are left alone: a byte range of the plain file is not a gzip stream.
if status != http.StatusNoContent && status != http.StatusNotModified && status != http.StatusPartialContent {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Del("Content-Length")
w.gzipWriter = gzip.NewWriter(w.ResponseWriter)
}
w.ResponseWriter.WriteHeader(status)
}
func (w *gzipResponseWriter) Write(p []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
if w.gzipWriter == nil {
return w.ResponseWriter.Write(p)
}
return w.gzipWriter.Write(p)
}
// withGzip compresses responses for clients that send Accept-Encoding: gzip.
func withGzip(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Encoding")
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
compressed := &gzipResponseWriter{ResponseWriter: w}
next.ServeHTTP(compressed, r)
if compressed.gzipWriter != nil {
_ = compressed.gzipWriter.Close()
}
})
}
func spaFileServer(root fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(root))
serveIndex := func(w http.ResponseWriter, r *http.Request) {
@@ -298,6 +452,8 @@ func spaFileServer(root fs.FS) http.Handler {
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Content-Security-Policy", dashboardCSP(data))
_, _ = w.Write(data)
}
@@ -311,6 +467,13 @@ func spaFileServer(root fs.FS) http.Handler {
serveIndex(w, r)
return
}
// SvelteKit names its content-hashed bundle files under _app/immutable/, so
// those can be cached for a long time. Everything else is revalidated.
if strings.HasPrefix(cleanPath, "_app/immutable/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
w.Header().Set("Cache-Control", "no-cache")
}
fileServer.ServeHTTP(w, r)
})
}