Files
wild-central/internal/domains/manager.go
Paul Payne 60f3ca4a3a Security hardening: input validation, secrets protection, NATS auth
Config injection prevention:
- Add FQDN validation for domain names (RFC 1123) in Register/Update —
  rejects newlines, spaces, shell metacharacters that could inject into
  HAProxy/dnsmasq configs
- Add backend address validation (valid host:port format, valid IP or
  hostname, port 1-65535). DNS-only backends allow bare IPs.
- Add header key/value validation — keys must be HTTP token chars only,
  values must not contain newlines or NULs
- Add WireGuard peer name validation (alphanumeric + hyphens + underscores)
- Add defense-in-depth domain validation in certbot Provision()

Secrets protection:
- Remove ?raw=true bypass on GET /api/v1/secrets — secrets are now always
  redacted in API responses regardless of query parameters
- Update test to verify redaction cannot be bypassed

NATS authentication:
- Generate random auth token on first startup, store in secrets.yaml
- Pass token to embedded NATS server via Authorization option
- Internal client connects with the same token
- External NATS clients (Wild Cloud) must now authenticate

Security headers:
- Add X-Content-Type-Options: nosniff
- Add X-Frame-Options: DENY
- Add Cache-Control: no-store
2026-07-14 12:38:17 +00:00

484 lines
14 KiB
Go

