Files
beacon-server/internal/api/middleware/runtime_config.go
T
MrAlders0n 03f66d1ae4 Database pools by workload, plan router, observe-only guards, metrics (rest of #237) (#238)
* feat(db): five pgx pools with fixed session settings and Prometheus tracing

* feat(guards): per-family observe/enforce guards with client slots, deadlines and a shadow budget

* fix(guards): attribute only guard deadlines and classify like the handlers

* feat(db): route API statements by sqlc name; class C always unnamed

* feat(admin): statement statistics by sqlc name; create pg_stat_statements where allowed

* fix(db): skip pg_stat_statements when no schema is creatable

* feat(background): index health against post-rebuild baselines, Postgres activity, job and ingest metrics

* feat: separate API, ingest and maintenance stores; guards on the public API; metrics listener

* fix(db): keep ingest writes waiting, size the ingest pool to the host, tidy

* test(db): give the statements probe a query id of its own
2026-10-19 07:52:51 -04:00

195 lines
6.1 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"errors"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"unicode"
"github.com/MeshCore-Beacon/beacon-server/internal/api"
"github.com/MeshCore-Beacon/beacon-server/internal/guards"
"github.com/go-chi/cors"
)
var ErrInvalidOrigins = errors.New("allowed_origins must contain 1-32 ASCII HTTP(S) origins (at most 512 bytes each), or a sole *; paths, credentials, queries and control characters are not allowed")
// ErrGuardsNotConfigured is returned for a guards update on a router without a guard.
var ErrGuardsNotConfigured = errors.New("guards are not configured")
type runtimePolicy struct {
config api.AdminConfig
handler http.Handler
}
// RuntimeConfig owns one router's CORS handler and its nonsecret config view.
// Published policies are immutable. Updates are runtime-only, never persisted.
type RuntimeConfig struct {
mu sync.Mutex
current atomic.Pointer[runtimePolicy]
next http.Handler
exposedHeaders []string
guard *guards.Guard // set once by BindGuards; its enforce list changes only under mu
}
func NewRuntimeConfig(config api.AdminConfig, exposedHeaders []string) *RuntimeConfig {
s := &RuntimeConfig{exposedHeaders: slices.Clone(exposedHeaders)}
s.current.Store(&runtimePolicy{config: cloneAdminConfig(config)})
return s
}
// CORS is bound once as the outer middleware of its owning router.
func (s *RuntimeConfig) CORS(next http.Handler) http.Handler {
s.mu.Lock()
defer s.mu.Unlock()
if s.next != nil {
panic("runtime CORS already bound")
}
s.next = next
s.current.Store(s.policy(s.current.Load().config))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.current.Load().handler.ServeHTTP(w, r)
})
}
func (s *RuntimeConfig) Snapshot() api.AdminConfig {
return cloneAdminConfig(s.current.Load().config)
}
// BindGuards attaches the guard whose enforced families the admin config reports and updates.
// Call it once, before serving.
func (s *RuntimeConfig) BindGuards(g *guards.Guard, view api.AdminGuardsConfig) {
s.mu.Lock()
defer s.mu.Unlock()
if s.guard != nil {
panic("runtime guards already bound")
}
s.guard = g
config := cloneAdminConfig(s.current.Load().config)
view.Enforce = familyNames(g.Enforce())
config.Guards = &view
s.current.Store(s.policy(config))
}
func (s *RuntimeConfig) UpdateOrigins(origins []string) (api.AdminConfig, error) {
return s.Update(&origins, nil)
}
// UpdateGuards replaces the enforced guard families; an empty list makes every family observe.
func (s *RuntimeConfig) UpdateGuards(enforce []string) (api.AdminConfig, error) {
return s.Update(nil, &enforce)
}
// Update replaces the CORS origins and/or the enforced guard families; a nil argument leaves
// that setting alone. Both are validated before either is applied, and both are published
// together, so a rejected update changes nothing.
func (s *RuntimeConfig) Update(origins, enforce *[]string) (api.AdminConfig, error) {
var validated []string
if origins != nil {
var err error
if validated, err = validateOrigins(*origins); err != nil {
return api.AdminConfig{}, err
}
}
var families []guards.Family
if enforce != nil {
var err error
if families, err = guards.ParseFamilies(*enforce); err != nil {
return api.AdminConfig{}, err
}
}
s.mu.Lock()
defer s.mu.Unlock()
if enforce != nil && s.guard == nil {
return api.AdminConfig{}, ErrGuardsNotConfigured
}
config := cloneAdminConfig(s.current.Load().config)
if origins != nil {
config.CORS.AllowedOrigins = validated
}
if enforce != nil {
s.guard.SetEnforce(families)
config.Guards.Enforce = familyNames(families)
}
s.current.Store(s.policy(config))
return cloneAdminConfig(config), nil
}
// familyNames returns the families as strings; never nil, so an empty list encodes as [].
func familyNames(fs []guards.Family) []string {
out := make([]string, 0, len(fs))
for _, f := range fs {
out = append(out, string(f))
}
return out
}
func (s *RuntimeConfig) policy(config api.AdminConfig) *runtimePolicy {
p := &runtimePolicy{config: config}
if s.next != nil {
p.handler = cors.Handler(cors.Options{
AllowedOrigins: slices.Clone(config.CORS.AllowedOrigins),
AllowedMethods: slices.Clone(config.CORS.AllowedMethods),
AllowedHeaders: slices.Clone(config.CORS.AllowedHeaders),
AllowCredentials: config.CORS.AllowCredentials, MaxAge: config.CORS.MaxAge,
ExposedHeaders: slices.Clone(s.exposedHeaders),
})(s.next)
}
return p
}
func cloneAdminConfig(config api.AdminConfig) api.AdminConfig {
config.CORS.AllowedOrigins = slices.Clone(config.CORS.AllowedOrigins)
config.CORS.AllowedMethods = slices.Clone(config.CORS.AllowedMethods)
config.CORS.AllowedHeaders = slices.Clone(config.CORS.AllowedHeaders)
if config.Guards != nil {
g := *config.Guards
g.Enforce = append([]string{}, g.Enforce...)
config.Guards = &g
}
return config
}
func validateOrigins(origins []string) ([]string, error) {
if len(origins) == 0 || len(origins) > 32 {
return nil, ErrInvalidOrigins
}
result := make([]string, len(origins))
for i, origin := range origins {
if len(origin) > 512 || strings.IndexFunc(origin, unicode.IsControl) >= 0 {
return nil, ErrInvalidOrigins
}
origin = strings.TrimSpace(origin)
if strings.IndexFunc(origin, func(r rune) bool { return r > unicode.MaxASCII }) >= 0 {
return nil, ErrInvalidOrigins
}
origin = strings.ToLower(origin)
if origin == "*" {
if len(origins) != 1 {
return nil, ErrInvalidOrigins
}
result[i] = origin
continue
}
u, err := url.Parse(origin)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.Contains(origin, "#") || strings.Count(u.Host, "*") > 1 || strings.Contains(u.Host, "%") || strings.HasSuffix(u.Host, ":") {
return nil, ErrInvalidOrigins
}
if port := u.Port(); port != "" {
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return nil, ErrInvalidOrigins
}
}
result[i] = origin
}
return result, nil
}