Files
CollabTable/backend/server.go
T

504 lines
20 KiB
Go
Raw Normal View History

package main
import (
"compress/gzip"
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"path"
"runtime"
"strings"
"time"
_ "github.com/joho/godotenv/autoload"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
2026-09-23 04:56:42 +02:00
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
// The SvelteKit build is copied here by the Docker builder before go build.
// Keeping a tiny tracked placeholder in web/ also lets go test run from a
// checkout before the dashboard has been built.
//
//go:embed all:web
var webFS embed.FS
type Server struct {
db *DB
auth *sharedauth.Service
startTime time.Time
internalServiceSecret string
coreConfig *coreconfig.Store
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() {
if len(os.Args) > 1 && os.Args[1] == "remap-users" {
os.Exit(runRemapUsers(os.Args[2:], os.Stdout))
}
port := envOrDefault("PORT", "8080")
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if connectionString == "" {
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
os.Exit(1)
}
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()
database, err := connectWithRetry(ctx, connectionString)
if err != nil {
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
os.Exit(1)
}
defer database.close()
go database.pruneExpiredSessions(ctx)
go database.cleanupNotifications(ctx)
// AuthGuard integration has three states now (see auth.go's top-of-file
// doc comment and sharedauth's own "Auth-disabled mode" section): an
// AUTHGUARD_URL set is used immediately; unset with AUTH_DISABLED
// unset/false is "pending" (fully gated, failing closed until
// ProjectConfigurator's push arrives); AUTH_DISABLED=true is an explicit
// opt-out where every request is treated as already authenticated, with
// nothing gated -- for local development or a standalone deployment, not
// a degraded fallback.
authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL"))
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
switch {
case authDisabled:
fmt.Println("auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
case authGuardURL != "":
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
default:
fmt.Println("auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
}
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
// coreConfig holds the AuthGuard/CarrierNode URLs ProjectConfigurator pushes once this project
// is registered there (PUT /api/core-services/internal, see registerRoutes) -- AUTHGUARD_URL and
// CARRIERNODE_URL above/below are only the bootstrap fallback used until the first push arrives.
// See Core/ProjectConfigurator/README.md's "Pushing core service info to other projects".
// auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds
// internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
coreConfig.OnUpdate(func(info coreconfig.Info) {
if info.AuthGuardURL != "" {
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
}
})
server := &Server{
db: database,
auth: auth,
startTime: time.Now(),
internalServiceSecret: internalServiceSecret,
coreConfig: coreConfig,
syncSlots: make(chan struct{}, maxConcurrentSyncs),
trustedProxies: trustedProxies,
}
webRoot, err := fs.Sub(webFS, "web")
if err != nil {
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
os.Exit(1)
}
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: handler,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
}
fmt.Printf("CollabTable Go server listening on :%s\n", port)
fmt.Printf("Database: PostgreSQL (pgx)\n")
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
os.Exit(1)
}
}
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
2026-09-23 04:56:42 +02:00
retryOptions := sharedpostgres.StartupRetryOptionsFromEnv()
for attempt := int64(1); ; attempt++ {
database, err := connectDB(ctx, connectionString)
if err == nil {
if schemaErr := database.initSchema(ctx); schemaErr == nil {
if attempt > 1 {
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
}
return database, nil
} else {
database.close()
err = schemaErr
}
}
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
2026-09-23 04:56:42 +02:00
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
return nil, err
}
2026-09-23 04:56:42 +02:00
fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval)
select {
case <-ctx.Done():
return nil, ctx.Err()
2026-09-23 04:56:42 +02:00
case <-time.After(retryOptions.Interval):
}
}
}
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)
// X-Internal-Auth-gated, not browser-session-gated -- ProjectConfigurator calls this directly
// 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.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)))
// 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", 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.
api := func(handler http.Handler) http.Handler {
return requireAPIToken(s.db)(handler)
}
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
mux.Handle("GET /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
mux.Handle("PUT /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
mux.Handle("DELETE /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
mux.Handle("POST /api/fields", api(http.HandlerFunc(s.handleFieldCollection)))
mux.Handle("GET /api/fields/list/{listId}", api(http.HandlerFunc(s.handleFieldsForList)))
mux.Handle("PUT /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
mux.Handle("DELETE /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
mux.Handle("POST /api/items", api(http.HandlerFunc(s.handleItemCollection)))
mux.Handle("POST /api/items/values", api(http.HandlerFunc(s.handleItemValueCollection)))
// These item paths overlap under the Go ServeMux pattern rules (for
// example /items/list/values), so dispatch the legacy subroutes in one
// prefix handler while keeping /items/values exact for POST.
mux.Handle("/api/items/", api(http.HandlerFunc(s.handleItemPath)))
mux.Handle("POST /api/sync", api(http.HandlerFunc(s.handleSync)))
mux.Handle("GET /api/notifications/poll", api(http.HandlerFunc(s.handleNotificationPoll)))
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
// are protected by the browser session.
mux.Handle("GET /api/tech-stack", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTechStack)))
mux.Handle("GET /web/data", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleWebData)))
mux.Handle("/", spaFileServer(webRoot))
}
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"status": "ok",
"timestamp": time.Now().UnixMilli(),
})
}
// handleInfo is CollabTable's self-describe endpoint: ProjectConfigurator's Projects workspace
// calls this (via its server-side /api/discover-service proxy) when an operator adds CollabTable
// by URL, to populate its display name, navigable tabs, and mount path types (none - CollabTable
// keeps all of its data in PostgreSQL, with no shared file mounts of its own) without any manual
// entry.
func (s *Server) handleInfo(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"name": "CollabTable",
"tabs": []map[string]string{
{"key": "overview", "label": "Overview", "token": "/"},
},
"mountTypes": []string{},
})
}
func envOrDefault(name, fallback string) string {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
return fallback
}
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
}
writeJSONError(w, http.StatusBadRequest, message)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeJSONError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{
"error": message,
"message": message,
})
}
// 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().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 {
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
}
next.ServeHTTP(w, r)
})
}
// 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) {
data, err := fs.ReadFile(root, "index.html")
if err != nil {
http.NotFound(w, r)
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)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The path is cleaned as a rooted URL path, and it is only read from webRoot,
// an embed.FS, so it cannot name a file outside the embedded build.
// nosemgrep: go.lang.security.filepath-clean-misuse.filepath-clean-misuse
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
serveIndex(w, r)
return
}
if _, err := fs.Stat(root, cleanPath); err != nil {
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)
})
}
type dependency struct {
Name string `json:"name"`
Version string `json:"version"`
}
type techStackResponse struct {
AppVersion string `json:"appVersion"`
Stack []stackEntry `json:"stack"`
}
type stackEntry struct {
Label string `json:"label"`
Value string `json:"value"`
}
func (s *Server) handleTechStack(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, techStackResponse{
AppVersion: envOrDefault("APP_VERSION", "dev"),
Stack: []stackEntry{
{Label: "Runtime", Value: "Go " + runtime.Version()},
{Label: "Web Framework", Value: "net/http"},
{Label: "Database", Value: "PostgreSQL (pgx/v5)"},
},
})
}