// Package domains manages domain registrations from Wild Cloud, Wild Works,
// and manual entries. Domains register with Central to get DNS, gateway
// routing, TLS certificates, and optional public exposure via DDNS.
//
// Each registration is keyed by its domain — one registration per domain.
// Central registers its own UI domain here on startup (source: "central").
package domains
import (
"fmt"
"log/slog"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"gopkg.in/yaml.v3"
"github.com/wild-cloud/wild-central/internal/storage"
)
// BackendType describes how the gateway handles traffic for this domain.
type BackendType string
const (
BackendTCPPassthrough BackendType = "tcp-passthrough" // L4 SNI passthrough (k8s)
BackendHTTP BackendType = "http" // L7 HTTP reverse proxy
BackendDNSOnly BackendType = "dns-only" // DNS resolution only, no gateway
)
// TLSMode describes how TLS is handled for the domain.
type TLSMode string
const (
TLSTerminate TLSMode = "terminate" // Central terminates TLS
TLSPassthrough TLSMode = "passthrough" // Backend handles TLS (k8s traefik)
TLSNone TLSMode = "none" // No TLS (dns-only)
)
// Backend describes the target for a domain.
type Backend struct {
Address string `yaml:"address" json:"address"` // host:port
Type BackendType `yaml:"type" json:"type"` // tcp-passthrough or http
Health string `yaml:"health,omitempty" json:"health,omitempty"`
}
// HeaderConfig describes custom request/response headers for L7 HTTP domains.
type HeaderConfig struct {
Request map[string]string `yaml:"request,omitempty" json:"request,omitempty"`
Response map[string]string `yaml:"response,omitempty" json:"response,omitempty"`
}
// Route describes one path→backend mapping within a domain.
// Routes are evaluated in order — first match wins.
// A route with empty Paths is a catch-all (should be last).
type Route struct {
Paths []string `yaml:"paths,omitempty" json:"paths,omitempty"` // path prefixes (empty = catch-all)
Backend Backend `yaml:"backend" json:"backend"` // where to route
Headers *HeaderConfig `yaml:"headers,omitempty" json:"headers,omitempty"` // per-route headers
IPAllow []string `yaml:"ipAllow,omitempty" json:"ipAllow,omitempty"` // per-route CIDR whitelist
}
// AuthConfig describes forward-auth protection for an L7 HTTP domain.
// Only applicable to domains with backend type "http" (L7 TLS termination).
type AuthConfig struct {
Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
Policy string `yaml:"policy,omitempty" json:"policy,omitempty"` // one_factor, two_factor, bypass
}
// Domain represents a registered domain. The Domain field is the unique key.
//
// Simple domains use Backend directly. Multi-backend domains use Routes
// for path-based splitting (Backend is ignored when Routes is present).
type Domain struct {
DomainName string `yaml:"domain" json:"domain"` // FQDN — unique key
Source string `yaml:"source,omitempty" json:"source,omitempty"` // who registered: wild-cloud, wild-works, manual
Backend Backend `yaml:"backend,omitempty" json:"backend,omitempty"` // single backend (simple case)
Subdomains bool `yaml:"subdomains,omitempty" json:"subdomains,omitempty"` // also match *.domain
Public bool `yaml:"public,omitempty" json:"public,omitempty"` // true = internet-visible (DDNS + external), false = LAN only
TLS TLSMode `yaml:"tls,omitempty" json:"tls,omitempty"` // passthrough or terminate
Auth *AuthConfig `yaml:"auth,omitempty" json:"auth,omitempty"` // forward-auth protection (L7 HTTP only)
// Multi-backend path routing. When present, Backend is ignored.
// Each route maps path prefixes to a specific backend with its own L7 options.
Routes []Route `yaml:"routes,omitempty" json:"routes,omitempty"`
}
// EffectiveRoutes returns the domain's routing as a normalized []Route.
// Simple domains (Backend, no Routes) are wrapped in a single-element slice.
func (d *Domain) EffectiveRoutes() []Route {
if len(d.Routes) > 0 {
return d.Routes
}
if d.Backend.Address == "" {
return nil
}
return []Route{{Backend: d.Backend}}
}
// EffectiveBackendAddress returns the primary backend address for DNS/DDNS purposes.
// For multi-route domains, returns the first route's backend.
func (d *Domain) EffectiveBackendAddress() string {
if len(d.Routes) > 0 {
return d.Routes[0].Backend.Address
}
return d.Backend.Address
}
// EffectiveBackendType returns the backend type for routing decisions.
func (d *Domain) EffectiveBackendType() BackendType {
if len(d.Routes) > 0 {
return d.Routes[0].Backend.Type
}
return d.Backend.Type
}
// Manager handles domain registration CRUD and triggers networking reconciliation.
type Manager struct {
dataDir string
mu sync.RWMutex
reconcileFn func()
}
// NewManager creates a new domain registration manager.
func NewManager(dataDir string) *Manager {
domainsDir := filepath.Join(dataDir, "domains")
oldServicesDir := filepath.Join(dataDir, "services")
// Migrate from old "services" directory if it exists
if _, err := os.Stat(oldServicesDir); err == nil {
if _, err := os.Stat(domainsDir); os.IsNotExist(err) {
if err := os.Rename(oldServicesDir, domainsDir); err != nil {
slog.Warn("failed to migrate services dir to domains", "error", err)
} else {
slog.Info("migrated data directory", "from", oldServicesDir, "to", domainsDir)
}
}
}
if err := os.MkdirAll(domainsDir, 0755); err != nil {
slog.Warn("failed to create domains directory", "path", domainsDir, "error", err)
}
return &Manager{dataDir: dataDir}
}
// SetReconcileFn sets the function called after domain changes to update networking.
func (m *Manager) SetReconcileFn(fn func()) {
m.reconcileFn = fn
}
func (m *Manager) domainsDir() string {
return filepath.Join(m.dataDir, "domains")
}
// domainToFilename converts a domain to a filesystem-safe filename.
func domainToFilename(domain string) string {
return strings.ReplaceAll(domain, ".", "_") + ".yaml"
}
func (m *Manager) domainPath(domain string) string {
return filepath.Join(m.domainsDir(), domainToFilename(domain))
}
// isValidDomain checks that a string is a valid FQDN (RFC 1123) or wildcard domain.
// Prevents config injection via newlines, spaces, or shell metacharacters.
func isValidDomain(s string) bool {
if len(s) == 0 || len(s) > 253 {
return false
}
for _, label := range strings.Split(s, ".") {
if len(label) == 0 || len(label) > 63 {
return false
}
if label[0] == '-' || label[len(label)-1] == '-' {
return false
}
for _, c := range label {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '*') {
return false
}
}
}
return true
}
// isValidBackendAddress checks that an address is a valid host:port.
func isValidBackendAddress(addr string) bool {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return false
}
port, err := strconv.Atoi(portStr)
if err != nil || port < 1 || port > 65535 {
return false
}
if net.ParseIP(host) != nil {
return true
}
return isValidDomain(host)
}
// isValidHeaderName checks that a header name contains only HTTP token characters.
func isValidHeaderName(s string) bool {
if len(s) == 0 {
return false
}
for _, c := range s {
if c <= ' ' || c == ':' || c == '"' || c >= 0x7f {
return false
}
}
return true
}
// isValidHeaderValue checks that a header value contains no newlines or NULs.
func isValidHeaderValue(s string) bool {
return !strings.ContainsAny(s, "\r\n\x00")
}
// validateHeaders checks all header keys and values in a HeaderConfig.
func validateHeaders(h *HeaderConfig) error {
if h == nil {
return nil
}
for k, v := range h.Request {
if !isValidHeaderName(k) {
return fmt.Errorf("invalid request header name: %q", k)
}
if !isValidHeaderValue(v) {
return fmt.Errorf("invalid request header value for %q", k)
}
}
for k, v := range h.Response {
if !isValidHeaderName(k) {
return fmt.Errorf("invalid response header name: %q", k)
}
if !isValidHeaderValue(v) {
return fmt.Errorf("invalid response header value for %q", k)
}
}
return nil
}
// Register creates or updates a domain registration.
func (m *Manager) Register(dom Domain) error {
m.mu.Lock()
defer m.mu.Unlock()
if dom.DomainName == "" {
return fmt.Errorf("domain is required")
}
if !isValidDomain(dom.DomainName) {
return fmt.Errorf("invalid domain name: %q", dom.DomainName)
}
hasBackend := dom.Backend.Address != ""
hasRoutes := len(dom.Routes) > 0
if hasBackend && hasRoutes {
return fmt.Errorf("domain must use backend or routes, not both")
}
if !hasBackend && !hasRoutes {
return fmt.Errorf("backend address or routes required")
}
if hasRoutes {
for i, r := range dom.Routes {
if r.Backend.Address == "" {
return fmt.Errorf("route %d: backend address is required", i)
}
if !isValidBackendAddress(r.Backend.Address) {
return fmt.Errorf("route %d: invalid backend address: %q", i, r.Backend.Address)
}
if r.Backend.Type == "" {
return fmt.Errorf("route %d: backend type is required", i)
}
if err := validateHeaders(r.Headers); err != nil {
return fmt.Errorf("route %d: %w", i, err)
}
}
} else {
if dom.Backend.Type == "" {
return fmt.Errorf("backend type is required")
}
// dns-only backends may omit port (just an IP for resolution)
if dom.Backend.Type == BackendDNSOnly {
if net.ParseIP(dom.Backend.Address) == nil && !isValidBackendAddress(dom.Backend.Address) {
return fmt.Errorf("invalid backend address: %q", dom.Backend.Address)
}
} else if !isValidBackendAddress(dom.Backend.Address) {
return fmt.Errorf("invalid backend address: %q", dom.Backend.Address)
}
}
// Default TLS mode based on backend type
if dom.TLS == "" {
switch dom.EffectiveBackendType() {
case BackendTCPPassthrough:
dom.TLS = TLSPassthrough
case BackendDNSOnly:
dom.TLS = TLSNone
default:
dom.TLS = TLSTerminate
}
}
// Default source
if dom.Source == "" {
dom.Source = "manual"
}
data, err := yaml.Marshal(dom)
if err != nil {
return fmt.Errorf("marshaling domain: %w", err)
}
if err := storage.WriteFileAtomic(m.domainPath(dom.DomainName), data, 0644); err != nil {
return fmt.Errorf("writing domain file: %w", err)
}
slog.Info("domain registered", "domain", dom.DomainName, "public", dom.Public, "source", dom.Source, "subdomains", dom.Subdomains)
if m.reconcileFn != nil {
go func() {
defer func() {
if r := recover(); r != nil {
slog.Error("reconcile panicked", "error", r)
}
}()
m.reconcileFn()
}()
}
return nil
}
// Deregister removes a domain registration by domain name.
func (m *Manager) Deregister(domain string) error {
m.mu.Lock()
defer m.mu.Unlock()
path := m.domainPath(domain)
if _, err := os.Stat(path); os.IsNotExist(err) {
return fmt.Errorf("domain %q not found", domain)
}
if err := os.Remove(path); err != nil {
return fmt.Errorf("removing domain file: %w", err)
}
slog.Info("domain deregistered", "domain", domain)
if m.reconcileFn != nil {
go m.reconcileFn()
}
return nil
}
// Get retrieves a domain registration by domain name.
func (m *Manager) Get(domain string) (*Domain, error) {
m.mu.RLock()
defer m.mu.RUnlock()
data, err := os.ReadFile(m.domainPath(domain))
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("domain %q not found", domain)
}
return nil, fmt.Errorf("reading domain file: %w", err)
}
var dom Domain
if err := yaml.Unmarshal(data, &dom); err != nil {
return nil, fmt.Errorf("parsing domain file: %w", err)
}
return &dom, nil
}
// List returns all registered domains.
func (m *Manager) List() ([]Domain, error) {
m.mu.RLock()
defer m.mu.RUnlock()
entries, err := os.ReadDir(m.domainsDir())
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("reading domains directory: %w", err)
}
var doms []Domain
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".yaml" {
continue
}
data, err := os.ReadFile(filepath.Join(m.domainsDir(), entry.Name()))
if err != nil {
slog.Warn("failed to read domain file", "file", entry.Name(), "error", err)
continue
}
var dom Domain
if err := yaml.Unmarshal(data, &dom); err != nil {
slog.Warn("failed to parse domain file", "file", entry.Name(), "error", err)
continue
}
doms = append(doms, dom)
}
return doms, nil
}
// DeregisterBySource removes all registrations from a given source that match
// a backend address. Used by consumers to clean up before re-registering.
func (m *Manager) DeregisterBySource(source, backendAddress string) error {
doms, err := m.List()
if err != nil {
return err
}
for _, dom := range doms {
if dom.Source == source && dom.EffectiveBackendAddress() == backendAddress {
if err := m.Deregister(dom.DomainName); err != nil {
slog.Warn("failed to deregister domain during cleanup", "domain", dom.DomainName, "error", err)
}
}
}
return nil
}
// Update applies partial updates to a domain registration.
func (m *Manager) Update(domain string, updates map[string]any) error {
dom, err := m.Get(domain)
if err != nil {
return err
}
if public, ok := updates["public"].(bool); ok {
dom.Public = public
}
if sub, ok := updates["subdomains"].(bool); ok {
dom.Subdomains = sub
}
if backend, ok := updates["backend"].(map[string]any); ok {
if addr, ok := backend["address"].(string); ok {
dom.Backend.Address = addr
}
if typ, ok := backend["type"].(string); ok {
dom.Backend.Type = BackendType(typ)
}
if health, ok := backend["health"].(string); ok {
dom.Backend.Health = health
}
}
if tls, ok := updates["tls"].(string); ok {
dom.TLS = TLSMode(tls)
}
if auth, ok := updates["auth"].(map[string]any); ok {
if dom.Auth == nil {
dom.Auth = &AuthConfig{}
}
if enabled, ok := auth["enabled"].(bool); ok {
dom.Auth.Enabled = enabled
}
if policy, ok := auth["policy"].(string); ok {
dom.Auth.Policy = policy
}
// Clear auth if disabled and no policy
if !dom.Auth.Enabled && dom.Auth.Policy == "" {
dom.Auth = nil
}
}
return m.Register(*dom)
}