services -> domains
This commit is contained in:
359
internal/domains/manager.go
Normal file
359
internal/domains/manager.go
Normal file
@@ -0,0 +1,359 @@
|
||||
// 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"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
// 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))
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
|
||||
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 r.Backend.Type == "" {
|
||||
return fmt.Errorf("route %d: backend type is required", i)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if dom.Backend.Type == "" {
|
||||
return fmt.Errorf("backend type is required")
|
||||
}
|
||||
}
|
||||
|
||||
// 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 := os.WriteFile(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)
|
||||
}
|
||||
|
||||
return m.Register(*dom)
|
||||
}
|
||||
605
internal/domains/manager_test.go
Normal file
605
internal/domains/manager_test.go
Normal file
@@ -0,0 +1,605 @@
|
||||
package domains
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegisterAndGet(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
dom := Domain{
|
||||
DomainName: "my-api.payne.io",
|
||||
Source: "wild-works",
|
||||
Backend: Backend{
|
||||
Address: "192.168.8.60:9001",
|
||||
Type: BackendHTTP,
|
||||
},
|
||||
}
|
||||
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
|
||||
got, err := mgr.Get("my-api.payne.io")
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
|
||||
if got.DomainName != "my-api.payne.io" {
|
||||
t.Errorf("expected domain my-api.payne.io, got %s", got.DomainName)
|
||||
}
|
||||
if got.Backend.Address != "192.168.8.60:9001" {
|
||||
t.Errorf("expected backend 192.168.8.60:9001, got %s", got.Backend.Address)
|
||||
}
|
||||
if got.TLS != TLSTerminate {
|
||||
t.Errorf("expected TLS terminate (default for http), got %s", got.TLS)
|
||||
}
|
||||
if got.Source != "wild-works" {
|
||||
t.Errorf("expected source wild-works, got %s", got.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterTCPPassthrough(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
dom := Domain{
|
||||
DomainName: "cloud.payne.io",
|
||||
Source: "wild-cloud",
|
||||
Backend: Backend{
|
||||
Address: "192.168.8.240:443",
|
||||
Type: BackendTCPPassthrough,
|
||||
},
|
||||
Subdomains: true,
|
||||
Public: true,
|
||||
}
|
||||
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
|
||||
got, err := mgr.Get("cloud.payne.io")
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
|
||||
if got.TLS != TLSPassthrough {
|
||||
t.Errorf("expected TLS passthrough for tcp-passthrough, got %s", got.TLS)
|
||||
}
|
||||
if !got.Subdomains {
|
||||
t.Error("expected subdomains=true")
|
||||
}
|
||||
if !got.Public {
|
||||
t.Error("expected public=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDomains(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
for _, domain := range []string{"a.example.com", "b.example.com", "c.example.com"} {
|
||||
if err := mgr.Register(Domain{
|
||||
DomainName: domain,
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
}); err != nil {
|
||||
t.Fatalf("Register %s failed: %v", domain, err)
|
||||
}
|
||||
}
|
||||
|
||||
doms, err := mgr.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(doms) != 3 {
|
||||
t.Errorf("expected 3 domains, got %d", len(doms))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeregister(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
if err := mgr.Register(Domain{
|
||||
DomainName: "temp.example.com",
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
}); err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
|
||||
if err := mgr.Deregister("temp.example.com"); err != nil {
|
||||
t.Fatalf("Deregister failed: %v", err)
|
||||
}
|
||||
|
||||
if _, err := mgr.Get("temp.example.com"); err == nil {
|
||||
t.Error("expected error after deregister, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeregisterBySource(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
// Register 3 domains from wild-cloud with same backend
|
||||
for _, domain := range []string{"cloud.payne.io", "internal.cloud.payne.io", "payne.io"} {
|
||||
mgr.Register(Domain{
|
||||
DomainName: domain,
|
||||
Source: "wild-cloud",
|
||||
Backend: Backend{Address: "192.168.8.240:443", Type: BackendTCPPassthrough},
|
||||
Public: true,
|
||||
})
|
||||
}
|
||||
// Register 1 domain from wild-works (different source)
|
||||
mgr.Register(Domain{
|
||||
DomainName: "my-api.payne.io",
|
||||
Source: "wild-works",
|
||||
Backend: Backend{Address: "127.0.0.1:9001", Type: BackendHTTP},
|
||||
})
|
||||
|
||||
// Deregister all wild-cloud domains with backend 192.168.8.240:443
|
||||
if err := mgr.DeregisterBySource("wild-cloud", "192.168.8.240:443"); err != nil {
|
||||
t.Fatalf("DeregisterBySource failed: %v", err)
|
||||
}
|
||||
|
||||
doms, _ := mgr.List()
|
||||
if len(doms) != 1 {
|
||||
t.Errorf("expected 1 remaining domain, got %d", len(doms))
|
||||
}
|
||||
if doms[0].DomainName != "my-api.payne.io" {
|
||||
t.Errorf("expected wild-works domain to remain, got %s", doms[0].DomainName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
mgr.Register(Domain{
|
||||
DomainName: "updatable.example.com",
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
})
|
||||
|
||||
if err := mgr.Update("updatable.example.com", map[string]any{
|
||||
"public": true,
|
||||
"subdomains": true,
|
||||
}); err != nil {
|
||||
t.Fatalf("Update failed: %v", err)
|
||||
}
|
||||
|
||||
got, _ := mgr.Get("updatable.example.com")
|
||||
if !got.Public {
|
||||
t.Error("expected public=true after update")
|
||||
}
|
||||
if !got.Subdomains {
|
||||
t.Error("expected subdomains=true after update")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterValidation(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
// Missing domain
|
||||
if err := mgr.Register(Domain{Backend: Backend{Address: "127.0.0.1:80", Type: BackendHTTP}}); err == nil {
|
||||
t.Error("expected error for missing domain")
|
||||
}
|
||||
|
||||
// Missing backend address
|
||||
if err := mgr.Register(Domain{DomainName: "x.com", Backend: Backend{Type: BackendHTTP}}); err == nil {
|
||||
t.Error("expected error for missing backend address")
|
||||
}
|
||||
|
||||
// Missing backend type
|
||||
if err := mgr.Register(Domain{DomainName: "x.com", Backend: Backend{Address: "127.0.0.1:80"}}); err == nil {
|
||||
t.Error("expected error for missing backend type")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultSource(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
mgr.Register(Domain{
|
||||
DomainName: "test.com",
|
||||
Backend: Backend{Address: "127.0.0.1:80", Type: BackendHTTP},
|
||||
})
|
||||
|
||||
got, _ := mgr.Get("test.com")
|
||||
if got.Source != "manual" {
|
||||
t.Errorf("expected default source 'manual', got %s", got.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterIdempotent(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
dom := Domain{
|
||||
DomainName: "idempotent.example.com",
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
}
|
||||
|
||||
// Register twice with same domain
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("first Register failed: %v", err)
|
||||
}
|
||||
|
||||
// Update the backend address on second registration
|
||||
dom.Backend.Address = "127.0.0.1:9090"
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("second Register failed: %v", err)
|
||||
}
|
||||
|
||||
// Should still have only one domain
|
||||
doms, err := mgr.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(doms) != 1 {
|
||||
t.Errorf("expected 1 domain after idempotent register, got %d", len(doms))
|
||||
}
|
||||
|
||||
// Should have the updated address
|
||||
got, err := mgr.Get("idempotent.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
if got.Backend.Address != "127.0.0.1:9090" {
|
||||
t.Errorf("expected updated backend address 127.0.0.1:9090, got %s", got.Backend.Address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListNoDuplicates(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
domainNames := []string{
|
||||
"alpha.example.com",
|
||||
"beta.example.com",
|
||||
"gamma.example.com",
|
||||
}
|
||||
|
||||
// Register each domain
|
||||
for _, name := range domainNames {
|
||||
if err := mgr.Register(Domain{
|
||||
DomainName: name,
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
}); err != nil {
|
||||
t.Fatalf("Register %s failed: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Re-register one domain to verify no duplication
|
||||
if err := mgr.Register(Domain{
|
||||
DomainName: "beta.example.com",
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:9090", Type: BackendHTTP},
|
||||
}); err != nil {
|
||||
t.Fatalf("Re-register beta failed: %v", err)
|
||||
}
|
||||
|
||||
doms, err := mgr.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
|
||||
if len(doms) != 3 {
|
||||
t.Errorf("expected 3 unique domains, got %d", len(doms))
|
||||
}
|
||||
|
||||
// Verify no duplicate domains
|
||||
seen := make(map[string]bool)
|
||||
for _, dom := range doms {
|
||||
if seen[dom.DomainName] {
|
||||
t.Errorf("duplicate domain in List(): %s", dom.DomainName)
|
||||
}
|
||||
seen[dom.DomainName] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainToFilename(t *testing.T) {
|
||||
tests := []struct {
|
||||
domain string
|
||||
expected string
|
||||
}{
|
||||
{"cloud.payne.io", "cloud_payne_io.yaml"},
|
||||
{"internal.cloud.payne.io", "internal_cloud_payne_io.yaml"},
|
||||
{"payne.io", "payne_io.yaml"},
|
||||
{"example.com", "example_com.yaml"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := domainToFilename(tt.domain)
|
||||
if got != tt.expected {
|
||||
t.Errorf("domainToFilename(%q) = %q, want %q", tt.domain, got, tt.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGet_NotFound(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
_, err := mgr.Get("nonexistent.example.com")
|
||||
if err == nil {
|
||||
t.Error("expected error for non-existent domain, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeregister_NotFound(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
err := mgr.Deregister("nonexistent.example.com")
|
||||
if err == nil {
|
||||
t.Error("expected error when deregistering non-existent domain, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeregisterBySource_NoMatch(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
mgr.Register(Domain{
|
||||
DomainName: "a.example.com",
|
||||
Source: "wild-cloud",
|
||||
Backend: Backend{Address: "10.0.0.1:443", Type: BackendTCPPassthrough},
|
||||
Public: true,
|
||||
})
|
||||
mgr.Register(Domain{
|
||||
DomainName: "b.example.com",
|
||||
Source: "wild-works",
|
||||
Backend: Backend{Address: "10.0.0.2:8080", Type: BackendHTTP},
|
||||
})
|
||||
|
||||
// Deregister with a source that doesn't match anything
|
||||
err := mgr.DeregisterBySource("unknown-source", "10.0.0.99:443")
|
||||
if err != nil {
|
||||
t.Fatalf("DeregisterBySource with no matches should not error: %v", err)
|
||||
}
|
||||
|
||||
// All domains should still be present
|
||||
doms, _ := mgr.List()
|
||||
if len(doms) != 2 {
|
||||
t.Errorf("expected 2 domains after no-match deregister, got %d", len(doms))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeregisterBySource_PartialMatch(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
// Same source, different backends
|
||||
mgr.Register(Domain{
|
||||
DomainName: "a.example.com",
|
||||
Source: "wild-cloud",
|
||||
Backend: Backend{Address: "10.0.0.1:443", Type: BackendTCPPassthrough},
|
||||
Public: true,
|
||||
})
|
||||
mgr.Register(Domain{
|
||||
DomainName: "b.example.com",
|
||||
Source: "wild-cloud",
|
||||
Backend: Backend{Address: "10.0.0.2:443", Type: BackendTCPPassthrough},
|
||||
Public: true,
|
||||
})
|
||||
|
||||
// Deregister only the ones matching source AND backend
|
||||
err := mgr.DeregisterBySource("wild-cloud", "10.0.0.1:443")
|
||||
if err != nil {
|
||||
t.Fatalf("DeregisterBySource failed: %v", err)
|
||||
}
|
||||
|
||||
doms, _ := mgr.List()
|
||||
if len(doms) != 1 {
|
||||
t.Errorf("expected 1 remaining domain, got %d", len(doms))
|
||||
}
|
||||
if doms[0].DomainName != "b.example.com" {
|
||||
t.Errorf("expected b.example.com to remain, got %s", doms[0].DomainName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_NotFound(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
err := mgr.Update("nonexistent.example.com", map[string]any{
|
||||
"public": true,
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("expected error when updating non-existent domain, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegister_OverwritePreservesFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mgr := NewManager(dir)
|
||||
|
||||
dom := Domain{
|
||||
DomainName: "overwrite.example.com",
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
}
|
||||
|
||||
// Register first time
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("first Register failed: %v", err)
|
||||
}
|
||||
|
||||
// Register again with different backend
|
||||
dom.Backend.Address = "127.0.0.1:9090"
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("second Register failed: %v", err)
|
||||
}
|
||||
|
||||
// File count should be exactly 1
|
||||
entries, err := os.ReadDir(filepath.Join(dir, "domains"))
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir failed: %v", err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Errorf("expected 1 file after overwrite, got %d", len(entries))
|
||||
}
|
||||
|
||||
// Value should be updated
|
||||
got, _ := mgr.Get("overwrite.example.com")
|
||||
if got.Backend.Address != "127.0.0.1:9090" {
|
||||
t.Errorf("expected updated backend 127.0.0.1:9090, got %s", got.Backend.Address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_EmptyDir(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
doms, err := mgr.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List on empty dir should not error: %v", err)
|
||||
}
|
||||
if len(doms) != 0 {
|
||||
t.Errorf("expected 0 domains from empty dir, got %d", len(doms))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterWithL7Fields(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
dom := Domain{
|
||||
DomainName: "keila.cloud.payne.io",
|
||||
Source: "wild-cloud",
|
||||
Routes: []Route{{
|
||||
Paths: []string{"/.well-known/matrix", "/_matrix"},
|
||||
Backend: Backend{
|
||||
Address: "192.168.8.80:80",
|
||||
Type: BackendHTTP,
|
||||
},
|
||||
Headers: &HeaderConfig{
|
||||
Response: map[string]string{
|
||||
"Access-Control-Allow-Origin": "https://payne.io",
|
||||
},
|
||||
Request: map[string]string{
|
||||
"X-Forwarded-Proto": "https",
|
||||
},
|
||||
},
|
||||
IPAllow: []string{"10.0.0.0/8", "192.168.0.0/16"},
|
||||
}},
|
||||
}
|
||||
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
|
||||
got, err := mgr.Get("keila.cloud.payne.io")
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
|
||||
if len(got.Routes) != 1 {
|
||||
t.Fatalf("expected 1 route, got %d", len(got.Routes))
|
||||
}
|
||||
r := got.Routes[0]
|
||||
if len(r.Paths) != 2 || r.Paths[0] != "/.well-known/matrix" {
|
||||
t.Errorf("expected 2 paths, got %v", r.Paths)
|
||||
}
|
||||
if r.Headers == nil {
|
||||
t.Fatal("expected headers, got nil")
|
||||
}
|
||||
if r.Headers.Response["Access-Control-Allow-Origin"] != "https://payne.io" {
|
||||
t.Errorf("expected response header, got %v", r.Headers.Response)
|
||||
}
|
||||
if r.Headers.Request["X-Forwarded-Proto"] != "https" {
|
||||
t.Errorf("expected request header, got %v", r.Headers.Request)
|
||||
}
|
||||
if len(r.IPAllow) != 2 || r.IPAllow[0] != "10.0.0.0/8" {
|
||||
t.Errorf("expected 2 ipAllow CIDRs, got %v", r.IPAllow)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateL7Fields(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
mgr.Register(Domain{
|
||||
DomainName: "updatable.example.com",
|
||||
Source: "test",
|
||||
Routes: []Route{{
|
||||
Paths: []string{"/api", "/webhook"},
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
IPAllow: []string{"10.0.0.0/8"},
|
||||
Headers: &HeaderConfig{
|
||||
Response: map[string]string{
|
||||
"X-Custom": "value",
|
||||
},
|
||||
},
|
||||
}},
|
||||
})
|
||||
|
||||
got, _ := mgr.Get("updatable.example.com")
|
||||
if len(got.Routes) != 1 {
|
||||
t.Fatalf("expected 1 route, got %d", len(got.Routes))
|
||||
}
|
||||
r := got.Routes[0]
|
||||
if len(r.Paths) != 2 || r.Paths[0] != "/api" {
|
||||
t.Errorf("expected paths [/api /webhook], got %v", r.Paths)
|
||||
}
|
||||
if len(r.IPAllow) != 1 || r.IPAllow[0] != "10.0.0.0/8" {
|
||||
t.Errorf("expected ipAllow [10.0.0.0/8], got %v", r.IPAllow)
|
||||
}
|
||||
if r.Headers == nil || r.Headers.Response["X-Custom"] != "value" {
|
||||
t.Errorf("expected response header X-Custom=value, got %v", r.Headers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_IgnoresNonYAML(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mgr := NewManager(dir)
|
||||
|
||||
// Register one real domain
|
||||
mgr.Register(Domain{
|
||||
DomainName: "real.example.com",
|
||||
Source: "test",
|
||||
Backend: Backend{Address: "127.0.0.1:8080", Type: BackendHTTP},
|
||||
})
|
||||
|
||||
// Create non-YAML files in the domains directory
|
||||
domainsDir := filepath.Join(dir, "domains")
|
||||
os.WriteFile(filepath.Join(domainsDir, "README.md"), []byte("# ignore me"), 0644)
|
||||
os.WriteFile(filepath.Join(domainsDir, "notes.txt"), []byte("some notes"), 0644)
|
||||
os.WriteFile(filepath.Join(domainsDir, ".gitkeep"), []byte(""), 0644)
|
||||
|
||||
doms, err := mgr.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(doms) != 1 {
|
||||
t.Errorf("expected 1 domain (ignoring non-YAML files), got %d", len(doms))
|
||||
}
|
||||
if doms[0].DomainName != "real.example.com" {
|
||||
t.Errorf("expected real.example.com, got %s", doms[0].DomainName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterDNSOnly(t *testing.T) {
|
||||
mgr := NewManager(t.TempDir())
|
||||
|
||||
dom := Domain{
|
||||
DomainName: "dev.payne.io",
|
||||
Source: "manual",
|
||||
Backend: Backend{
|
||||
Address: "192.168.8.222",
|
||||
Type: BackendDNSOnly,
|
||||
},
|
||||
Public: true,
|
||||
}
|
||||
|
||||
if err := mgr.Register(dom); err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
|
||||
got, err := mgr.Get("dev.payne.io")
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
|
||||
if got.TLS != TLSNone {
|
||||
t.Errorf("expected TLS none for dns-only, got %s", got.TLS)
|
||||
}
|
||||
if got.Backend.Type != BackendDNSOnly {
|
||||
t.Errorf("expected backend type dns-only, got %s", got.Backend.Type)
|
||||
}
|
||||
if got.Backend.Address != "192.168.8.222" {
|
||||
t.Errorf("expected address 192.168.8.222, got %s", got.Backend.Address)
|
||||
}
|
||||
if !got.Public {
|
||||
t.Error("expected public=true")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user