Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91e51890dd | ||
|
|
7611572062 | ||
|
|
3b5bf578a0 | ||
|
|
bf211ca273 | ||
|
|
becd068637 | ||
|
|
b3dda81b49 | ||
|
|
b20ace8763 | ||
|
|
053b38e46c | ||
|
|
df31bfa720 |
41
CLAUDE.md
41
CLAUDE.md
@@ -13,7 +13,9 @@ Vor jeder Entscheidung über Feldwerte, API-Shapes, Dateinamen, Funktions-Signat
|
||||
|
||||
# EdgeGuard Native (`eg`)
|
||||
|
||||
> Native Neufassung des Docker-basierten EdgeGuard-Stacks. Kein Docker, kein WAF in v1. Zielplattform: **Debian 13 (Trixie), amd64 + arm64**. Auslieferung als signiertes `.deb`.
|
||||
> Native Neufassung des Docker-basierten EdgeGuard-Stacks. Kein Docker — alle Dienste nativ unter systemd. Zielplattform: **Debian 13 (Trixie), amd64 + arm64**. Auslieferung als signiertes `.deb`.
|
||||
>
|
||||
> **Hinweis:** Mehrere ursprüngliche v1-Nicht-Ziele (WAF, IDS/IPS, DHCP, RADIUS) sind inzwischen umgesetzt — siehe „Feature-Stand" weiter unten.
|
||||
|
||||
---
|
||||
|
||||
@@ -67,26 +69,47 @@ ac_search_code(query="<Stichworte>", project_id=8, session_name="$(printenv ARCH
|
||||
| **API** | Go 1.26, Gin, GORM (Queries), goose (Migrations) |
|
||||
| **UI** | React 19, TypeScript strict, Vite, Ant Design 6, TanStack Query 5 |
|
||||
| **DB** | PostgreSQL 16 (Distro-Paket), goose-Migrations in `migrations/` |
|
||||
| **State/HA** | KeyDB Active-Active (Redis-kompatibel) |
|
||||
| **State/HA** | PostgreSQL Logical Replication + Cluster-Agent-Heartbeat (mTLS); KeyDB Active-Active nur optional (`Recommends`, für Lizenz-Leader-Election/Shared-Cache) |
|
||||
| **Proxy/LB** | HAProxy (Distro) — TLS-Termination, L7-Routing, LB |
|
||||
| **WAF** | Coraza v3 + OWASP CRS, via HAProxy SPOE (`edgeguard-waf`-Agent) |
|
||||
| **IDS/IPS** | CrowdSec + `crowdsec-firewall-bouncer` (nftables) — managed-wenn-installiert (kein Depends) |
|
||||
| **VPN** | WireGuard (Kernel-Modul ab 5.6, `wireguard-tools`) |
|
||||
| **DNS** | Unbound (Distro) — Forwarder+Cache mit DNSSEC, Cluster-internes Split-Horizon |
|
||||
| **DHCP** | Kea (`kea-dhcp4-server`) — managed, default-off |
|
||||
| **AAA/RADIUS** | FreeRADIUS (PAP/CHAP, files-based) — managed, default-off |
|
||||
| **NTP** | chrony (Distro) |
|
||||
| **VIP/HA** | keepalived (VRRP) |
|
||||
| **FW** | nftables (Distro) |
|
||||
| **Forward-Proxy** | Squid (Distro) |
|
||||
| **Auth/SSO** | JWT (lokal) + 2FA/TOTP + OIDC/OAuth2 (Keycloak u. a.) |
|
||||
| **TLS** | certbot + webroot-Plugin |
|
||||
| **Packaging** | dpkg-deb (direkt, wie mail-gateway + netcell-webpanel) |
|
||||
| **Plattform** | Debian 13 Trixie · amd64 + arm64 |
|
||||
|
||||
---
|
||||
|
||||
## Nicht-Ziele (v1)
|
||||
## Feature-Stand (Stand 2026-06)
|
||||
|
||||
Über den ursprünglichen v1-Scope hinaus inzwischen **umgesetzt** (waren mal Nicht-Ziele):
|
||||
|
||||
- **WAF** — Coraza v3 + OWASP CRS via HAProxy SPOE (`edgeguard-waf`)
|
||||
- **IDS/IPS** — CrowdSec + `crowdsec-firewall-bouncer` (nftables-Bouncer); managed-wenn-installiert, kein hartes Depends
|
||||
- **DHCP** — Kea `kea-dhcp4-server` (managed, default-off)
|
||||
- **RADIUS** — FreeRADIUS PAP/CHAP, files-based (managed, default-off)
|
||||
- **SSO** — OIDC/OAuth2 (additiv, Rolle aus DB, lokaler Login bleibt)
|
||||
- **2FA** — TOTP
|
||||
- **IPv6** — Firewall-Regeln + NAT familienbewusst
|
||||
- **HA** — VIP via keepalived (VRRP), PG-Logical-Replication, bidirektionaler Cluster-Heartbeat
|
||||
|
||||
Damit ist die ursprüngliche v2-Roadmap (WAF, 2FA, IPv6-FW, OIDC, DHCP, RADIUS) abgearbeitet.
|
||||
|
||||
## Nicht-Ziele (weiterhin)
|
||||
|
||||
- **Kein Docker** — alle Dienste nativ unter systemd
|
||||
- **Kein WAF** (kein Coraza, kein ModSecurity)
|
||||
- **Kein IDS/IPS** (kein Suricata, kein CrowdSec)
|
||||
- **Kein DHCP-Server** (kein Kea)
|
||||
- **Kein RADIUS** (kein FreeRADIUS)
|
||||
- **Kein Network-IDS Suricata** — Intrusion-Detection läuft über CrowdSec, nicht über Suricata-Paket-Inspektion
|
||||
- **Keine Mail-Verarbeitung** (eigenes Produkt: mail-gateway)
|
||||
- **Keine Multi-Tenant-GuardZones**
|
||||
- **Keine ISO-Builds** (kein EdgeGuardOS-Klon — nur APT)
|
||||
- **Nur Debian 13** — kein Ubuntu, kein Debian 12, kein RHEL
|
||||
|
||||
---
|
||||
@@ -154,7 +177,6 @@ cd management-ui && bun run dev
|
||||
│ ├── unbound/ # Config-Generator (Forwarder + Cluster-DNS)
|
||||
│ ├── firewall/ # nftables-Generator
|
||||
│ ├── cluster/ # Join/Promote/Peer-Discovery
|
||||
│ ├── proxy/ # Write-Proxy → Cluster-Primary
|
||||
│ ├── aggregator/ # Cluster-View APIs
|
||||
│ └── license/ # Lizenz-Validierung
|
||||
├── management-ui/ # React 19 + AntD 6 (1:1 enconf-Pattern)
|
||||
@@ -185,7 +207,8 @@ cd management-ui && bun run dev
|
||||
- **ORM:** GORM für Queries, nicht für Schema-Verwaltung
|
||||
- **Config-Generierung:** Template-Datei in `deploy/*/`, Generator in `internal/*/`
|
||||
- **Config-Reload:** `systemctl reload <service>` nach Config-Schreiben
|
||||
- **Cluster-Writes:** immer über `internal/proxy` → Primary-URL aus KeyDB `cluster:pg-primary-url`
|
||||
- **Cluster-Primary-Ermittlung:** zuverlässig über `pg_publication` (`edgeguard_shared`); Primary-URL aus `setup.json` `PrimaryFQDN` via `clusterjoin.NormalizePrimaryURL`. **Kein Write-Proxy** — Schreibzugriffe auf geteilte Tabellen erfolgen am Primary.
|
||||
- **Failover:** `edgeguard-ctl promote` ist Logical-Replication-aware (Subscription lösen → `setupReplicationPrimary` → Publisher werden, inkl. PG-Restart für `wal_level=logical`); erholte Nodes danach via `cluster-setup-standby <neuer-primary>` zurückhängen.
|
||||
|
||||
### Packaging
|
||||
- `dpkg-deb` direkt (wie mail-gateway) — kein dh_make/debhelper/fpm
|
||||
|
||||
@@ -194,6 +194,12 @@ func main() {
|
||||
}
|
||||
// runSecondaryConfigRender wird weiter unten gestartet sobald
|
||||
// clusterAggregator verfügbar ist (braucht mTLS-Client für Cert-Sync).
|
||||
} else if nodeID != "" && st != nil && st.Completed && st.FQDN != "" {
|
||||
// Primary/Founder (kein joined Secondary): self (role=primary) an
|
||||
// alle Peers pushen, damit deren lokale ha_nodes den Primary frisch
|
||||
// hält — sonst zeigt die vom Secondary ausgelieferte UI den Primary
|
||||
// als offline. No-op solange keine Peers existieren (Single-Node).
|
||||
go runPeerPush(context.Background(), pool, clusterStore, nodeID, st.FQDN, version)
|
||||
}
|
||||
|
||||
// Phase 3.3: Cluster-CA + Peer-Cert. Founder-Pfad — auf einem
|
||||
@@ -425,7 +431,14 @@ func main() {
|
||||
wgReloader := func(ctx context.Context) error {
|
||||
return wgrender.New(pool, secretsBox).Render(ctx)
|
||||
}
|
||||
handlers.NewWireguardHandler(wgIfaces, wgPeers, secretsBox, auditRepo, nodeID, withFW(wgReloader)).Register(authed)
|
||||
// Öffentlicher WG-Endpoint-Host für Peer-Configs = FQDN dieser Node
|
||||
// (aus setup.json). Verhindert den REPLACE_WITH_PUBLIC_HOST-Platzhalter,
|
||||
// an dem Clients sonst keinen Tunnel aufbauen können.
|
||||
wgPublicHost := ""
|
||||
if sst, serr := setupStore.Load(); serr == nil && sst != nil {
|
||||
wgPublicHost = sst.FQDN
|
||||
}
|
||||
handlers.NewWireguardHandler(wgIfaces, wgPeers, secretsBox, auditRepo, nodeID, withFW(wgReloader)).WithPublicHost(wgPublicHost).Register(authed)
|
||||
|
||||
// Squid forward-proxy reload — re-render squid.conf + reload
|
||||
// squid.service. sudoers im postinst whitelistet das. ACL-Count
|
||||
@@ -826,12 +839,20 @@ func runSecondaryConfigRender(ctx context.Context, pool *pgxpoolPool, box *secre
|
||||
}
|
||||
|
||||
// runPrimaryPush periodically pushes this secondary node's config_hash to the
|
||||
// primary via mTLS. The primary's ha_nodes view only gets config_hash written
|
||||
// during join-time autoRegister — after that the primary never hears about
|
||||
// hash changes unless we push. Without this, the drift banner shows stale
|
||||
// hashes from join-time forever.
|
||||
// primary via mTLS. The primary's ha_nodes view only gets config_hash + last_seen
|
||||
// written during join-time autoRegister — after that the primary never hears about
|
||||
// the secondary unless we push. Without this, the drift banner shows stale hashes
|
||||
// from join-time forever AND the secondary's last_seen freezes → SweepStaleNodes
|
||||
// marks it offline.
|
||||
//
|
||||
// WICHTIG: tick MUSS deutlich unter dem Stale-Threshold (4× 30s = 2 min, siehe
|
||||
// scheduler.staleThreshold / cluster.SweepStaleNodes) liegen. Sonst flippt der
|
||||
// Secondary zwischen den Pushes zwangsläufig auf "offline" (bei 5-min-Tick:
|
||||
// 2 min online, 3 min offline). 30s = 4 Pushes pro Stale-Fenster → ein
|
||||
// verpasster Push (Netz-Glitch) ist unkritisch. Der Receiver (AgentRegisterPeer)
|
||||
// lädt nftables nur bei IP-Änderung neu → kein Reload-Sturm durch häufige Pushes.
|
||||
func runPrimaryPush(ctx context.Context, pool *pgxpoolPool, nodeID, fqdn, version, primaryURL string) {
|
||||
const tick = 5 * time.Minute
|
||||
const tick = 30 * time.Second
|
||||
t := time.NewTicker(tick)
|
||||
defer t.Stop()
|
||||
push := func() {
|
||||
@@ -855,6 +876,51 @@ func runPrimaryPush(ctx context.Context, pool *pgxpoolPool, nodeID, fqdn, versio
|
||||
}
|
||||
}
|
||||
|
||||
// runPeerPush läuft auf dem Primary/Founder und pusht alle 30s die eigene
|
||||
// Identität (role=primary) an jeden Peer via mTLS — das Gegenstück zu
|
||||
// runPrimaryPush (Secondary→Primary). Zusammen ergibt das einen
|
||||
// bidirektionalen Cross-Node-Heartbeat: beide Nodes sehen sich gegenseitig
|
||||
// als online, egal von welchem Node die UI ausgeliefert wird. Tick wie
|
||||
// runPrimaryPush deutlich unter dem 2-min-Stale-Threshold. No-op solange
|
||||
// keine Peers existieren (Single-Node) bzw. wenn ein Peer down ist (Debug-Log).
|
||||
func runPeerPush(ctx context.Context, pool *pgxpoolPool, store *cluster.Store, nodeID, fqdn, version string) {
|
||||
const tick = 30 * time.Second
|
||||
t := time.NewTicker(tick)
|
||||
defer t.Stop()
|
||||
push := func() {
|
||||
pCtx, cancel := context.WithTimeout(ctx, 25*time.Second)
|
||||
defer cancel()
|
||||
peers, err := store.List(pCtx)
|
||||
if err != nil {
|
||||
slog.Warn("cluster: peer-push list failed", "error", err)
|
||||
return
|
||||
}
|
||||
hash, _ := cluster.ComputeConfigHash(pCtx, pool)
|
||||
for i := range peers {
|
||||
p := peers[i]
|
||||
if p.ID == nodeID {
|
||||
continue // nicht an sich selbst pushen
|
||||
}
|
||||
target := p.APIURL
|
||||
if target == "" {
|
||||
target = "https://" + p.FQDN
|
||||
}
|
||||
if err := clusterjoin.PushSelfToPeer(target, "", nodeID, fqdn, version, hash, "primary"); err != nil {
|
||||
slog.Debug("cluster: push-to-peer failed", "peer", p.FQDN, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
push() // immediate push on API startup
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
push()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func randomEphemeralSecret() []byte {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -114,11 +115,29 @@ func cmdClusterInitReplication(args []string) int {
|
||||
}
|
||||
fmt.Printf("→ PostgreSQL %s/%s erkannt\n", pg.Version, pg.Cluster)
|
||||
|
||||
if err := setupReplicationPrimary(pg); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication:", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("Nächste Schritte:")
|
||||
fmt.Println(" 1) Auf dem Secondary: edgeguard-ctl cluster-setup-standby <primary-ip>")
|
||||
fmt.Println(" 2) Cluster-Settings (VIP) auf BEIDEN Nodes separat konfigurieren")
|
||||
fmt.Println(" → Settings → Cluster → VIP/Keepalived")
|
||||
return 0
|
||||
}
|
||||
|
||||
// setupReplicationPrimary konfiguriert die lokale PG-Instanz als Logical-
|
||||
// Replication-Primary: Replikations-Rolle + Secret, conf.d (wal_level=logical),
|
||||
// pg_hba, SELECT-Grants, PUBLICATION. Stellt sicher dass wal_level=logical
|
||||
// AKTIV ist (Restart nur falls nötig — für wal_level reicht reload nicht).
|
||||
// Idempotent. Gemeinsam genutzt von cluster-init-replication und promote.
|
||||
func setupReplicationPrimary(pg pgConfig) error {
|
||||
// 1. Passwort generieren
|
||||
pass, err := generatePassword(32)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: generate password:", err)
|
||||
return 1
|
||||
return fmt.Errorf("generate password: %w", err)
|
||||
}
|
||||
|
||||
// 2. edgeguard_replicator-Rolle anlegen/updaten
|
||||
@@ -132,21 +151,17 @@ BEGIN
|
||||
END
|
||||
$$`, egReplUser, egReplUser, pass, egReplUser, pass)
|
||||
if err := psqlExec(roleSQL); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: create replication role:", err)
|
||||
return 1
|
||||
return fmt.Errorf("create replication role: %w", err)
|
||||
}
|
||||
fmt.Printf("✓ Replication-Rolle %q angelegt/aktualisiert\n", egReplUser)
|
||||
|
||||
// 3. Passwort speichern
|
||||
// 3. Passwort speichern (Ownership an edgeguard-User, damit die API liest)
|
||||
if err := os.MkdirAll(filepath.Dir(egReplSecret), 0o750); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: mkdir:", err)
|
||||
return 1
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(egReplSecret, []byte(pass), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: write secret:", err)
|
||||
return 1
|
||||
return fmt.Errorf("write secret: %w", err)
|
||||
}
|
||||
// Ownership an edgeguard-api-User übergeben damit die API lesen kann
|
||||
if u, err := user.Lookup("edgeguard"); err == nil {
|
||||
uid, _ := strconv.Atoi(u.Uid)
|
||||
gid, _ := strconv.Atoi(u.Gid)
|
||||
@@ -155,71 +170,88 @@ $$`, egReplUser, egReplUser, pass, egReplUser, pass)
|
||||
fmt.Printf("✓ Replication-Secret gespeichert: %s\n", egReplSecret)
|
||||
|
||||
// 4. conf.d/edgeguard-replication.conf schreiben
|
||||
// wal_level=logical ist eine Obermenge von replica — unterstützt
|
||||
// sowohl Logical Replication als auch ggfs. physisches WAL-Archiving.
|
||||
if err := os.MkdirAll(pg.ConfD, 0o755); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: conf.d mkdir:", err)
|
||||
return 1
|
||||
return fmt.Errorf("conf.d mkdir: %w", err)
|
||||
}
|
||||
replConf := `# EdgeGuard Logical Replication — automatisch generiert
|
||||
# Nicht manuell bearbeiten; wird von edgeguard-ctl cluster-init-replication verwaltet.
|
||||
# Nicht manuell bearbeiten; wird von edgeguard-ctl verwaltet.
|
||||
wal_level = logical
|
||||
max_wal_senders = 10
|
||||
max_replication_slots = 20
|
||||
max_logical_replication_workers = 4
|
||||
wal_keep_size = 512MB
|
||||
# Lausche auf localhost + alle konfigurierten Interfaces damit Cluster-Peers
|
||||
# sich verbinden können. '*' ist sicher weil pg_hba.conf den Zugriff auf
|
||||
# bekannte Replikations-User beschränkt.
|
||||
# '*' ist sicher weil pg_hba.conf den Zugriff auf bekannte Replikations-User beschränkt.
|
||||
listen_addresses = '*'
|
||||
`
|
||||
confPath := filepath.Join(pg.ConfD, "edgeguard-replication.conf")
|
||||
if err := os.WriteFile(confPath, []byte(replConf), 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: write postgresql conf:", err)
|
||||
return 1
|
||||
return fmt.Errorf("write postgresql conf: %w", err)
|
||||
}
|
||||
fmt.Printf("✓ %s geschrieben (wal_level=logical)\n", confPath)
|
||||
|
||||
// 5. pg_hba.conf aktualisieren
|
||||
if err := ensureHBAReplication(pg.HBAPath); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: pg_hba.conf:", err)
|
||||
return 1
|
||||
return fmt.Errorf("pg_hba.conf: %w", err)
|
||||
}
|
||||
fmt.Printf("✓ %s aktualisiert\n", pg.HBAPath)
|
||||
|
||||
// 6. PG reload (damit wal_level + pg_hba aktiv werden)
|
||||
// 6. PG reload (pg_hba aktiv). wal_level/max_wal_senders sind aber
|
||||
// postmaster-Parameter → nur per RESTART aktiv. Nur restarten wenn nötig.
|
||||
if out, err := exec.Command("pg_ctlcluster", pg.Version, pg.Cluster, "reload").CombinedOutput(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cluster-init-replication: pg reload failed: %v\n%s\n", err, out)
|
||||
return 1
|
||||
return fmt.Errorf("pg reload: %w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
fmt.Printf("✓ PostgreSQL %s/%s neu geladen\n", pg.Version, pg.Cluster)
|
||||
if cur, _ := psqlRun([]string{"-tA", "-c", "SHOW wal_level;"}); strings.TrimSpace(string(cur)) != "logical" {
|
||||
fmt.Println("→ wal_level wechselt auf 'logical' — PostgreSQL-Restart nötig...")
|
||||
if out, err := exec.Command("pg_ctlcluster", pg.Version, pg.Cluster, "restart").CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("pg restart: %w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
ready := false
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := psqlRun([]string{"-tA", "-c", "SELECT 1;"}); err == nil {
|
||||
ready = true
|
||||
break
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
if !ready {
|
||||
return fmt.Errorf("PostgreSQL kam nach Restart binnen 60s nicht zurück — prüfe PG-Logs")
|
||||
}
|
||||
fmt.Println("✓ PostgreSQL neu gestartet (wal_level=logical aktiv)")
|
||||
}
|
||||
|
||||
// 7. SELECT-Grants: edgeguard_replicator muss alle zu replizierenden
|
||||
// Tabellen lesen können. DEFAULT PRIVILEGES sichert zukünftige Tabellen.
|
||||
// 7. SELECT-Grants (DEFAULT PRIVILEGES sichert zukünftige Tabellen)
|
||||
grantSQL := fmt.Sprintf(`
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA public TO %s;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO %s;
|
||||
`, egReplUser, egReplUser)
|
||||
if err := psqlDBExec("edgeguard", grantSQL); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: grant SELECT:", err)
|
||||
return 1
|
||||
return fmt.Errorf("grant SELECT: %w", err)
|
||||
}
|
||||
fmt.Printf("✓ SELECT auf alle Tabellen für %q gewährt\n", egReplUser)
|
||||
|
||||
// 8. PUBLICATION erstellen — alle public-Tabellen außer localOnlyTables.
|
||||
// Idempotent: DROP IF EXISTS + CREATE.
|
||||
// 8. PUBLICATION (idempotent: DROP IF EXISTS + CREATE)
|
||||
if err := createPublication(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: create publication:", err)
|
||||
return 1
|
||||
return fmt.Errorf("create publication: %w", err)
|
||||
}
|
||||
fmt.Printf("✓ PUBLICATION %q erstellt\n", egPubName)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("Nächste Schritte:")
|
||||
fmt.Println(" 1) Auf dem Secondary: edgeguard-ctl cluster-setup-standby <primary-ip>")
|
||||
fmt.Println(" 2) Cluster-Settings (VIP) auf BEIDEN Nodes separat konfigurieren")
|
||||
fmt.Println(" → Settings → Cluster → VIP/Keepalived")
|
||||
return 0
|
||||
// dropSubscriptionIfExists entfernt die lokale Logical-Replication-Subscription
|
||||
// idempotent. DISABLE + slot_name=NONE VOR DROP, damit DROP nicht versucht den
|
||||
// Slot auf dem (beim Failover evtl. toten) Publisher zu löschen → kein Hängen.
|
||||
func dropSubscriptionIfExists() error {
|
||||
dropSQL := fmt.Sprintf(`
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT FROM pg_subscription WHERE subname = '%s') THEN
|
||||
ALTER SUBSCRIPTION %s DISABLE;
|
||||
ALTER SUBSCRIPTION %s SET (slot_name = NONE);
|
||||
DROP SUBSCRIPTION %s;
|
||||
END IF;
|
||||
END $$;`, egSubName, egSubName, egSubName, egSubName)
|
||||
return psqlDBExec("edgeguard", dropSQL)
|
||||
}
|
||||
|
||||
// createPublication baut die PUBLICATION dynamisch aus allen Tabellen
|
||||
@@ -333,15 +365,7 @@ func cmdClusterSetupStandby(args []string) int {
|
||||
fmt.Printf("✓ Replication-Credentials von %s:%d erhalten\n", primaryHost, *agentPort)
|
||||
|
||||
// 2. Bestehende Subscription löschen (idempotent)
|
||||
dropSQL := fmt.Sprintf(`
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT FROM pg_subscription WHERE subname = '%s') THEN
|
||||
ALTER SUBSCRIPTION %s DISABLE;
|
||||
ALTER SUBSCRIPTION %s SET (slot_name = NONE);
|
||||
DROP SUBSCRIPTION %s;
|
||||
END IF;
|
||||
END $$;`, egSubName, egSubName, egSubName, egSubName)
|
||||
if err := psqlDBExec("edgeguard", dropSQL); err != nil {
|
||||
if err := dropSubscriptionIfExists(); err != nil {
|
||||
// Nicht fatal — wenn PG noch keine Subscription kennt ist das OK
|
||||
fmt.Printf(" → keine bestehende Subscription gefunden (ok)\n")
|
||||
} else {
|
||||
@@ -359,7 +383,9 @@ END $$;`, egSubName, egSubName, egSubName, egSubName)
|
||||
"CREATE SUBSCRIPTION %s CONNECTION '%s' PUBLICATION %s WITH (copy_data = true, enabled = true);",
|
||||
egSubName, connStr, egPubName,
|
||||
)
|
||||
if err := psqlDBExec("edgeguard", createSQL); err != nil {
|
||||
// Via stdin (nicht -c), damit das Replikations-Passwort nicht in der
|
||||
// Prozess-Argv (ps/proc) oder in PG-log_statement landet.
|
||||
if err := psqlDBExecStdin("edgeguard", createSQL); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cluster-setup-standby: create subscription: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
@@ -470,7 +496,7 @@ func fetchReplicationCreds(host string, agentPort int, tlsDir string) (*pgReplic
|
||||
},
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://%s:%d/agent/cluster/pg-replication-info", host, agentPort)
|
||||
url := "https://" + net.JoinHostPort(host, strconv.Itoa(agentPort)) + "/agent/cluster/pg-replication-info"
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GET %s: %w", url, err)
|
||||
@@ -516,7 +542,7 @@ func syncMasterKey(host string, agentPort int, tlsDir string) error {
|
||||
},
|
||||
},
|
||||
}
|
||||
url := fmt.Sprintf("https://%s:%d/agent/cluster/master-key", host, agentPort)
|
||||
url := "https://" + net.JoinHostPort(host, strconv.Itoa(agentPort)) + "/agent/cluster/master-key"
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GET %s: %w", url, err)
|
||||
@@ -568,6 +594,17 @@ func psqlDBExec(db, sql string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// psqlDBExecStdin führt SQL über stdin (`-f -`) aus statt `-c`, damit
|
||||
// Secrets im SQL nicht in der Prozess-Argv / PG-Statement-Logs erscheinen.
|
||||
func psqlDBExecStdin(db, sql string) error {
|
||||
cmd := buildPsqlCmd([]string{"-d", db, "-v", "ON_ERROR_STOP=1", "-f", "-"})
|
||||
cmd.Stdin = strings.NewReader(sql)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// psqlDBRun führt psql-Kommandos gegen eine bestimmte Datenbank aus.
|
||||
func psqlDBRun(db string, args []string) ([]byte, error) {
|
||||
baseArgs := []string{"-d", db}
|
||||
|
||||
@@ -4,8 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -14,18 +12,22 @@ import (
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/keepalived"
|
||||
)
|
||||
|
||||
// cmdPromote promotes this node's PostgreSQL instance from Hot-Standby
|
||||
// to Primary. Manual failover — keine automatische Promotion, um Split-Brain
|
||||
// in 2-Node-Clustern ohne externen Quorum zu verhindern.
|
||||
// cmdPromote befördert diese Node zum Logical-Replication-Primary. Manuelles
|
||||
// Failover — keine automatische Promotion, um Split-Brain in 2-Node-Clustern
|
||||
// ohne externes Quorum zu verhindern.
|
||||
//
|
||||
// Hintergrund: Die Replikation ist LOGICAL (Publication/Subscription), nicht
|
||||
// physisch. Ein Subscriber ist eine normale beschreibbare PG-Instanz (nie „in
|
||||
// recovery", kein standby.signal). „Promote" heißt darum: Subscription zum
|
||||
// (toten/alten) Primary lösen und selbst Publisher werden.
|
||||
//
|
||||
// Ablauf:
|
||||
// 1. Prüfen ob standby.signal vorhanden (wir sind wirklich Standby)
|
||||
// 2. pg_ctlcluster promote → PG wird Primary
|
||||
// 3. Warten bis pg_is_in_recovery() = false
|
||||
// 4. ha_nodes.pg_role auf 'primary' setzen
|
||||
// 5. KeyDB cluster:pg-primary-url auf lokal setzen
|
||||
// 6. keepalived.conf neu rendern (Primary bekommt Priorität 200)
|
||||
// 7. keepalived reload
|
||||
// 1. Idempotenz-Check: schon Publisher ohne Subscription → fertig
|
||||
// 2. Subscription lösen (DISABLE + slot_name=NONE + DROP)
|
||||
// 3. setupReplicationPrimary: Rolle/Secret/conf.d/pg_hba/Grants/Publication
|
||||
// + sicherstellen dass wal_level=logical aktiv ist (PG-Restart falls nötig)
|
||||
// 4. ha_nodes.pg_role/role = 'primary'
|
||||
// 5. keepalived neu rendern (Primary = Priorität 200 = MASTER → übernimmt VIP)
|
||||
func cmdPromote(args []string) int {
|
||||
pg, err := detectPGConfig()
|
||||
if err != nil {
|
||||
@@ -33,51 +35,43 @@ func cmdPromote(args []string) int {
|
||||
return 1
|
||||
}
|
||||
|
||||
// 1. Standby-Signal prüfen
|
||||
signalPath := filepath.Join(pg.DataDir, "standby.signal")
|
||||
if _, err := os.Stat(signalPath); os.IsNotExist(err) {
|
||||
fmt.Fprintf(os.Stderr,
|
||||
"promote: %s nicht gefunden — diese Node ist kein PG-Standby oder wurde bereits promoted.\n",
|
||||
signalPath)
|
||||
return 1
|
||||
// 1. Idempotenz: bereits Publisher (Primary) ohne Subscription?
|
||||
pubOut, _ := psqlDBRun("edgeguard", []string{"-tA", "-c",
|
||||
fmt.Sprintf("SELECT count(*) FROM pg_publication WHERE pubname='%s';", egPubName)})
|
||||
subOut, _ := psqlDBRun("edgeguard", []string{"-tA", "-c",
|
||||
fmt.Sprintf("SELECT count(*) FROM pg_subscription WHERE subname='%s';", egSubName)})
|
||||
hasPub := strings.TrimSpace(string(pubOut)) == "1"
|
||||
hasSub := strings.TrimSpace(string(subOut)) == "1"
|
||||
if hasPub && !hasSub {
|
||||
fmt.Println("✓ Diese Node ist bereits Logical-Replication-Primary (Publication vorhanden, keine Subscription). Nichts zu tun.")
|
||||
return 0
|
||||
}
|
||||
|
||||
fmt.Printf("→ Promoting PostgreSQL %s/%s zu Primary...\n", pg.Version, pg.Cluster)
|
||||
if out, err := exec.Command("pg_ctlcluster", pg.Version, pg.Cluster, "promote").
|
||||
CombinedOutput(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "promote: pg_ctlcluster promote: %v\n%s\n", err, out)
|
||||
return 1
|
||||
}
|
||||
fmt.Println("✓ pg_ctlcluster promote gesendet")
|
||||
fmt.Printf("→ Promote zu Logical-Replication-Primary (PostgreSQL %s/%s)...\n", pg.Version, pg.Cluster)
|
||||
|
||||
// 2. Warten bis PG wirklich Primary ist (pg_is_in_recovery = false)
|
||||
fmt.Print("→ Warte auf PG Primary-Mode")
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
out, err := psqlRun([]string{"-tA", "-c", "SELECT pg_is_in_recovery();"})
|
||||
if err == nil && strings.TrimSpace(string(out)) == "f" {
|
||||
break
|
||||
// 2. Subscription zum alten/toten Primary lösen
|
||||
if hasSub {
|
||||
if err := dropSubscriptionIfExists(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "promote: Subscription lösen:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Print(".")
|
||||
time.Sleep(2 * time.Second)
|
||||
fmt.Println("✓ Subscription zum alten Primary entfernt")
|
||||
}
|
||||
fmt.Println()
|
||||
// Nochmal prüfen
|
||||
out, err := psqlRun([]string{"-tA", "-c", "SELECT pg_is_in_recovery();"})
|
||||
if err != nil || strings.TrimSpace(string(out)) != "f" {
|
||||
fmt.Fprintln(os.Stderr, "promote: PG ist nach 60s noch in recovery — prüfe PG-Logs")
|
||||
|
||||
// 3. Diese Node als Publisher einrichten (inkl. wal_level=logical + Restart)
|
||||
if err := setupReplicationPrimary(pg); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "promote:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Println("✓ PostgreSQL ist jetzt Primary")
|
||||
|
||||
// 3. ha_nodes.pg_role + role aktualisieren
|
||||
// 4. ha_nodes-Rolle aktualisieren
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := database.Open(ctx, database.ConnStringFromEnv())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "promote: db connect:", err)
|
||||
fmt.Println(" → ha_nodes manuell updaten: UPDATE ha_nodes SET pg_role='primary', role='primary' WHERE id='<local-id>';")
|
||||
fmt.Println(" → ha_nodes manuell: UPDATE ha_nodes SET pg_role='primary', role='primary' WHERE id='<local-id>';")
|
||||
} else {
|
||||
defer pool.Close()
|
||||
localID, err := loadLocalID()
|
||||
@@ -93,15 +87,7 @@ func cmdPromote(args []string) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 4. KeyDB cluster:pg-primary-url updaten
|
||||
if err := updateKeyDBPrimaryURL(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "promote: KeyDB update: %v\n", err)
|
||||
fmt.Println(" → Manuell: redis-cli SET cluster:pg-primary-url 'postgres://edgeguard@/edgeguard'")
|
||||
} else {
|
||||
fmt.Println("✓ KeyDB cluster:pg-primary-url aktualisiert")
|
||||
}
|
||||
|
||||
// 5. Keepalived.conf neu rendern (Primary = Priorität 200)
|
||||
// 5. keepalived.conf neu rendern (Primary = MASTER, Priority 200 → VIP)
|
||||
if pool != nil {
|
||||
localID, _ := loadLocalID()
|
||||
kg := keepalived.New(pool, localID)
|
||||
@@ -109,9 +95,9 @@ func cmdPromote(args []string) int {
|
||||
defer renderCancel()
|
||||
if err := kg.Render(renderCtx); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "promote: keepalived render: %v\n", err)
|
||||
fmt.Println(" → Manuell: edgeguard-ctl render-config --only=keepalived")
|
||||
fmt.Println(" → Manuell: sudo -u edgeguard edgeguard-ctl render-config --only=keepalived")
|
||||
} else {
|
||||
fmt.Println("✓ keepalived.conf neu gerendert (Priority 200)")
|
||||
fmt.Println("✓ keepalived.conf neu gerendert (MASTER, Priority 200)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,8 +105,8 @@ func cmdPromote(args []string) int {
|
||||
fmt.Println("✓ Promotion abgeschlossen. Diese Node ist jetzt der primäre EdgeGuard-Knoten.")
|
||||
fmt.Println()
|
||||
fmt.Println("Empfohlene Nachschritte:")
|
||||
fmt.Println(" 1) sudo systemctl restart edgeguard-api (falls noch nicht laufend)")
|
||||
fmt.Println(" 2) Alte Primary-Node nach Recovery als neuen Standby einrichten:")
|
||||
fmt.Println(" 1) sudo systemctl restart edgeguard-api")
|
||||
fmt.Println(" 2) Übrige/erholte Nodes als Standby auf DIESE Node zeigen lassen:")
|
||||
fmt.Println(" edgeguard-ctl cluster-setup-standby <diese-node-ip>")
|
||||
return 0
|
||||
}
|
||||
@@ -136,25 +122,3 @@ func loadLocalID() (string, error) {
|
||||
}
|
||||
return c.NodeID, nil
|
||||
}
|
||||
|
||||
// updateKeyDBPrimaryURL schreibt den lokalen PG-DSN als cluster:pg-primary-url
|
||||
// in KeyDB, damit alle Nodes im Cluster Writes an diese Node schicken.
|
||||
func updateKeyDBPrimaryURL() error {
|
||||
// edgeguard-api nutzt Unix-Socket-Auth, der DSN ist immer lokal.
|
||||
const localDSN = "postgres://edgeguard@/edgeguard?host=/var/run/postgresql"
|
||||
out, err := exec.Command("redis-cli",
|
||||
"-s", "/var/run/keydb/keydb.sock",
|
||||
"SET", "cluster:pg-primary-url", localDSN,
|
||||
).CombinedOutput()
|
||||
if err != nil {
|
||||
// Fallback: Standard-Port
|
||||
out2, err2 := exec.Command("redis-cli",
|
||||
"-p", "6379",
|
||||
"SET", "cluster:pg-primary-url", localDSN,
|
||||
).CombinedOutput()
|
||||
if err2 != nil {
|
||||
return fmt.Errorf("%v: %s / %v: %s", err, out, err2, out2)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -68,6 +68,10 @@ func cmdRenderConfig(args []string) int {
|
||||
if skipReload {
|
||||
hap.SkipReload = true
|
||||
fw.SkipReload = true
|
||||
sq.SkipReload = true
|
||||
wg.SkipReload = true
|
||||
ub.SkipReload = true
|
||||
cn.SkipReload = true
|
||||
ke.SkipReload = true
|
||||
fr.SkipReload = true
|
||||
}
|
||||
|
||||
@@ -83,6 +83,8 @@ func main() {
|
||||
slog.Error("waf: SPOE agent stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Graceful shutdown (ctx cancelled): gepufferte Alerts flushen.
|
||||
alertWriter.Close()
|
||||
}
|
||||
|
||||
// reload fetches all domain+waf_config pairs from DB and rebuilds engines.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# EdgeGuard — Architektur
|
||||
|
||||
> Status: **v0.1 (Entwurf)** · Stand: 2026-05-08 · Ziel-Plattformen: Debian 13 (Trixie) + Ubuntu 24.04 LTS (Noble Numbat), Architekturen amd64 + arm64.
|
||||
> Status: **in Produktion** (v1.2.x) · Entwurf: 2026-05-08 · **Cluster/HA-Abschnitte an Ist-Stand angeglichen: 2026-06-06** · Plattform: Debian 13 (Trixie), amd64 + arm64.
|
||||
>
|
||||
> ⚠️ **Lesehinweis:** Dieses Dokument war ursprünglich ein Entwurf. Mehrere Cluster/HA-Annahmen wurden anders umgesetzt — maßgeblich sind die mit „**Ist-Stand**" markierten Stellen (§0, §6–§9). Kurzfassung: **Logical Replication** statt Streaming, **keepalived/VRRP** statt Hoster-Floating-IP, **KeyDB optional/ungenutzt** (Cluster-State in PostgreSQL), **kein Write-Proxy**.
|
||||
|
||||
EdgeGuard ist die native Neufassung des bisherigen Docker-basierten Reverse-Proxy/Loadbalancer/Forward-Proxy/VPN-Stacks. Vorbild für Architektur, Build-System und Cluster-Modell ist [`mail-gateway`](../../mail-gateway/docs/architecture.md) (`nmg`); UI-Pattern und Bootstrap-Onliner stammen aus [`netcell-webpanel`](../../netcell-webpanel/CLAUDE.md) (`enconf`).
|
||||
|
||||
@@ -8,14 +10,14 @@ EdgeGuard ist die native Neufassung des bisherigen Docker-basierten Reverse-Prox
|
||||
|
||||
## 0. Leitplanken (nicht verhandelbar)
|
||||
|
||||
- **Kein Docker.** Alle Dienste nativ unter `systemd`, installiert via `apt`. Distro-Pakete für Drittsoftware (HAProxy, Squid, WireGuard, Unbound, PostgreSQL, KeyDB, certbot), eigene `.deb`-Pakete für EdgeGuard-Code (api, ui, ctl).
|
||||
- **Plattform-Matrix:** Debian 13 (Trixie) **und** Ubuntu 24.04 LTS (Noble Numbat), je amd64 + arm64. Alle vier Targets gleichberechtigt.
|
||||
- **Kein Docker.** Alle Dienste nativ unter `systemd`, installiert via `apt`. Distro-Pakete für Drittsoftware (HAProxy, Squid, WireGuard, Unbound, PostgreSQL, keepalived, chrony, certbot), eigene `.deb`-Pakete für EdgeGuard-Code (api, ui, ctl).
|
||||
- **Plattform:** **Debian 13 (Trixie), amd64 + arm64.** Nur Trixie — die Build-/Publish-Pipeline (`Makefile`, `scripts/apt-repo/`) zielt ausschließlich auf `trixie`. _(Eine frühere Ubuntu-24.04-Matrix war geplant, ist aber nicht implementiert.)_
|
||||
- **Auslieferung:** signierte `.deb`-Pakete + Meta-Paket via APT. Bootstrap ist der enconf-analoge curl-Onliner `curl -fsSL https://get.edgeguard.netcell-it.de | sudo bash`.
|
||||
- **HA nativ als Cluster:** N symmetrische Peers, **KeyDB Active-Active** für Shared State + **PostgreSQL Streaming Replication** (single writer, transparenter API-Write-Proxy) + **Floating-IP des Hosters** für HTTP/HTTPS-Ingress (nicht VRRP, nicht DNS-RR).
|
||||
- **Kein WAF, kein IDS, kein DHCP, kein RADIUS, keine Mail-Funktion in v1.** Mail-Gateway ist eigenes Produkt (`nmg`); WAF/CrowdSec/Suricata kommen ggf. in v2.
|
||||
- **HA nativ als Cluster (Ist-Stand 2026-06):** N symmetrische Peers, **PostgreSQL Logical Replication** (ein Publisher/Primary `edgeguard_shared` → N Subscriber; node-lokale Tabellen ausgenommen) + **keepalived/VRRP** für den VIP-Failover (HTTP/HTTPS-Ingress) + **mTLS-Cluster-Agent** (:8443) für Heartbeat/Cert-Sync/Aggregation. **KeyDB ist optional** (`Recommends`) und im Code praktisch ungenutzt; ein Write-Proxy existiert nicht (Writes erfolgen am Primary). _(Der ursprüngliche Entwurf — KeyDB Active-Active, PG-Streaming-Replication mit transparentem Write-Proxy, Floating-IP-statt-VRRP — wurde so nicht umgesetzt; Details in §6–§9.)_
|
||||
- **WAF, IDS/IPS, DHCP, RADIUS inzwischen umgesetzt** (Stand 2026-06): WAF via Coraza+SPOE, IDS/IPS via CrowdSec, DHCP via Kea, RADIUS via FreeRADIUS. Mail-Funktion bleibt ausgeschlossen — Mail-Gateway ist eigenes Produkt (`nmg`).
|
||||
- **Migrations:** `goose` (SQL-Dateien), nicht GORM AutoMigrate.
|
||||
|
||||
**Nicht-Ziele (ausdrücklich):** kein WAF, kein Network-IDS (Suricata), kein IPS (CrowdSec), kein DHCP-Server (Kea), kein RADIUS, keine Mail-Verarbeitung, keine Multi-Tenant-GuardZones in v1, keine ISO-Builds (kein EdgeGuardOS-Klon — nur APT).
|
||||
**Nicht-Ziele (weiterhin):** kein Network-IDS via Suricata (IDS/IPS läuft über CrowdSec), keine Mail-Verarbeitung, keine Multi-Tenant-GuardZones, keine ISO-Builds (kein EdgeGuardOS-Klon — nur APT). _(Historisch waren auch WAF/DHCP/RADIUS/IPS Nicht-Ziele — siehe oben, inzwischen umgesetzt.)_
|
||||
|
||||
---
|
||||
|
||||
@@ -33,12 +35,13 @@ EdgeGuard ist die native Neufassung des bisherigen Docker-basierten Reverse-Prox
|
||||
|
||||
| Komponente | Rolle |
|
||||
|---|---|
|
||||
| `edgeguard-api` | Go/Gin REST-API, bindet `127.0.0.1:9443`, Reads aus lokaler PG, Writes an Cluster-Primary |
|
||||
| `edgeguard-scheduler` | Cron-artige Jobs (ACME-Renewal-Hook, Backup, Health-Aggregation, License-Heartbeat) |
|
||||
| `edgeguard-ctl` | CLI für Setup/Wartung (`initdb`, `migrate`, `cluster-join`, `promote`, `dump-config`) |
|
||||
| `edgeguard-api` | Go/Gin REST-API, bindet `127.0.0.1:9443`, Reads/Writes auf lokaler PG. Geteilte Tabellen werden vom Primary per Logical Replication an Subscriber verteilt; Writes sollen am Primary erfolgen (keine Write-Proxy-Umleitung im Code). |
|
||||
| `edgeguard-waf` | Coraza-WAF-Agent (HAProxy SPOE) — Binary im `edgeguard-api`-Paket, eigene systemd-Unit |
|
||||
| `edgeguard-scheduler` | Cron-artige Jobs (ACME-Renewal-Hook, Backup, Health-Aggregation, Stale-Node-Sweep, License-Heartbeat) |
|
||||
| `edgeguard-ctl` | CLI für Setup/Wartung (`initdb`, `migrate`, `cluster-join`, `promote`, `cluster-init-replication`, `cluster-setup-standby`, `dump-config`) |
|
||||
| `management-ui` | React 19 + AntD 6 + Vite, statisch unter `/usr/share/edgeguard/ui/`, von `edgeguard-api` per gin `StaticFS` ausgeliefert (HAProxy proxied Management-FQDN dorthin) |
|
||||
| **PostgreSQL 16** | Single Source of Truth — Domains, Backends, Routing-Rules, ACLs, Peers, etc. |
|
||||
| **KeyDB** (Redis-kompatibel) | Active-Active-Replication, Cluster-State, Locks, Rate-Counter, Pub/Sub für Config-Reload |
|
||||
| **PostgreSQL 16/17** | Single Source of Truth — Domains, Backends, Routing-Rules, ACLs, Peers, Cluster-State (`ha_nodes`), Lizenz etc. |
|
||||
| **KeyDB** (optional) | `Recommends`, im Code praktisch ungenutzt — kein Redis-Client in `go.mod`. Cluster-State/Heartbeat/Locks liegen in PostgreSQL, nicht in KeyDB. |
|
||||
|
||||
---
|
||||
|
||||
@@ -61,10 +64,15 @@ EdgeGuard ist die native Neufassung des bisherigen Docker-basierten Reverse-Prox
|
||||
│ ├── wireguard/ # WireGuard-Config-Generator (wg-quick + wg syncconf)
|
||||
│ ├── unbound/ # Unbound-Config-Generator (Forwarder + Cluster-DNS)
|
||||
│ ├── firewall/ # nftables-Ruleset-Generator
|
||||
│ ├── cluster/ # Join/Promote/Peer-Discovery, KeyDB-Replication-Setup, pg_basebackup
|
||||
│ ├── proxy/ # API-Write-Proxy-Middleware (Replica → Primary), mTLS-Calls
|
||||
│ ├── aggregator/ # Cluster-View-APIs (alle Backends, alle Peers, alle Health-States)
|
||||
│ └── license/ # License-Validation, License-Leader-Election (KeyDB-Lock)
|
||||
│ ├── cluster/ # Join/Promote/Peer-Discovery, Heartbeat, Logical-Replication-Setup, confighash
|
||||
│ ├── keepalived/ # keepalived/VRRP-Config-Generator (VIP-Failover)
|
||||
│ ├── chrony/ # chrony-Config-Generator (NTP)
|
||||
│ ├── kea/ # Kea-DHCP4-Config-Generator
|
||||
│ ├── freeradius/ # FreeRADIUS-Config-Generator (RADIUS)
|
||||
│ ├── crowdsec/ # CrowdSec-IDS/IPS-Management (managed-wenn-installiert)
|
||||
│ ├── waf/ # Coraza-WAF-Engine + SPOE-Agent-Logik
|
||||
│ ├── aggregator/ # Cluster-View-APIs via mTLS (read-only Fan-Out + Trigger-Actions)
|
||||
│ └── license/ # License-Validation (jeder Node verifiziert eigenständig — KEINE KeyDB-Leader-Election)
|
||||
├── management-ui/ # React 19 + AntD 6 + Vite (Struktur 1:1 wie netcell-webpanel/management-ui/)
|
||||
├── packaging/
|
||||
│ └── debian/
|
||||
@@ -94,17 +102,17 @@ EdgeGuard ist die native Neufassung des bisherigen Docker-basierten Reverse-Prox
|
||||
|
||||
## 3. Debian-Pakete
|
||||
|
||||
Drei Pakete + Meta — analog nmg, kein WAF-Paket weil kein WAF in v1.
|
||||
Drei Pakete + Meta — analog nmg. Der WAF-Agent `edgeguard-waf` ist **kein eigenes Paket**, sondern liegt als zusätzliches Binary im `edgeguard-api`-Paket (eigene systemd-Unit).
|
||||
|
||||
| Paket | Arch | Inhalt | Depends |
|
||||
|---|---|---|---|
|
||||
| `edgeguard-api` | amd64, arm64 | `/usr/bin/edgeguard-{api,scheduler,ctl}`, Unit-Files, Migrations, Default-Configs | `postgresql-16`, `keydb-server`, `haproxy`, `squid`, `wireguard-tools`, `unbound`, `nftables`, `certbot`, `openssl` |
|
||||
| `edgeguard-api` | amd64, arm64 | `/usr/bin/edgeguard-{api,scheduler,ctl,waf}`, Unit-Files, Migrations, Default-Configs | `postgresql-16 \| postgresql-17`, `haproxy (>=2.8)`, `squid`, `wireguard-tools`, `unbound`, `chrony`, `kea-dhcp4-server`, `freeradius`, `nftables`, `keepalived`, `certbot`, `openssl`, `sudo`, `adduser`, `systemd`, `ca-certificates`, `ulogd2`, `ulogd2-json` u. a. · _Recommends:_ `edgeguard-keydb`, `apparmor`, `fail2ban` · _CrowdSec: managed-wenn-installiert (kein Depends)_ |
|
||||
| `edgeguard-ui` | all | `/usr/share/edgeguard/ui/` (statische Build-Artefakte) | `edgeguard-api (= ${binary:Version})` |
|
||||
| `edgeguard-meta` | all | keine Dateien, nur `Depends` | `edgeguard-api`, `edgeguard-ui` |
|
||||
|
||||
Pro Release: 1 arch-spezifisch × 2 Dists × 2 Arches = 4 `.deb` + 2 arch-agnostische × 2 Dists = 4 `.deb` → **8 Artefakte je Release**.
|
||||
Pro Release: 1 arch-spezifisches Paket (`edgeguard-api`) × **1 Dist (trixie)** × 2 Arches = 2 `.deb` + 2 arch-agnostische (`edgeguard-ui`, `edgeguard-meta`) = **4 Artefakte je Release**. (Build/Publish-Pipeline zielt nur auf `trixie`.)
|
||||
|
||||
**KeyDB-Herkunft:** KeyDB ist weder in `trixie` noch `noble` in den offiziellen Repos. Wir bauen es aus Source (amd64 + arm64), veröffentlichen es parallel im eigenen APT-Repo. `edgeguard-api` `Depends: keydb-server` löst aus unserem Repo aus.
|
||||
**KeyDB-Herkunft:** KeyDB ist optional (`Recommends: edgeguard-keydb`), nicht in den offiziellen trixie-Repos. Falls genutzt, aus Source gebaut + im eigenen APT-Repo veröffentlicht. Im aktuellen Code wird KeyDB nicht benötigt — siehe §7.
|
||||
|
||||
**Build-Werkzeug:** **direkter `dpkg-deb`-Build** analog WebPanel/EdgeGuardOS-Pattern. **Nicht** `dh_make`/`debhelper`, **nicht** `fpm`. Konsistenz mit existierendem Workflow.
|
||||
|
||||
@@ -162,7 +170,8 @@ Entspricht FHS — keine Überraschungen für Admins, Lintian-clean.
|
||||
|
||||
| Unit | Typ | Depends-on | User | Restart |
|
||||
|---|---|---|---|---|
|
||||
| `edgeguard-api.service` | `simple` | `postgresql.service`, `keydb-server.service` | `edgeguard` | `on-failure`, `RestartSec=5` |
|
||||
| `edgeguard-api.service` | `simple` | `Requires=postgresql.service`; `After=`/`Wants=keydb-server.service` (KeyDB nur weich/optional) | `edgeguard` | `on-failure`, `RestartSec=5` |
|
||||
| `edgeguard-waf.service` | `simple` | `edgeguard-api.service` (Coraza SPOE-Agent) | `edgeguard` | `on-failure` |
|
||||
| `edgeguard-scheduler.service` | `simple` | `edgeguard-api.service` | `edgeguard` | `on-failure` |
|
||||
| `edgeguard-cert-deploy.path` | `path` | — | — | — |
|
||||
| `edgeguard-firewall.service` | `oneshot`, `RemainAfterExit=true` | — | root | — |
|
||||
@@ -183,7 +192,7 @@ SystemCallFilter=@system-service
|
||||
ReadWritePaths=/var/lib/edgeguard /var/log/edgeguard /etc/edgeguard
|
||||
```
|
||||
|
||||
Drittsoftware (HAProxy, Squid, WireGuard via `wg-quick@.service`, Unbound, nftables) läuft als **Distro-Units**. EdgeGuard generiert deren Config + signalisiert Reload, übernimmt aber die Service-Verwaltung **nicht**.
|
||||
Drittsoftware läuft als **Distro-Units** — EdgeGuard generiert deren Config + signalisiert Reload/Restart, übernimmt aber die Service-Verwaltung weitgehend nicht. Renderer existieren für: **HAProxy, Squid, WireGuard (`wg-quick@.service`), Unbound, nftables, keepalived, chrony, Kea (`kea-dhcp4-server`), FreeRADIUS** (letzte beide default-off). **CrowdSec** (`crowdsec` + `crowdsec-firewall-bouncer`) wird gemanagt, wenn installiert (kein Depends).
|
||||
|
||||
API bindet auf `127.0.0.1:9443` (nicht öffentlich). HAProxy terminiert TLS auf `:443`, leitet `/.well-known/acme-challenge/*` und Management-FQDN-Traffic an die API weiter, routet alle anderen Hosts per ACL an die User-Backends.
|
||||
|
||||
@@ -191,29 +200,28 @@ API bindet auf `127.0.0.1:9443` (nicht öffentlich). HAProxy terminiert TLS auf
|
||||
|
||||
## 6. Datenbank-Setup
|
||||
|
||||
- **PostgreSQL 16**, Distro-Paket `postgresql-16`.
|
||||
- **Verbindung:** Unix-Socket (`/var/run/postgresql`) für lokale Reads + Writes der API. TCP/5432 mit TLS-Client-Cert nur zwischen Cluster-Peers für Streaming Replication.
|
||||
- **Topologie:** **ein logischer Primary** zu jedem Zeitpunkt, N Read-Replicas. Lokale API liest immer aus lokaler PG; Writes routet die API-Write-Proxy-Middleware transparent an den aktuellen Primary (KeyDB-Key `cluster:pg-primary-url`).
|
||||
- **Migrations:** `goose` (SQL-Dateien in `internal/database/migrations/`, via `//go:embed` ins Binary gepackt). **Nicht** GORM AutoMigrate.
|
||||
- **PostgreSQL 16/17**, Distro-Paket `postgresql-16 | postgresql-17`.
|
||||
- **Verbindung:** Unix-Socket (`/var/run/postgresql`) für lokale Reads + Writes der API. TCP/5432 (Rolle `edgeguard_replicator`) nur zwischen Cluster-Peers für die Logical-Replication-Verbindung.
|
||||
- **Topologie (Ist-Stand):** **Logical Replication** — ein Primary publiziert `edgeguard_shared` (alle Tabellen außer `localOnlyTables`), N Subscriber (`edgeguard_sub`, `wal_level=logical`, Initialkopie via `copy_data=true`). Jeder Node hat eine **eigene beschreibbare** PG-Instanz; geteilte Config fließt vom Primary zu den Subscribern. **Es gibt keinen Write-Proxy** — Schreibzugriffe auf geteilte Tabellen müssen am Primary erfolgen; ein Subscriber-Write auf eine replizierte Tabelle würde nicht propagieren (Drift-Banner erkennt das via `config_hash`). Primary-Erkennung zuverlässig über `pg_publication`; der Standby-Bootstrap läuft per Logical Subscription (kein `pg_basebackup` im aktiven Pfad).
|
||||
- **node-lokale Tabellen** (nicht repliziert): `ha_nodes`, `network_interfaces`, `ip_addresses`, `static_routes`, `cluster_settings`, `dns_settings`, `ntp_settings`, `dhcp_settings`, `radius_settings`, `system_settings`, `join_tokens_used`, `audit_log`, `alert_events`, `backups`, `goose_db_version` (Liste: `cmd/edgeguard-ctl/cluster_replication.go` `localOnlyTables`).
|
||||
- **Migrations:** `goose` (SQL-Dateien in `internal/database/migrations/`, via `//go:embed`). **Nicht** GORM AutoMigrate.
|
||||
|
||||
GORM bleibt als ORM für Query-Komfort; nur das Schema-Management wechselt zu `goose`.
|
||||
GORM bleibt als ORM für Query-Komfort; Schema-Management läuft über `goose`.
|
||||
|
||||
---
|
||||
|
||||
## 7. KeyDB Active-Active
|
||||
## 7. Cluster-State & KeyDB (Ist-Stand: PostgreSQL-zentrisch)
|
||||
|
||||
KeyDB ersetzt Redis. **Active-Active Replication** (Multi-Master, operation-basiert, split-brain-tolerant).
|
||||
> **Hinweis:** Der ursprüngliche Entwurf sah KeyDB Active-Active als Cluster-State-Layer vor. **Im Code ist das nicht umgesetzt** — es gibt **keinen Redis/KeyDB-Client** (`go.mod` enthält nur `pgx`). KeyDB ist optional (`Recommends`) und wird vom laufenden System nicht benötigt.
|
||||
|
||||
**Verwendung:**
|
||||
- `cluster:pg-primary-url` — wer ist aktueller PG-Primary?
|
||||
- `cluster:license-leader` — Lock für License-Heartbeat (`SET … NX EX 60`)
|
||||
- `cluster:license-status` — Cache des Lizenz-Validate-Ergebnisses (TTL 24 h)
|
||||
- `cluster:nodes:<node-id>` — Heartbeat-Marker (TTL 2 min)
|
||||
- `ratelimit:<scope>:<key>` — Rate-Counter (HINCRBY-Ops mergen korrekt)
|
||||
- `acme:lock:<domain>` — verhindert Parallel-Issue auf zwei Nodes
|
||||
- Pub/Sub: `edgeguard:config-changed` — alle Nodes regenerieren Config
|
||||
**Wie Cluster-State tatsächlich gehalten wird:**
|
||||
- **PG-Primary** — über `pg_publication` (`edgeguard_shared`) ermittelt; die Peer-Adresse für Pushes stammt aus `setup.json` `PrimaryFQDN`.
|
||||
- **Node-Heartbeat/-Status** — Spalten `last_seen`/`status` in PG `ha_nodes`. Jeder Node bumpt seine Row alle 30s (`runClusterHeartbeat`); Secondary→Primary (`runPrimaryPush`) und Primary→Secondary (`runPeerPush`) pushen sich gegenseitig per mTLS (30s, bidirektional). `SweepStaleNodes` (Scheduler) flippt Peers nach 2 min ohne Heartbeat auf `offline`.
|
||||
- **Lizenz** — jeder Node verifiziert **eigenständig** gegen `license.netcell-it.com` (kein Leader-Lock); Ergebnis in PG `licenses`.
|
||||
- **ACME** — kein verteilter Issue-Lock implementiert (Single-Node-Default; bei Cluster Issue am aktiven/Primary-Node).
|
||||
- `cluster:pg-primary-url` in KeyDB wird von `edgeguard-ctl promote` **geschrieben, falls KeyDB läuft**, aber von der API **nie gelesen** (advisory/Altlast).
|
||||
|
||||
KeyDB hört nur auf `127.0.0.1:6379` für lokale Clients und `<node-ip>:16379` (TLS) für Peer-Replication.
|
||||
_Falls KeyDB künftig wieder eingeführt wird (Rate-Limiting-Counter, Pub/Sub-Config-Reload): hört auf `127.0.0.1:6379` lokal und `<node-ip>:16379` (TLS) für Peer-Replication. Derzeit ungenutzt._
|
||||
|
||||
---
|
||||
|
||||
@@ -234,7 +242,7 @@ Unbound erfüllt zwei Rollen, beide aus PG generiert:
|
||||
- **Local-Zone** `eg.cluster.` enthält A/AAAA-Records aller Cluster-Peers (Node-Hostnamen aus PG `ha_nodes`).
|
||||
- Beispiel: `node1.eg.cluster → 10.42.0.11`, `node2.eg.cluster → 10.42.0.12`.
|
||||
- Wird bei jedem Node-Join/-Leave aus PG regeneriert + via `edgeguard:config-changed` Pub/Sub auf allen Peers neu geladen (`unbound-control reload`).
|
||||
- Cluster-interner Traffic (PG-Replication, KeyDB-Replication, mTLS-API-Calls, Cert-Push) löst Peer-Adressen ausschließlich über diese Zone auf — kein DNS-Roundtrip ins öffentliche Internet, keine `/etc/hosts`-Synchronisation.
|
||||
- Cluster-interner Traffic (PG-Logical-Replication, mTLS-Agent-Calls auf :8443, Cert-Push) löst Peer-Adressen ausschließlich über diese Zone auf — kein DNS-Roundtrip ins öffentliche Internet, keine `/etc/hosts`-Synchronisation.
|
||||
- `<node-name>.eg.cluster` ist **nicht extern erreichbar** (nur über Unbound der Cluster-Peers).
|
||||
|
||||
### Config-Schichten
|
||||
@@ -253,54 +261,56 @@ Reload via `unbound-control reload` (kein Restart, keine Cache-Invalidierung au
|
||||
|
||||
## 8. Cluster-Topologie & HA pro Service
|
||||
|
||||
**N symmetrische Peers** (1 … N Nodes, jeder vollwertig). Keine VRRP, keine Master/Backup-Rollen für Daten-Services. Public-IP: **Floating-IP des Hosters** (siehe §9).
|
||||
**N symmetrische Peers** (1 … N Nodes, jeder vollwertig). Public-IP-Failover via **VIP/VRRP (keepalived)** — siehe §9 (der ursprünglich geplante „Floating-IP statt VRRP"-Ansatz wurde **nicht** umgesetzt).
|
||||
|
||||
| Service | HA-Strategie |
|
||||
|---|---|
|
||||
| **HAProxy** | stateless, pro Node identisch. Floating-IP zeigt zum aktuellen aktiven Node; bei Node-Ausfall API-Call zum Hoster (oder manueller Switch) reicht. ACME-Issue nur auf License-Leader (KeyDB-Lock); Zerts werden via PG/mTLS an alle verteilt. |
|
||||
| **Squid** | stateless (Cache lokal, kein Sync nötig). Pro Node identische ACL-Config. |
|
||||
| **VIP/keepalived** | VRRP (`vrrp_instance`), MASTER/BACKUP per `pg_role` (primary→prio 200/MASTER, standby→100/BACKUP). VIPs aus `ip_addresses` (`is_vip=true`). Trägt den HTTP/HTTPS-Ingress. |
|
||||
| **HAProxy** | stateless, pro Node identisch. Hört auf der VIP des aktiven Node. ACME-Issue ohne verteilten Lock (Single-/Primary-Node); Zerts werden via mTLS (`/agent/cluster/tls-certs`) an alle verteilt. |
|
||||
| **Squid** | stateless (Cache lokal). Pro Node identische ACL-Config. |
|
||||
| **WireGuard** | siehe §8.1 |
|
||||
| **Unbound** | stateless (Cache lokal). Pro Node identische Forwarder-Config + identische Cluster-internen Local-Zones (siehe §7.5). |
|
||||
| **nftables** | pro Node identisch, Ruleset aus PG generiert. `crowdsec_blocklist`/`threat_intel_blocklist`-Sets entfallen in v1 (kein CrowdSec). |
|
||||
| **edgeguard-api** | pro Node, Reads lokal, Writes via Proxy zu Primary. |
|
||||
| **edgeguard-ui** | statisch, pro Node identisch. |
|
||||
| **PostgreSQL** | Streaming Replication, manueller Promote (siehe nmg §6.2). |
|
||||
| **KeyDB** | Active-Active. |
|
||||
| **Unbound** | stateless (Cache lokal). Pro Node identische Forwarder-Config + Cluster-Local-Zones (§7.5). |
|
||||
| **nftables** | pro Node, Ruleset aus PG generiert. CrowdSec-Blocklist via `crowdsec-firewall-bouncer` (eigene Sets), wenn CrowdSec installiert. |
|
||||
| **edgeguard-api** | pro Node, Reads lokal. Writes auf geteilte Tabellen am Primary (kein Write-Proxy). |
|
||||
| **edgeguard-ui / edgeguard-waf** | statisch bzw. pro Node identisch. |
|
||||
| **PostgreSQL** | **Logical Replication** (Publisher→Subscriber), manueller Promote (§8.2). |
|
||||
| **KeyDB** | optional/ungenutzt (§7). |
|
||||
|
||||
### 8.1 WireGuard im Cluster
|
||||
|
||||
Drei Optionen, für v1 wählen wir **Option A**:
|
||||
|
||||
- **A — Geteilte Server-Identität (gewählt):** alle Peers haben **denselben** Server-Privatkey + dasselbe Listen-Port. Floating-IP routet UDP zum aktiven Node. Bei Failover: Floating-IP wandert, Clients schicken Pakete zum neuen Node, neuer Handshake (~1–2s Latenz beim ersten Paket). Replay-Protection-Counter werden nicht repliziert — beim Failover macht der Client neuen Handshake, alte Counter sind irrelevant.
|
||||
- **A — Geteilte Server-Identität (gewählt):** alle Peers haben **denselben** Server-Privatkey + dasselbe Listen-Port. Die **VIP (keepalived)** trägt das WireGuard-UDP zum aktiven Node. Bei Failover: VIP wandert, Clients schicken Pakete zum neuen Node, neuer Handshake (~1–2s Latenz beim ersten Paket). Replay-Protection-Counter werden nicht repliziert — beim Failover macht der Client neuen Handshake, alte Counter sind irrelevant.
|
||||
- B — Pro Node eigene Identität, Client kennt alle: Client-Configs haben mehrere `[Peer]`-Blöcke. Aufwendiger zu provisionieren, kein Failover-Vorteil.
|
||||
- C — Aktiv/Standby per License-Leader-Pattern: nur ein Node hat WireGuard aktiv, andere idle. Verschwendet Kapazität.
|
||||
|
||||
**Begründung A:** Privatkey ist in PG (verschlüsselt mit `edgeguard.key`), wird beim Cluster-Join an neue Peers verteilt. WireGuard handelt selbständig neue Sessions aus, kein State-Sync nötig. Operation-Tools (Peer hinzufügen/entfernen) wirken auf alle Nodes via `edgeguard:config-changed` Pub/Sub + lokales `wg syncconf`.
|
||||
**Begründung A:** Privatkey liegt verschlüsselt in PG, wird per Logical Replication an die Peers verteilt. WireGuard handelt selbständig neue Sessions aus, kein State-Sync nötig. Peer-Änderungen propagieren über die Logical Replication; Secondaries erkennen die Änderung am `config_hash` (`runSecondaryConfigRender`, 5-min-Tick) und re-rendern lokal → `wg syncconf`.
|
||||
|
||||
### 8.2 Manual Promote (PG-Primary-Failover)
|
||||
|
||||
1:1 nmg-Pattern (siehe `mail-gateway/docs/architecture.md` §6.2). Bei Ausfall des Primary antworten Config-Writes mit `503 + actionable Error`. Admin promotet via UI/CLI. Datenebene (HAProxy/Squid/WireGuard/Unbound) läuft unbeeinträchtigt weiter, weil jeder Node eine lokale PG-Replica hat.
|
||||
Bei Ausfall des Primary läuft die Datenebene (HAProxy/Squid/WireGuard/Unbound) weiter, weil jeder Node eine lokale, lesbare PG-Instanz (Logical-Subscriber) hat. Schreibzugriffe auf geteilte Config müssen am Primary erfolgen — fällt der Primary aus, promotet der Admin manuell via **`edgeguard-ctl promote`**. Das ist Logical-Replication-aware: es löst die Subscription zum toten Primary (`DISABLE` + `slot_name=NONE` + `DROP`, hängt also nicht am toten Publisher), richtet die Node via `setupReplicationPrimary` als Publisher ein (Rolle/Secret/`wal_level=logical` inkl. **PG-Restart** falls nötig/Publication), setzt `ha_nodes.pg_role='primary'` und rendert keepalived (→ MASTER, übernimmt die VIP). Erholte Nodes danach mit `edgeguard-ctl cluster-setup-standby <neuer-primary>` zurückhängen. **Achtung:** echtes Cross-Node-Failover ist nur im Drill testbar — die Bausteine (Drop-Subscription, Publication, Restart) sind dieselben wie in `cluster-init-replication`/`cluster-setup-standby`.
|
||||
|
||||
### 8.3 License-Leader-Election
|
||||
### 8.3 License-Verifikation
|
||||
|
||||
Ein einziger Node kontaktiert `license.netcell-it.com` (KeyDB-Lock, 60-s-TTL). Ergebnis cluster-weit in `cluster:license-status` (TTL 24 h). `active_servers`-Verbrauchswert = Count der Peers mit Heartbeat < 2 min.
|
||||
**Kein Leader-Election** (anders als ursprünglich geplant). Jeder Node verifiziert **eigenständig** gegen `license.netcell-it.com` (Scheduler-Tick), Ergebnis in PG `licenses`. `active_servers` = Anzahl Peers mit Heartbeat < 2 min (aus `ha_nodes`). Ein KeyDB-Lock existiert nicht.
|
||||
|
||||
---
|
||||
|
||||
## 9. Public-Ingress — Floating-IP statt VRRP
|
||||
## 9. Public-Ingress — VIP via keepalived/VRRP
|
||||
|
||||
**Problem:** HTTP-Clients machen kein automatisches Failover bei DNS-RR (anders als MTAs). Ein toter A-Record = 50% Fehler bis DNS-TTL.
|
||||
> **Ist-Stand:** Umgesetzt ist **VIP-Failover über keepalived (VRRP)** — nicht der ursprünglich angedachte „Floating-IP des Hosters"-Ansatz. Es gibt **keinen** Hoster-API-Code und **keinen** `POST /cluster/promote-this-node`-Endpoint.
|
||||
|
||||
**Entscheidung:** **Floating-IP des Hosters**. Der Hoster bietet eine API zum Umroute der IP zwischen Servern (z. B. via REST oder DNS-Update bei dynamischer Anycast-Lösung). Failover dauert Sekunden, kein VRRP-Drama, kein "VIP verschwindet"-Problem aus dem alten Setup.
|
||||
**Mechanik (`internal/keepalived`):**
|
||||
- Renderer erzeugt `/etc/keepalived/keepalived.conf` mit `vrrp_instance` (unicast peer, `virtual_router_id`, `authentication`).
|
||||
- **State/Priorität aus `pg_role`:** Primary → `state MASTER`, `priority 200`; Standby → `state BACKUP`, `priority 100`.
|
||||
- **VIPs** kommen aus `ip_addresses` (`is_vip=true`, `active=true`), inkl. Interface; managed via `systemctl reload-or-restart keepalived`.
|
||||
- Bei Node-/PG-Ausfall übernimmt VRRP die VIP auf den verbleibenden Node (Sekundenbereich).
|
||||
|
||||
Optionen pro Hoster:
|
||||
1. **Provider-Floating-IP** (gewünscht): API-Call schaltet IP um. EdgeGuard exponiert `POST /api/v1/cluster/promote-this-node`, das die Hoster-API aufruft.
|
||||
2. **DNS-RR mit kurzer TTL (60s)** als Notlösung wenn keine Floating-IP verfügbar.
|
||||
3. **Anycast/BGP** als Premium-Variante (für Enterprise).
|
||||
**Tooling:** `GET/PUT /cluster/vip-settings`, `GET /cluster/vip-status`, `POST /cluster/vip-test` (Letzteres bewegt eine VIP testweise per `ip addr add/del` zwischen Nodes — kein Hoster-Call).
|
||||
|
||||
**v1-Default:** Single-Node mit fest zugewiesener Floating-IP. Cluster-Erweiterung kommt mit Phase 2.
|
||||
**v1-Default:** Single-Node. Im Cluster trägt der MASTER (Primary) die VIP.
|
||||
|
||||
⚑ **OFFEN:** Welcher Hoster ist Standard? API-Spec dokumentieren sobald geklärt.
|
||||
⚑ **OFFEN (Altlast-Bereinigung):** Doku-Abschnitte/Code, die noch „Floating-IP des Hosters" implizieren, sind historisch — der reale Pfad ist keepalived/VRRP.
|
||||
|
||||
---
|
||||
|
||||
@@ -312,7 +322,7 @@ curl -fsSL https://get.edgeguard.netcell-it.de | sudo bash
|
||||
|
||||
Schritte (idempotent, analog `netcell-webpanel/install.sh`):
|
||||
|
||||
1. **OS-Detection** (`/etc/os-release`): nur Trixie *oder* Noble, sonst Abbruch.
|
||||
1. **OS-Detection** (`/etc/os-release`): nur Debian 13 (Trixie), sonst Abbruch.
|
||||
2. **Arch-Detection**: nur amd64 *oder* arm64.
|
||||
3. **Base-Deps:** `curl gnupg ca-certificates apt-transport-https`.
|
||||
4. **APT-Keyrings:**
|
||||
@@ -329,7 +339,7 @@ curl -fsSL https://get.edgeguard.netcell-it.de | sudo bash -s -- \
|
||||
--token <cluster-join-token>
|
||||
```
|
||||
|
||||
`edgeguard-ctl cluster-join` führt aus: PG-Basebackup vom Primary, KeyDB-Replication-Setup, Node-Registrierung in `ha_nodes`, TLS-Cert-Pull via mTLS, Config-Regeneration, Service-Start.
|
||||
`edgeguard-ctl cluster-join` führt aus: TLS-Cert-Pull via mTLS (CSR→issue-cert), Node-Registrierung in `ha_nodes` (`autoRegister`), Setup als **Logical-Replication-Subscriber** (`cluster-setup-standby`: `CREATE SUBSCRIPTION … copy_data=true`, Initialkopie der geteilten Tabellen), Config-Regeneration, Service-Start. _(Kein `pg_basebackup`, kein KeyDB-Setup — beides war nur im ursprünglichen Entwurf.)_
|
||||
|
||||
---
|
||||
|
||||
@@ -337,7 +347,7 @@ curl -fsSL https://get.edgeguard.netcell-it.de | sudo bash -s -- \
|
||||
|
||||
- **Primärquelle:** Gitea Package Registry (`https://git.netcell-it.de/api/packages/projekte/debian`).
|
||||
- **Kunden-Mirror:** `https://apt.netcell-it.de/edgeguard/` (rsync von Gitea).
|
||||
- **Suiten:** `stable` · `testing` · `security` — pro Codename (`trixie`, `noble`).
|
||||
- **Suiten:** `stable` · `testing` · `security` — Codename `trixie`.
|
||||
- **Signatur:** GPG-Key `netcell-edgeguard-signing`, ausgeliefert in `/etc/apt/keyrings/`.
|
||||
- **Update-Check-API:** `GET /api/v1/system/package-versions` → pro `edgeguard-*`-Paket `{name, installed, available, reboot_required}`.
|
||||
- **Upgrade-Trigger:** `POST /api/v1/system/upgrade` startet `systemd-run --unit=edgeguard-upgrade.service --collect …` (HTTP-Response geht VOR dem Upgrade raus, weil API beim Self-Update stirbt — Pattern aus `netcell-webpanel/management-agent/internal/handlers/update.go:105`).
|
||||
@@ -355,13 +365,13 @@ Build-/Release-Scripts identisch zu `mail-gateway/scripts/apt-repo/`.
|
||||
- **Lizenzserver:** `https://license.netcell-it.com` (öffentlich, kein API-Key).
|
||||
- **Verify-Endpoint:** `GET /api/v1/licenses/{key}/verify?system_id={fp}&system_name={host}&active_domains={n}`.
|
||||
- **Fingerprint:** `SHA256(/etc/machine-id + erste-aktive-MAC + hostname)`.
|
||||
- **Caching:** Live → KeyDB `cluster:license-status` (TTL 24h) → `/var/lib/edgeguard/trial.json` (30 Tage) → `expired`.
|
||||
- **Leader-Election** wie nmg §6.3.
|
||||
- **Caching:** Live-Verify → Ergebnis in PG `licenses` → `/var/lib/edgeguard/trial.json` (30-Tage-Trial-Fallback) → `expired`.
|
||||
- **Keine Leader-Election** — jeder Node verifiziert eigenständig (§8.3).
|
||||
|
||||
### 12.2 ACME
|
||||
|
||||
- **certbot** (Distro-Paket) mit `--webroot=/var/lib/edgeguard/acme` — HAProxy ACL `path_beg /.well-known/acme-challenge/` proxied diese Pfade an `edgeguard-api`, das die Challenge-Tokens aus der Webroot-Dir ausliefert.
|
||||
- **Lock vor Issue:** `acme:lock:<domain>` in KeyDB verhindert Parallel-Issue auf zwei Nodes.
|
||||
- **Cluster-Locking:** derzeit **kein** verteilter Issue-Lock implementiert (Single-Node-Default; im Cluster sollte ACME am Primary/aktiven Node laufen). _(Der ursprünglich geplante KeyDB-`acme:lock:<domain>` existiert nicht.)_
|
||||
- **Deploy-Hook:** schreibt fertiges PEM (cert+chain+key kombiniert) nach `/etc/edgeguard/tls/<domain>.pem` und triggert `systemctl reload haproxy`. HAProxy lädt den `crt /etc/edgeguard/tls/`-Verzeichnisinhalt neu.
|
||||
- **Cert-Verteilung im Cluster:** Issuing-Node pushed via mTLS-API an alle Peers, Zerts landen in `/etc/edgeguard/tls/`.
|
||||
|
||||
@@ -384,14 +394,12 @@ Komponentenbibliothek, Theme, Layouts, Navigations-Struktur, Form-Patterns, i18n
|
||||
|
||||
## 14. Plattform-Matrix
|
||||
|
||||
| Distribution | Codename | Arch | Status v1 |
|
||||
| Distribution | Codename | Arch | Status |
|
||||
|---|---|---|---|
|
||||
| Debian 13 | trixie | amd64 | Tier 1 |
|
||||
| Debian 13 | trixie | arm64 | Tier 1 |
|
||||
| Ubuntu 24.04 LTS | noble | amd64 | Tier 1 |
|
||||
| Ubuntu 24.04 LTS | noble | arm64 | Tier 1 |
|
||||
|
||||
Andere Distributionen (Debian 12, Ubuntu 22.04, RHEL/Rocky) sind **nicht unterstützt**. Installer bricht hart ab.
|
||||
**Nur Debian 13 (Trixie).** Die Build-/Publish-Pipeline (`Makefile`, `scripts/apt-repo/`) zielt ausschließlich auf `trixie`; der Installer bricht auf anderem OS hart ab. _(Eine ursprünglich geplante Ubuntu-24.04-„noble"-Matrix ist nicht implementiert.)_ Andere Distributionen (Debian 12, Ubuntu, RHEL/Rocky) sind **nicht unterstützt**.
|
||||
|
||||
---
|
||||
|
||||
@@ -402,7 +410,7 @@ EdgeGuard-Native ist eigenes Repo (`git.netcell-it.de/projekte/edgeguard-native`
|
||||
1. **Frische Installation** auf Test-VM via `install.sh`.
|
||||
2. **Config-Export** aus altem Stack (`edgeguard-ctl export --from-docker`) — liest aus alter PG, schreibt in neues Format.
|
||||
3. **Validierung** Side-by-Side (alter Stack auf einem Server, neuer Stack auf anderem, Traffic vergleichen).
|
||||
4. **Cutover** via Floating-IP-Switch.
|
||||
4. **Cutover** via VIP-Umzug (keepalived) bzw. DNS-Umstellung.
|
||||
|
||||
Der alte `proxy-lb-waf`-Code bleibt für Bestandskunden im Wartungsmodus, keine neuen Features.
|
||||
|
||||
@@ -410,6 +418,6 @@ Der alte `proxy-lb-waf`-Code bleibt für Bestandskunden im Wartungsmodus, keine
|
||||
|
||||
## Offene Punkte
|
||||
|
||||
- **Hoster + Floating-IP-API** (§9): Spec dokumentieren.
|
||||
- **WireGuard-State-Replication** in der Praxis testen (Handshake-Latenz nach Floating-IP-Switch messen).
|
||||
- **Failover-Drill:** `edgeguard-ctl promote` (Logical-aware) + anschließendes `cluster-setup-standby` in einem echten 2-Node-Failover durchspielen (inkl. VIP-Umzug, WireGuard-Handshake-Latenz). _(Code-Altlasten `internal/proxy`-Stub und `promote.go`-`standby.signal` wurden 2026-06 bereinigt.)_
|
||||
- **Optional KeyDB** (Rate-Limit-Counter, Pub/Sub-Config-Reload) — falls je benötigt; aktuell ungenutzt.
|
||||
- **`get.edgeguard.netcell-it.de`** anlegen oder Übergangs-URL auf `apt.netcell-it.de/edgeguard/install.sh` nutzen.
|
||||
|
||||
@@ -150,6 +150,7 @@ type AutoFWRule struct {
|
||||
Proto string
|
||||
Port int
|
||||
DstIP string
|
||||
L3 string // "ip"/"ip6" — gesetzt für DstIP-Rules (Familie); leer = agnostisch
|
||||
Iface string // optional: scope auf ein iifname (z.B. DHCP udp/67 nur auf LAN)
|
||||
Comment string
|
||||
}
|
||||
@@ -457,7 +458,21 @@ func (g *Generator) loadAutoRules(ctx context.Context) []AutoFWRule {
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
// Familien-Tag (ip/ip6) für DstIP-basierte Auto-Rules setzen; eine
|
||||
// IPv6-Listen-Adresse muss `ip6 daddr` ergeben (sonst lehnt nft das
|
||||
// gesamte Ruleset ab). Unparsebare DstIPs werden verworfen.
|
||||
tagged := out[:0]
|
||||
for _, r := range out {
|
||||
if r.DstIP != "" {
|
||||
fam := addrFamily(r.DstIP)
|
||||
if fam == "" {
|
||||
continue
|
||||
}
|
||||
r.L3 = fam
|
||||
}
|
||||
tagged = append(tagged, r)
|
||||
}
|
||||
return tagged
|
||||
}
|
||||
|
||||
// splitCSV — wie in den Service-renderern.
|
||||
|
||||
@@ -15,7 +15,8 @@ func TestTemplate_autoRuleIface(t *testing.T) {
|
||||
view := &View{
|
||||
AutoRules: []AutoFWRule{
|
||||
{Proto: "udp", Port: 67, Iface: "eth1", Comment: "DHCP (Kea) auf eth1"},
|
||||
{Proto: "udp", Port: 53, DstIP: "10.0.0.1", Comment: "DNS"},
|
||||
{Proto: "udp", Port: 53, DstIP: "10.0.0.1", L3: "ip", Comment: "DNS"},
|
||||
{Proto: "udp", Port: 53, DstIP: "2001:db8::1", L3: "ip6", Comment: "DNS v6"},
|
||||
},
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
@@ -27,9 +28,13 @@ func TestTemplate_autoRuleIface(t *testing.T) {
|
||||
if !strings.Contains(out, `iifname "eth1" udp dport 67 accept comment "auto: DHCP (Kea) auf eth1"`) {
|
||||
t.Errorf("missing iface-scoped DHCP auto-rule\n----\n%s", out)
|
||||
}
|
||||
// Regression: DstIP-Auto-Rule ohne Iface bleibt unverändert.
|
||||
// v4-DstIP-Auto-Rule: ip daddr.
|
||||
if !strings.Contains(out, `ip daddr 10.0.0.1 udp dport 53 accept`) {
|
||||
t.Errorf("DstIP auto-rule changed\n----\n%s", out)
|
||||
t.Errorf("v4 DstIP auto-rule wrong\n----\n%s", out)
|
||||
}
|
||||
// Fix #5: v6-DstIP muss `ip6 daddr` ergeben (sonst bricht nft das Ruleset).
|
||||
if !strings.Contains(out, `ip6 daddr 2001:db8::1 udp dport 53 accept`) {
|
||||
t.Errorf("v6 DstIP auto-rule must use ip6 daddr\n----\n%s", out)
|
||||
}
|
||||
|
||||
// Echte nft-Syntaxvalidierung (braucht root → via sudo, sonst skip).
|
||||
|
||||
@@ -61,7 +61,7 @@ table inet edgeguard {
|
||||
# editiert diese nicht. Wenn der Service entfernt/disabled
|
||||
# wird, ist die Rule beim nächsten Render weg.
|
||||
{{range .AutoRules}}
|
||||
{{if .Iface}}iifname "{{.Iface}}" {{end}}{{if .DstIP}}ip daddr {{.DstIP}} {{end}}{{.Proto}} dport {{.Port}} accept comment "auto: {{.Comment}}"
|
||||
{{if .Iface}}iifname "{{.Iface}}" {{end}}{{if .DstIP}}{{.L3}} daddr {{.DstIP}} {{end}}{{.Proto}} dport {{.Port}} accept comment "auto: {{.Comment}}"
|
||||
{{end}}
|
||||
|
||||
# ── Operator-defined rules ──
|
||||
|
||||
@@ -43,8 +43,12 @@ func New(pool *pgxpool.Pool, box *secrets.Box) *Generator {
|
||||
|
||||
func (g *Generator) Name() string { return "freeradius" }
|
||||
|
||||
// confEscape escaped FreeRADIUS-double-quoted-Strings (Backslash + Quote).
|
||||
// confEscape escaped FreeRADIUS-double-quoted-Strings (Backslash + Quote)
|
||||
// und strippt Steuerzeichen (CR/LF) als Defense-in-Depth gegen Zeilen-
|
||||
// Injection — die Werte werden zwar schon im Handler validiert.
|
||||
func confEscape(s string) string {
|
||||
s = strings.ReplaceAll(s, "\r", "")
|
||||
s = strings.ReplaceAll(s, "\n", "")
|
||||
s = strings.ReplaceAll(s, `\`, `\\`)
|
||||
s = strings.ReplaceAll(s, `"`, `\"`)
|
||||
return s
|
||||
|
||||
@@ -110,6 +110,7 @@ func (h *AuthHandler) Login(c *gin.Context) {
|
||||
actor, role := "", "admin"
|
||||
remote := c.ClientIP()
|
||||
var totpEnabled bool
|
||||
var viaDB bool // true wenn Rolle/TOTP bereits aus der DB-Row stammen
|
||||
|
||||
// 1. Try DB users table first.
|
||||
if h.Users != nil {
|
||||
@@ -134,6 +135,7 @@ func (h *AuthHandler) Login(c *gin.Context) {
|
||||
actor = ai.Email
|
||||
role = ai.Role
|
||||
totpEnabled = ai.TOTPEnabled
|
||||
viaDB = true
|
||||
h.Users.RecordLogin(c.Request.Context(), ai.ID)
|
||||
}
|
||||
}
|
||||
@@ -168,6 +170,18 @@ func (h *AuthHandler) Login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bei Fallback (Setup-Store) / Federation (Primary) stammen role/TOTP
|
||||
// NICHT aus der DB. Rolle + TOTP-Status autoritativ aus der lokalen
|
||||
// (replizierten) users-Row ableiten — damit 2FA greift und die Rolle
|
||||
// nie aus einer Remote-Payload kommt. Ist der User lokal (noch) nicht
|
||||
// vorhanden (Replikations-Lag/DB aus), bleibt es beim Fallback-Wert.
|
||||
if actor != "" && !viaDB && h.Users != nil {
|
||||
if ai, err := h.Users.FindForAuth(c.Request.Context(), actor); err == nil {
|
||||
role = ai.Role
|
||||
totpEnabled = ai.TOTPEnabled
|
||||
}
|
||||
}
|
||||
|
||||
// TOTP gate: password OK but 2FA required → issue a short-lived pending
|
||||
// cookie and tell the UI to show the TOTP input.
|
||||
if totpEnabled {
|
||||
|
||||
@@ -866,6 +866,7 @@ type registerPeerRequest struct {
|
||||
MgmtIP string `json:"mgmt_ip"` // optional
|
||||
Version string `json:"version"`
|
||||
ConfigHash *string `json:"config_hash"` // nil=absent (don't change), ""=no user config
|
||||
Role string `json:"role"` // "" → "peer" (joining peer); "primary" beim Push des Primary
|
||||
}
|
||||
|
||||
// AgentRegisterPeer: vom Joiner nach issue-cert via mTLS aufgerufen.
|
||||
@@ -904,12 +905,21 @@ func (h *ClusterHandler) AgentRegisterPeer(c *gin.Context) {
|
||||
// Node, hier ist der „Self" der joining-Peer auf dieser Primary-Seite.
|
||||
// Der Name passt nicht 100% semantisch, aber das SQL ist exakt das was
|
||||
// wir brauchen.)
|
||||
// Rolle aus dem Request (default "peer"). Ein joining-Peer sendet keine
|
||||
// Rolle → "peer". Der Primary-Push sendet "primary", damit die vom
|
||||
// Secondary ausgelieferte UI den Primary korrekt als primary zeigt.
|
||||
// Cert-CN authentifiziert die FQDN; role ist node-lokal/Anzeige (echte
|
||||
// Rollenerkennung läuft über pg_publication).
|
||||
role := strings.TrimSpace(req.Role)
|
||||
if role == "" {
|
||||
role = "peer"
|
||||
}
|
||||
n := models.HANode{
|
||||
ID: req.ID,
|
||||
Name: req.Name,
|
||||
FQDN: req.FQDN,
|
||||
APIURL: req.APIURL,
|
||||
Role: "peer",
|
||||
Role: role,
|
||||
Status: "online", // peer IS online — it just connected via mTLS
|
||||
}
|
||||
if req.PublicIP != "" {
|
||||
@@ -965,7 +975,14 @@ func (h *ClusterHandler) AgentRegisterPeer(c *gin.Context) {
|
||||
}()
|
||||
}
|
||||
|
||||
slog.Info("cluster: peer registered via mTLS",
|
||||
// Bei neuem Peer / IP-Wechsel als Info loggen (relevantes Ereignis),
|
||||
// sonst Debug — die periodischen 30s-Pushes (runPrimaryPush/runPeerPush)
|
||||
// würden sonst das Log fluten.
|
||||
logFn := slog.Debug
|
||||
if ipChanged {
|
||||
logFn = slog.Info
|
||||
}
|
||||
logFn("cluster: peer registered via mTLS",
|
||||
"id", out.ID, "fqdn", out.FQDN, "role", out.Role, "status", out.Status,
|
||||
"client_cn", cn, "remote", c.ClientIP())
|
||||
response.OK(c, out)
|
||||
|
||||
@@ -81,7 +81,14 @@ func (h *ClusterHandler) RepairReplication(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if h.nodeHasPublication(ctx) {
|
||||
isPrimary, err := h.nodeHasPublication(ctx)
|
||||
if err != nil {
|
||||
// Primary/Subscriber-Status nicht ermittelbar → NICHT raten
|
||||
// (sonst Resync auf dem falschen Node). Abbrechen.
|
||||
response.Internal(c, fmt.Errorf("primary-status nicht ermittelbar: %w", err))
|
||||
return
|
||||
}
|
||||
if isPrimary {
|
||||
// Primary → an den Subscriber-Peer delegieren, mit eigener Adresse.
|
||||
if h.Aggregator == nil {
|
||||
response.BadRequest(c, errors.New("kein mTLS-Aggregator verfügbar — Resync nicht delegierbar"))
|
||||
@@ -162,7 +169,12 @@ func (h *ClusterHandler) startResync(ctx context.Context, primaryHost string) er
|
||||
}
|
||||
// Niemals auf dem Primary (Publication-Quelle) resyncen — würde die
|
||||
// eigene Config mit sich selbst überschreiben bzw. ist sinnlos.
|
||||
if h.nodeHasPublication(ctx) {
|
||||
// Bei Statusfehler fail-closed (NICHT resyncen).
|
||||
isPrimary, err := h.nodeHasPublication(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("publication-status nicht ermittelbar: %w", err)
|
||||
}
|
||||
if isPrimary {
|
||||
return errors.New("dieser Node ist der Publication-Primary — Resync läuft nur auf einem Subscriber")
|
||||
}
|
||||
if st := repairUnitState(); st == "activating" || st == "active" {
|
||||
@@ -201,9 +213,9 @@ rm -f %[2]s
|
||||
// nodeHasPublication prüft, ob dieser Node die Replikations-Publication
|
||||
// besitzt — das verlässliche Primary-Signal. pg_publication ist für jeden
|
||||
// DB-User lesbar (anders als pg_subscription).
|
||||
func (h *ClusterHandler) nodeHasPublication(ctx context.Context) bool {
|
||||
func (h *ClusterHandler) nodeHasPublication(ctx context.Context) (bool, error) {
|
||||
if h.Store == nil || h.Store.Pool == nil {
|
||||
return false
|
||||
return false, errors.New("no db pool")
|
||||
}
|
||||
cctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
@@ -211,9 +223,9 @@ func (h *ClusterHandler) nodeHasPublication(ctx context.Context) bool {
|
||||
if err := h.Store.Pool.QueryRow(cctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM pg_publication WHERE pubname = $1)`, repairPubName,
|
||||
).Scan(&exists); err != nil {
|
||||
return false
|
||||
return false, err
|
||||
}
|
||||
return exists
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// repairStatusResponse spiegelt den Zustand der transienten Repair-Unit.
|
||||
@@ -231,7 +243,9 @@ type repairStatusResponse struct {
|
||||
// Status vom Subscriber-Peer geholt (dort läuft der Job); sonst lokal.
|
||||
func (h *ClusterHandler) RepairReplicationStatus(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if h.Store != nil && h.nodeHasPublication(ctx) && h.Aggregator != nil {
|
||||
// Status-Poll: bei Fehler kein 500 — einfach lokalen Status liefern.
|
||||
isPrimary, _ := h.nodeHasPublication(ctx)
|
||||
if h.Store != nil && isPrimary && h.Aggregator != nil {
|
||||
if all, err := h.Store.List(ctx); err == nil {
|
||||
if peer := findOtherPeer(all, h.LocalID); peer != nil {
|
||||
results := h.Aggregator.FanOut(ctx,
|
||||
|
||||
@@ -7,14 +7,21 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/configgen"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/handlers/response"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/models"
|
||||
aptsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/apt"
|
||||
)
|
||||
|
||||
// ruStateMu serialisiert Lesen/Schreiben der Rolling-Update-State-Datei
|
||||
// (HTTP-Handler + Hintergrund-Goroutine greifen gleichzeitig zu).
|
||||
var ruStateMu sync.Mutex
|
||||
|
||||
const rollingUpdateStateFile = "/var/lib/edgeguard/rolling-update-state.json"
|
||||
|
||||
const (
|
||||
@@ -26,17 +33,24 @@ const (
|
||||
phaseFailed = "failed"
|
||||
)
|
||||
|
||||
// FinishRollingUpdateIfPending wird beim API-Start aufgerufen. Wenn die
|
||||
// State-Datei "updating-primary" enthält, bedeutet das dass der Primary
|
||||
// gerade erfolgreich neugestartet ist → Update abgeschlossen → "done" schreiben.
|
||||
// FinishRollingUpdateIfPending wird beim API-Start aufgerufen.
|
||||
// - "updating-primary": der Primary ist gerade erfolgreich neugestartet →
|
||||
// Update abgeschlossen → "done".
|
||||
// - "updating-secondary"/"waiting-secondary": die orchestrierende Goroutine
|
||||
// lief in DIESEM (jetzt neu gestarteten) Prozess und ist mit ihm gestorben.
|
||||
// Die Phase kann nicht weiterlaufen → auf "idle" zurücksetzen, sonst zeigt
|
||||
// die UI ewig "Rolling Update läuft". (Vorher blieb so ein Stand hängen.)
|
||||
func FinishRollingUpdateIfPending() {
|
||||
st := readRollingUpdateState()
|
||||
if st.Phase == phaseUpdatingPrimary {
|
||||
switch st.Phase {
|
||||
case phaseUpdatingPrimary:
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseDone,
|
||||
SecondaryID: st.SecondaryID,
|
||||
SecondaryFQDN: st.SecondaryFQDN,
|
||||
})
|
||||
case phaseUpdatingSecondary, phaseWaitingSecondary:
|
||||
writeRollingUpdateState(RollingUpdateState{Phase: phaseIdle})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +67,8 @@ type RollingUpdateState struct {
|
||||
}
|
||||
|
||||
func readRollingUpdateState() RollingUpdateState {
|
||||
ruStateMu.Lock()
|
||||
defer ruStateMu.Unlock()
|
||||
data, err := os.ReadFile(rollingUpdateStateFile)
|
||||
if err != nil {
|
||||
return RollingUpdateState{Phase: phaseIdle, UpdatedAt: time.Now()}
|
||||
@@ -61,6 +77,13 @@ func readRollingUpdateState() RollingUpdateState {
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return RollingUpdateState{Phase: phaseIdle, UpdatedAt: time.Now()}
|
||||
}
|
||||
// Terminale Zustände altern aus (statt Mutation-on-GET): nach 10 min
|
||||
// gilt done/failed als idle — so verliert kein paralleler Poller das
|
||||
// Ergebnis und ein alter Stand bleibt nicht hängen.
|
||||
if (s.Phase == phaseDone || s.Phase == phaseFailed) && !s.UpdatedAt.IsZero() &&
|
||||
time.Since(s.UpdatedAt) > 10*time.Minute {
|
||||
return RollingUpdateState{Phase: phaseIdle, UpdatedAt: time.Now()}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -71,7 +94,10 @@ func writeRollingUpdateState(s RollingUpdateState) {
|
||||
slog.Warn("rolling-update: failed to marshal state", "error", err)
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(rollingUpdateStateFile, data, 0o600); err != nil {
|
||||
ruStateMu.Lock()
|
||||
defer ruStateMu.Unlock()
|
||||
// AtomicWrite (temp+rename) → Leser sehen nie einen partiellen Stand.
|
||||
if err := configgen.AtomicWrite(rollingUpdateStateFile, data, 0o600); err != nil {
|
||||
slog.Warn("rolling-update: failed to write state file", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -127,76 +153,108 @@ func (h *ClusterHandler) RollingUpdate(c *gin.Context) {
|
||||
}
|
||||
|
||||
// RollingUpdateStatus gibt den aktuellen Rolling-Update-State zurück.
|
||||
// Bei phase == "done" wird nach Auslieferung sofort auf idle zurückgesetzt
|
||||
// damit der nächste Pageload keinen Stale-done vorfindet.
|
||||
// Read-only — terminale Zustände altern in readRollingUpdateState aus
|
||||
// (kein Reset-on-GET mehr, das parallelen Pollern das "done" wegnahm).
|
||||
func (h *ClusterHandler) RollingUpdateStatus(c *gin.Context) {
|
||||
st := readRollingUpdateState()
|
||||
response.OK(c, st)
|
||||
if st.Phase == phaseDone {
|
||||
writeRollingUpdateState(RollingUpdateState{Phase: phaseIdle})
|
||||
}
|
||||
response.OK(c, readRollingUpdateState())
|
||||
}
|
||||
|
||||
func (h *ClusterHandler) runRollingUpdate(secondary *models.HANode) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 1. Secondary triggern
|
||||
slog.Info("rolling-update: posting trigger-update to secondary", "fqdn", secondary.FQDN)
|
||||
result := h.Aggregator.PostPeer(ctx, *secondary, "/agent/cluster/trigger-update")
|
||||
if !result.OK {
|
||||
// Zielversion = das verfügbare apt-Candidate (worauf wir hochziehen) und
|
||||
// die aktuelle Secondary-Version als Baseline. Beides steuert, ob der
|
||||
// Secondary überhaupt etwas zu tun hat.
|
||||
candidate := rollingCandidateVersion(ctx)
|
||||
baseline := secondaryVersion(ctx, h, secondary)
|
||||
|
||||
// Ist der Secondary bereits auf der Zielversion, gibt es nichts
|
||||
// hochzuziehen — KEIN Trigger, KEIN Warten. Sonst würde auf einen
|
||||
// Version-Flip gewartet, der nie kommt → 10-min-Timeout (der frühere Bug,
|
||||
// wenn beide Nodes schon aktuell waren).
|
||||
secondaryUpToDate := candidate != "" && baseline != "" && baseline == candidate
|
||||
if secondaryUpToDate {
|
||||
slog.Info("rolling-update: secondary already at target — skipping secondary step",
|
||||
"version", candidate)
|
||||
} else {
|
||||
// 1. Secondary triggern
|
||||
slog.Info("rolling-update: posting trigger-update to secondary", "fqdn", secondary.FQDN)
|
||||
result := h.Aggregator.PostPeer(ctx, *secondary, "/agent/cluster/trigger-update")
|
||||
if !result.OK {
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseFailed,
|
||||
SecondaryID: secondary.ID,
|
||||
SecondaryFQDN: secondary.FQDN,
|
||||
Error: "trigger-update failed: " + result.Err,
|
||||
})
|
||||
slog.Warn("rolling-update: secondary trigger failed", "error", result.Err)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Secondary-Version pollen — der Secondary restartet nach dem
|
||||
// Upgrade, danach zeigt /agent/cluster/version eine neue Version.
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseFailed,
|
||||
Phase: phaseWaitingSecondary,
|
||||
SecondaryID: secondary.ID,
|
||||
SecondaryFQDN: secondary.FQDN,
|
||||
Error: "trigger-update failed: " + result.Err,
|
||||
})
|
||||
slog.Warn("rolling-update: secondary trigger failed", "error", result.Err)
|
||||
return
|
||||
}
|
||||
slog.Info("rolling-update: waiting for secondary version flip",
|
||||
"baseline", baseline, "candidate", candidate)
|
||||
|
||||
// 2. Secondary-Version pollen — der Secondary restartet nach dem
|
||||
// Upgrade, danach zeigt /agent/cluster/version eine neue Version.
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseWaitingSecondary,
|
||||
SecondaryID: secondary.ID,
|
||||
SecondaryFQDN: secondary.FQDN,
|
||||
})
|
||||
slog.Info("rolling-update: waiting for secondary version flip")
|
||||
// Kurze Wartezeit damit apt auf dem Secondary erst losläuft
|
||||
time.Sleep(20 * time.Second)
|
||||
|
||||
// Kurze Wartezeit damit apt auf dem Secondary erst losläuft
|
||||
time.Sleep(20 * time.Second)
|
||||
|
||||
deadline := time.Now().Add(10 * time.Minute)
|
||||
versionFlipped := false
|
||||
for time.Now().Before(deadline) {
|
||||
results := h.Aggregator.FanOut(ctx, []models.HANode{*secondary}, "/agent/cluster/version", h.LocalID)
|
||||
if len(results) > 0 && results[0].OK {
|
||||
var ver struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err := json.Unmarshal(results[0].Data, &ver); err == nil {
|
||||
slog.Info("rolling-update: secondary version", "version", ver.Version, "primary", h.Version)
|
||||
if ver.Version != h.Version {
|
||||
versionFlipped = true
|
||||
break
|
||||
deadline := time.Now().Add(10 * time.Minute)
|
||||
versionFlipped := false
|
||||
for time.Now().Before(deadline) {
|
||||
results := h.Aggregator.FanOut(ctx, []models.HANode{*secondary}, "/agent/cluster/version", h.LocalID)
|
||||
if len(results) > 0 && results[0].OK {
|
||||
var ver struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err := json.Unmarshal(results[0].Data, &ver); err == nil {
|
||||
slog.Info("rolling-update: secondary version", "version", ver.Version,
|
||||
"baseline", baseline, "candidate", candidate)
|
||||
// Erfolg = Secondary hat die Zielversion erreicht (candidate)
|
||||
// ODER hat sich gegenüber der Baseline überhaupt bewegt
|
||||
// (Fallback, wenn candidate nicht ermittelbar war).
|
||||
if ver.Version != "" &&
|
||||
((candidate != "" && ver.Version == candidate) || ver.Version != baseline) {
|
||||
versionFlipped = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
|
||||
if !versionFlipped {
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseFailed,
|
||||
SecondaryID: secondary.ID,
|
||||
SecondaryFQDN: secondary.FQDN,
|
||||
Error: "timeout (10 min) waiting for secondary version flip",
|
||||
})
|
||||
slog.Warn("rolling-update: secondary version flip timeout")
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
|
||||
if !versionFlipped {
|
||||
// 3. Primary (uns selbst) aktualisieren — identisch zu /system/upgrade.
|
||||
// Ist der Primary bereits auf der Zielversion (z. B. beide Nodes schon
|
||||
// aktuell), gibt es nichts zu tun → direkt "done". Sonst liefe ein
|
||||
// apt-Lauf ohne Paket-Wechsel → kein Restart → Phase hinge ewig in
|
||||
// "updating-primary".
|
||||
if candidate != "" && h.Version == candidate {
|
||||
slog.Info("rolling-update: primary already at target — nothing to upgrade", "version", candidate)
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseFailed,
|
||||
Phase: phaseDone,
|
||||
SecondaryID: secondary.ID,
|
||||
SecondaryFQDN: secondary.FQDN,
|
||||
Error: "timeout (10 min) waiting for secondary version flip",
|
||||
})
|
||||
slog.Warn("rolling-update: secondary version flip timeout")
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Primary (uns selbst) aktualisieren — identisch zu /system/upgrade
|
||||
writeRollingUpdateState(RollingUpdateState{
|
||||
Phase: phaseUpdatingPrimary,
|
||||
SecondaryID: secondary.ID,
|
||||
@@ -256,3 +314,26 @@ rm -f /var/lib/edgeguard/upgrade.sh
|
||||
// UI erkennt Version-Flip via /system/health und schließt den Flow.
|
||||
slog.Info("rolling-update: primary upgrade dispatched, process will restart")
|
||||
}
|
||||
|
||||
// rollingCandidateVersion liefert best-effort die verfügbare apt-Candidate-
|
||||
// Version des Meta-Pakets "edgeguard" — also die Version, auf die das Rolling-
|
||||
// Update hochzieht. Leerer String, wenn apt sie nicht ermitteln kann (dann
|
||||
// fällt runRollingUpdate auf reine Baseline-Flip-Erkennung zurück).
|
||||
func rollingCandidateVersion(ctx context.Context) string {
|
||||
vers := aptsvc.PackageVersions(ctx, false)
|
||||
return vers["edgeguard_available"]
|
||||
}
|
||||
|
||||
// secondaryVersion holt best-effort die laufende Version des Peers via mTLS.
|
||||
func secondaryVersion(ctx context.Context, h *ClusterHandler, secondary *models.HANode) string {
|
||||
results := h.Aggregator.FanOut(ctx, []models.HANode{*secondary}, "/agent/cluster/version", h.LocalID)
|
||||
if len(results) > 0 && results[0].OK {
|
||||
var ver struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if json.Unmarshal(results[0].Data, &ver) == nil {
|
||||
return ver.Version
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -148,11 +148,16 @@ func (b *clientBody) validate(creating bool) error {
|
||||
return errors.New("ipaddr ist keine gültige IP/CIDR: " + b.IPAddr)
|
||||
}
|
||||
}
|
||||
if creating && (b.Secret == nil || len(*b.Secret) < 6) {
|
||||
return errors.New("secret ist erforderlich (mind. 6 Zeichen)")
|
||||
if creating && b.Secret == nil {
|
||||
return errors.New("secret ist erforderlich")
|
||||
}
|
||||
if b.Secret != nil && *b.Secret != "" && len(*b.Secret) < 6 {
|
||||
return errors.New("secret muss mind. 6 Zeichen haben")
|
||||
if b.Secret != nil {
|
||||
if len(*b.Secret) < 6 {
|
||||
return errors.New("secret muss mind. 6 Zeichen haben (leer löscht es nicht)")
|
||||
}
|
||||
if strings.ContainsAny(*b.Secret, "\r\n") {
|
||||
return errors.New("secret darf keine Zeilenumbrüche enthalten")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -266,6 +271,14 @@ func (b *userBody) validate(creating bool) error {
|
||||
if creating && (b.Password == nil || *b.Password == "") {
|
||||
return errors.New("password ist erforderlich")
|
||||
}
|
||||
if b.Password != nil {
|
||||
if *b.Password == "" {
|
||||
return errors.New("password darf nicht leer sein (löscht es nicht)")
|
||||
}
|
||||
if strings.ContainsAny(*b.Password, "\r\n") {
|
||||
return errors.New("password darf keine Zeilenumbrüche enthalten")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -194,6 +194,8 @@ var servicesToCheck = []struct{ Label, Unit string }{
|
||||
{"unbound", "unbound"},
|
||||
{"chrony", "chrony"},
|
||||
{"squid", "squid"},
|
||||
{"kea-dhcp4", "kea-dhcp4-server"},
|
||||
{"freeradius", "freeradius"},
|
||||
{"postgresql", "postgresql"},
|
||||
{"crowdsec", "crowdsec"},
|
||||
{"crowdsec-firewall-bouncer", "crowdsec-firewall-bouncer"},
|
||||
|
||||
@@ -4,8 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -15,6 +18,10 @@ import (
|
||||
wafsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/waf"
|
||||
)
|
||||
|
||||
// wafRuleIDRe erlaubt nur einzelne CRS-Rule-IDs oder Ranges ("942100" /
|
||||
// "942100-942999") als Exclusion — verhindert SecLang-Direktiven-Injection.
|
||||
var wafRuleIDRe = regexp.MustCompile(`^[0-9]{1,9}(-[0-9]{1,9})?$`)
|
||||
|
||||
// WafHandler exposes the per-domain WAF configuration REST API:
|
||||
//
|
||||
// GET /waf/configs — list all configs (one per domain)
|
||||
@@ -110,6 +117,27 @@ func (h *WafHandler) Upsert(c *gin.Context) {
|
||||
if body.ExclusionNotes == nil {
|
||||
body.ExclusionNotes = map[string]string{}
|
||||
}
|
||||
// Exclusions müssen reine Rule-IDs/Ranges sein (sonst Direktiven-Injection
|
||||
// in die SecLang-Config via Newline).
|
||||
for _, ex := range body.RuleExclusions {
|
||||
if !wafRuleIDRe.MatchString(strings.TrimSpace(ex)) {
|
||||
response.BadRequest(c, errors.New("ungültige Rule-Exclusion (nur IDs/Ranges erlaubt): "+ex))
|
||||
return
|
||||
}
|
||||
}
|
||||
// Trusted-Proxies müssen gültige IPs/CIDRs sein.
|
||||
for _, p := range body.TrustedProxies {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
if net.ParseIP(p) == nil {
|
||||
if _, _, err := net.ParseCIDR(p); err != nil {
|
||||
response.BadRequest(c, errors.New("ungültiger Trusted-Proxy (IP/CIDR): "+p))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg := models.WafConfig{
|
||||
DomainID: domainID,
|
||||
Enabled: body.Enabled,
|
||||
|
||||
@@ -32,6 +32,10 @@ type WireguardHandler struct {
|
||||
Audit *audit.Repo
|
||||
NodeID string
|
||||
Reloader func(ctx context.Context) error
|
||||
// PublicHost ist der öffentliche Host (FQDN/IP), den Clients als
|
||||
// WireGuard-Endpoint anwählen. Wird in heruntergeladene Peer-Configs
|
||||
// geschrieben (statt eines Platzhalters). Leer → Platzhalter (Fallback).
|
||||
PublicHost string
|
||||
}
|
||||
|
||||
func NewWireguardHandler(
|
||||
@@ -45,6 +49,12 @@ func NewWireguardHandler(
|
||||
return &WireguardHandler{Ifaces: ifaces, Peers: peers, Box: box, Audit: a, NodeID: nodeID, Reloader: reloader}
|
||||
}
|
||||
|
||||
// WithPublicHost setzt den öffentlichen Endpoint-Host für Peer-Configs.
|
||||
func (h *WireguardHandler) WithPublicHost(host string) *WireguardHandler {
|
||||
h.PublicHost = strings.TrimSpace(host)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *WireguardHandler) reload(ctx context.Context, op string) {
|
||||
if h.Reloader == nil {
|
||||
return
|
||||
@@ -702,11 +712,15 @@ func (h *WireguardHandler) peerConfigText(ctx context.Context, peerID int64) (st
|
||||
clientAllowedIPs += ", " + strings.TrimSpace(*ifc.ClientRoutes)
|
||||
}
|
||||
fmt.Fprintf(&b, "AllowedIPs = %s\n", clientAllowedIPs)
|
||||
// Endpoint — the operator's public host:port that peers dial.
|
||||
// We don't know this here (could be a CNAME or behind a load
|
||||
// balancer); leave a placeholder the operator must fill in.
|
||||
// Endpoint — der öffentliche Host:Port, den Clients anwählen. Standard
|
||||
// ist der FQDN dieser Node (PublicHost, aus setup.json). Nur wenn der
|
||||
// nicht ermittelbar ist, bleibt ein Platzhalter den der Operator füllt.
|
||||
if ifc.ListenPort != nil {
|
||||
fmt.Fprintf(&b, "Endpoint = REPLACE_WITH_PUBLIC_HOST:%d\n", *ifc.ListenPort)
|
||||
host := h.PublicHost
|
||||
if host == "" {
|
||||
host = "REPLACE_WITH_PUBLIC_HOST"
|
||||
}
|
||||
fmt.Fprintf(&b, "Endpoint = %s:%d\n", host, *ifc.ListenPort)
|
||||
}
|
||||
if p.Keepalive != nil && *p.Keepalive > 0 {
|
||||
fmt.Fprintf(&b, "PersistentKeepalive = %d\n", *p.Keepalive)
|
||||
|
||||
@@ -119,7 +119,7 @@ func (g *Generator) buildConfig(ctx context.Context) (*keaConfig, *bool, error)
|
||||
}
|
||||
|
||||
ifaceSet := map[string]bool{}
|
||||
var ifaces []string
|
||||
ifaces := []string{} // nie nil → JSON "[]" statt "null" (Kea lehnt null ab)
|
||||
var sn4 []subnet4
|
||||
|
||||
for _, s := range subnets {
|
||||
|
||||
@@ -128,7 +128,7 @@ func Join(req Request) error {
|
||||
// synchronous on the primary side.
|
||||
var autoRegErr error
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := autoRegister(primary, tlsDir, req.CommonName, req.Version, req.NodeID, ""); err == nil {
|
||||
if err := autoRegister(primary, tlsDir, req.CommonName, req.Version, req.NodeID, "", "peer"); err == nil {
|
||||
autoRegErr = nil
|
||||
break
|
||||
} else {
|
||||
@@ -222,13 +222,21 @@ func issueCert(primary, token, csr string, insecure bool) (caCert, peerCert stri
|
||||
// goroutine so the primary's ha_nodes always reflects the secondary's actual
|
||||
// config_hash (not the stale join-time value).
|
||||
func PushSelfToPrimary(primaryURL, tlsDir, nodeID, fqdn, version, configHash string) error {
|
||||
return PushSelfToPeer(primaryURL, tlsDir, nodeID, fqdn, version, configHash, "peer")
|
||||
}
|
||||
|
||||
// PushSelfToPeer sendet die eigene Identität an einen beliebigen Peer (mTLS,
|
||||
// /agent/cluster/peers). role bestimmt, mit welcher Rolle sich dieser Node
|
||||
// beim Empfänger einträgt: ein Secondary pusht "peer" an den Primary, der
|
||||
// Primary pusht "primary" an jeden Secondary (bidirektionaler Heartbeat).
|
||||
func PushSelfToPeer(peerURL, tlsDir, nodeID, fqdn, version, configHash, role string) error {
|
||||
if tlsDir == "" {
|
||||
tlsDir = clustertls.DefaultDir
|
||||
}
|
||||
return autoRegister(primaryURL, tlsDir, fqdn, version, nodeID, configHash)
|
||||
return autoRegister(peerURL, tlsDir, fqdn, version, nodeID, configHash, role)
|
||||
}
|
||||
|
||||
func autoRegister(primary, tlsDir, commonName, version, nodeID, configHash string) error {
|
||||
func autoRegister(primary, tlsDir, commonName, version, nodeID, configHash, role string) error {
|
||||
u, err := url.Parse(primary)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -241,6 +249,9 @@ func autoRegister(primary, tlsDir, commonName, version, nodeID, configHash strin
|
||||
nodeID = strings.TrimSpace(string(raw))
|
||||
}
|
||||
hostname, _ := os.Hostname()
|
||||
if role == "" {
|
||||
role = "peer"
|
||||
}
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"id": nodeID,
|
||||
"name": hostname,
|
||||
@@ -248,6 +259,7 @@ func autoRegister(primary, tlsDir, commonName, version, nodeID, configHash strin
|
||||
"api_url": "https://" + commonName + ":3443",
|
||||
"version": version,
|
||||
"config_hash": configHash,
|
||||
"role": role,
|
||||
})
|
||||
|
||||
pair, err := tls.LoadX509KeyPair(tlsDir+"/peer.crt", tlsDir+"/peer.key")
|
||||
|
||||
@@ -44,6 +44,7 @@ func Run(ctx context.Context, gens []configgen.Generator, only []string) ([]Resu
|
||||
whitelist[n] = true
|
||||
}
|
||||
out := make([]Result, 0, len(gens))
|
||||
var errs []error
|
||||
for _, g := range gens {
|
||||
if len(whitelist) > 0 && !whitelist[g.Name()] {
|
||||
out = append(out, Result{Name: g.Name(), Skipped: true})
|
||||
@@ -52,11 +53,14 @@ func Run(ctx context.Context, gens []configgen.Generator, only []string) ([]Resu
|
||||
err := g.Render(ctx)
|
||||
out = append(out, Result{Name: g.Name(), Err: err})
|
||||
if err != nil && !errors.Is(err, configgen.ErrNotImplemented) {
|
||||
// hard failure — surface it but return what's done so far
|
||||
return out, fmt.Errorf("%s: %w", g.Name(), err)
|
||||
// Weitermachen: die Generatoren sind unabhängig und reloaden
|
||||
// inline (nft/Service-Reload sind atomar). Abbrechen würde die
|
||||
// restlichen Dienste auf altem Stand lassen → halb angewandt.
|
||||
// Stattdessen alle versuchen und Fehler gesammelt zurückgeben.
|
||||
errs = append(errs, fmt.Errorf("%s: %w", g.Name(), err))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
return out, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// Summarise turns the result slice into a human-readable multiline
|
||||
|
||||
@@ -96,14 +96,15 @@ func loadOrCreateSecret(path string) ([]byte, error) {
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
// IssueWithRole returns a signed token for the given actor + role.
|
||||
func (s *Signer) IssueWithRole(actor, role string) (string, *Token, error) {
|
||||
// issue builds + signs a token with an explicit TTL. No shared-state
|
||||
// mutation — safe for concurrent use of the shared Signer singleton.
|
||||
func (s *Signer) issue(actor, role string, ttl time.Duration) (string, *Token, error) {
|
||||
now := s.Now()
|
||||
t := Token{
|
||||
Actor: actor,
|
||||
Role: role,
|
||||
Iat: now.Unix(),
|
||||
Exp: now.Add(s.TTL).Unix(),
|
||||
Exp: now.Add(ttl).Unix(),
|
||||
}
|
||||
data, err := json.Marshal(t)
|
||||
if err != nil {
|
||||
@@ -117,18 +118,20 @@ func (s *Signer) IssueWithRole(actor, role string) (string, *Token, error) {
|
||||
return encoded, &t, nil
|
||||
}
|
||||
|
||||
// Issue is IssueWithRole with empty role.
|
||||
func (s *Signer) Issue(actor string) (string, *Token, error) {
|
||||
return s.IssueWithRole(actor, "")
|
||||
// IssueWithRole returns a signed token for the given actor + role.
|
||||
func (s *Signer) IssueWithRole(actor, role string) (string, *Token, error) {
|
||||
return s.issue(actor, role, s.TTL)
|
||||
}
|
||||
|
||||
// IssueWithRoleTTL issues a token with a custom TTL (overrides s.TTL for this call).
|
||||
// Issue is IssueWithRole with empty role.
|
||||
func (s *Signer) Issue(actor string) (string, *Token, error) {
|
||||
return s.issue(actor, "", s.TTL)
|
||||
}
|
||||
|
||||
// IssueWithRoleTTL issues a token with a custom TTL — no longer mutates
|
||||
// the shared Signer (previously a data race under concurrent logins).
|
||||
func (s *Signer) IssueWithRoleTTL(actor, role string, ttl time.Duration) (string, *Token, error) {
|
||||
orig := s.TTL
|
||||
s.TTL = ttl
|
||||
raw, tok, err := s.IssueWithRole(actor, role)
|
||||
s.TTL = orig
|
||||
return raw, tok, err
|
||||
return s.issue(actor, role, ttl)
|
||||
}
|
||||
|
||||
// Verify checks a token. Returns ErrInvalidToken or ErrExpiredToken.
|
||||
|
||||
47
internal/services/session/ttl_test.go
Normal file
47
internal/services/session/ttl_test.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestSigner_TTLNotShared beweist Fix #1: IssueWithRoleTTL darf das geteilte
|
||||
// s.TTL nicht mehr mutieren. Unter `go test -race` schlägt die alte Version
|
||||
// als Data-Race an; zusätzlich prüfen wir, dass parallele normale Logins nie
|
||||
// die kurze TOTP-TTL erben.
|
||||
func TestSigner_TTLNotShared(t *testing.T) {
|
||||
s := NewSigner([]byte("0123456789abcdef0123456789abcdef"), nil, time.Hour)
|
||||
var wg sync.WaitGroup
|
||||
var bad int32
|
||||
for i := 0; i < 200; i++ {
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _, _ = s.IssueWithRoleTTL("a", "totp_pending", 2*time.Minute)
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, tok, err := s.IssueWithRole("b", "admin")
|
||||
if err != nil {
|
||||
atomic.AddInt32(&bad, 1)
|
||||
return
|
||||
}
|
||||
// Normale Session muss ~1h gelten, nie die 2-Min-TOTP-TTL.
|
||||
if tok.Exp-tok.Iat < int64((30 * time.Minute).Seconds()) {
|
||||
atomic.AddInt32(&bad, 1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if bad > 0 {
|
||||
t.Fatalf("%d normale Tokens bekamen eine zu kurze TTL → geteilter Zustand", bad)
|
||||
}
|
||||
|
||||
// TTL-Override wirkt weiterhin korrekt für den TOTP-Token.
|
||||
_, ptok, _ := s.IssueWithRoleTTL("x", "totp_pending", 2*time.Minute)
|
||||
if d := ptok.Exp - ptok.Iat; d > int64((3 * time.Minute).Seconds()) {
|
||||
t.Fatalf("totp-pending TTL = %ds, want ~120s", d)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package waf
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -26,8 +28,12 @@ type Alert struct {
|
||||
// AlertWriter accepts Alert values via a buffered channel and writes
|
||||
// them to PostgreSQL asynchronously so SPOE handling stays low-latency.
|
||||
type AlertWriter struct {
|
||||
pool *pgxpool.Pool
|
||||
ch chan Alert
|
||||
pool *pgxpool.Pool
|
||||
ch chan Alert
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
closeOnce sync.Once
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
// NewAlertWriter creates an AlertWriter and starts its background goroutine.
|
||||
@@ -36,14 +42,19 @@ func NewAlertWriter(pool *pgxpool.Pool, bufSize int) *AlertWriter {
|
||||
aw := &AlertWriter{
|
||||
pool: pool,
|
||||
ch: make(chan Alert, bufSize),
|
||||
stop: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go aw.run()
|
||||
return aw
|
||||
}
|
||||
|
||||
// Send enqueues an alert. Drops silently if the channel is full to
|
||||
// avoid slowing down SPOE request handling.
|
||||
// Send enqueues an alert. Drops silently if the channel is full (or the
|
||||
// writer is closing) to avoid slowing down / panicking SPOE handling.
|
||||
func (aw *AlertWriter) Send(a Alert) {
|
||||
if aw.closed.Load() {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case aw.ch <- a:
|
||||
default:
|
||||
@@ -51,9 +62,34 @@ func (aw *AlertWriter) Send(a Alert) {
|
||||
}
|
||||
}
|
||||
|
||||
// Close stops the writer and flushes buffered alerts (best-effort).
|
||||
// Safe to call multiple times. The channel is never closed → Send never
|
||||
// panics even if it races with Close.
|
||||
func (aw *AlertWriter) Close() {
|
||||
aw.closeOnce.Do(func() {
|
||||
aw.closed.Store(true)
|
||||
close(aw.stop)
|
||||
})
|
||||
<-aw.done
|
||||
}
|
||||
|
||||
func (aw *AlertWriter) run() {
|
||||
for a := range aw.ch {
|
||||
aw.write(a)
|
||||
defer close(aw.done)
|
||||
for {
|
||||
select {
|
||||
case a := <-aw.ch:
|
||||
aw.write(a)
|
||||
case <-aw.stop:
|
||||
// Restliche gepufferte Alerts noch wegschreiben, dann Ende.
|
||||
for {
|
||||
select {
|
||||
case a := <-aw.ch:
|
||||
aw.write(a)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
61
internal/waf/alerts_test.go
Normal file
61
internal/waf/alerts_test.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package waf
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
||||
)
|
||||
|
||||
// Beweist Fix #15: AlertWriter.Close() flusht, ist idempotent, und Send/Close
|
||||
// racen ohne Panic (Kanal wird nie geschlossen). Guarded per EG_FWTEST_DSN.
|
||||
func TestAlertWriter_CloseFlush(t *testing.T) {
|
||||
dsn := os.Getenv("EG_FWTEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("set EG_FWTEST_DSN to run the alert-writer test")
|
||||
}
|
||||
ctx := context.Background()
|
||||
var mErr error
|
||||
for i := 0; i < 3; i++ {
|
||||
if mErr = database.Migrate(ctx, dsn); mErr == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(700 * time.Millisecond)
|
||||
}
|
||||
if mErr != nil {
|
||||
t.Fatalf("migrate: %v", mErr)
|
||||
}
|
||||
pool, err := database.Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
aw := NewAlertWriter(pool, 64)
|
||||
for i := 0; i < 20; i++ {
|
||||
aw.Send(Alert{Hostname: "t.local", ClientIP: "203.0.113.1", Method: "GET", URI: "/", Action: "detected"})
|
||||
}
|
||||
|
||||
// Send parallel zu Close → darf nicht paniken.
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); aw.Send(Alert{Hostname: "t.local", Action: "detected"}) }()
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { aw.Close(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("Close() did not return (flush hung)")
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Idempotent + Send nach Close ist No-op (kein Panic).
|
||||
aw.Close()
|
||||
aw.Send(Alert{Hostname: "after.local", Action: "detected"})
|
||||
}
|
||||
@@ -66,14 +66,10 @@ func buildDirectives(cfg models.WafConfig, crsDir string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// Trusted proxies: tell Coraza to trust X-Forwarded-For from these IPs.
|
||||
for _, ip := range cfg.TrustedProxies {
|
||||
ip = strings.TrimSpace(ip)
|
||||
if ip != "" {
|
||||
sb.WriteString(fmt.Sprintf("SecRemoteRulesFailAction Abort\n"))
|
||||
_ = ip // used in custom rules below if needed
|
||||
}
|
||||
}
|
||||
// Trusted proxies are NOT a SecLang directive — they are applied in the
|
||||
// SPOE agent (spoe.go): when the connection source is a trusted proxy,
|
||||
// the real client IP is taken from X-Forwarded-For before Coraza sees
|
||||
// it. (Previously this loop emitted a bogus, unrelated directive.)
|
||||
|
||||
// Custom rules (appended last so they can override CRS).
|
||||
if strings.TrimSpace(cfg.CustomRules) != "" {
|
||||
|
||||
@@ -3,6 +3,7 @@ package waf
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/corazawaf/coraza/v3"
|
||||
@@ -12,8 +13,9 @@ import (
|
||||
|
||||
// DomainEngine bundles a Coraza WAF with its operating mode.
|
||||
type DomainEngine struct {
|
||||
WAF coraza.WAF
|
||||
Mode string // "detection" | "blocking"
|
||||
WAF coraza.WAF
|
||||
Mode string // "detection" | "blocking"
|
||||
TrustedProxies []string // wenn src ∈ diese → echte Client-IP aus X-Forwarded-For
|
||||
}
|
||||
|
||||
// Manager holds per-domain Coraza engine instances. Engines are
|
||||
@@ -90,7 +92,7 @@ func (m *Manager) Reload(domains []DomainConfig) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("waf: build engine for %s: %w", dc.Hostname, err)
|
||||
}
|
||||
newEngines[dc.Hostname] = &DomainEngine{WAF: waf, Mode: dc.Config.Mode}
|
||||
newEngines[dc.Hostname] = &DomainEngine{WAF: waf, Mode: dc.Config.Mode, TrustedProxies: dc.Config.TrustedProxies}
|
||||
slog.Info("waf: engine (re)loaded",
|
||||
"host", dc.Hostname,
|
||||
"mode", dc.Config.Mode,
|
||||
@@ -110,8 +112,9 @@ func (m *Manager) Reload(domains []DomainConfig) error {
|
||||
// (nil, false) when the domain has no WAF or WAF is disabled.
|
||||
func (m *Manager) GetForHost(host string) (*DomainEngine, bool) {
|
||||
// Strip port if present (e.g. "example.com:443" → "example.com").
|
||||
if i := lastColon(host); i >= 0 {
|
||||
host = host[:i]
|
||||
// SplitHostPort errors for a bare host or bare IPv6 literal → keep as-is.
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
}
|
||||
m.mu.RLock()
|
||||
de, ok := m.engines[host]
|
||||
@@ -122,36 +125,3 @@ func (m *Manager) GetForHost(host string) (*DomainEngine, bool) {
|
||||
return de, true
|
||||
}
|
||||
|
||||
// lastColon returns the index of the last ':' in s that looks like a
|
||||
// port separator (after the final ']' for IPv6), or -1.
|
||||
func lastColon(s string) int {
|
||||
// IPv6 addresses in brackets: "[::1]:443"
|
||||
if len(s) > 0 && s[0] == '[' {
|
||||
if rb := lastByte(s, ']'); rb >= 0 && rb < len(s)-1 && s[rb+1] == ':' {
|
||||
return rb + 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
// Plain host — only strip port if there's exactly one colon.
|
||||
count := 0
|
||||
idx := -1
|
||||
for i, c := range s {
|
||||
if c == ':' {
|
||||
count++
|
||||
idx = i
|
||||
}
|
||||
}
|
||||
if count == 1 {
|
||||
return idx
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func lastByte(s string, b byte) int {
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
if s[i] == b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package waf
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -75,6 +76,15 @@ func (a *SPOEAgent) handle(ctx context.Context, w *encoding.ActionWriter, m *enc
|
||||
return // WAF not configured or disabled for this domain
|
||||
}
|
||||
|
||||
// Trusted-Proxy-Handling: stammt die Verbindung von einem konfigurierten
|
||||
// Trusted-Proxy, ist die echte Client-IP das letzte X-Forwarded-For-Glied
|
||||
// (das der Proxy angehängt hat), nicht die Proxy-IP selbst.
|
||||
if clientIP != "" && len(de.TrustedProxies) > 0 && ipMatchesAny(clientIP, de.TrustedProxies) {
|
||||
if real := rightmostXFF(rawHdrs); real != "" {
|
||||
clientIP = real
|
||||
}
|
||||
}
|
||||
|
||||
tx := de.WAF.NewTransaction()
|
||||
defer func() {
|
||||
tx.ProcessLogging()
|
||||
@@ -165,6 +175,53 @@ func (a *SPOEAgent) sendAlert(host, clientIP, method, uri string, mr types.Match
|
||||
})
|
||||
}
|
||||
|
||||
// rightmostXFF gibt den letzten (vom nächstgelegenen Proxy angehängten)
|
||||
// X-Forwarded-For-Eintrag zurück, sofern es eine gültige IP ist.
|
||||
func rightmostXFF(rawHdrs string) string {
|
||||
var val string
|
||||
for _, line := range strings.Split(rawHdrs, "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
idx := strings.IndexByte(line, ':')
|
||||
if idx <= 0 {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(line[:idx]), "x-forwarded-for") {
|
||||
val = strings.TrimSpace(line[idx+1:]) // letzter XFF-Header gewinnt
|
||||
}
|
||||
}
|
||||
if val == "" {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(val, ",")
|
||||
cand := strings.TrimSpace(parts[len(parts)-1])
|
||||
if net.ParseIP(cand) == nil {
|
||||
return ""
|
||||
}
|
||||
return cand
|
||||
}
|
||||
|
||||
// ipMatchesAny prüft, ob ip exakt einer IP oder einem CIDR aus list entspricht.
|
||||
func ipMatchesAny(ip string, list []string) bool {
|
||||
parsed := net.ParseIP(ip)
|
||||
if parsed == nil {
|
||||
return false
|
||||
}
|
||||
for _, e := range list {
|
||||
e = strings.TrimSpace(e)
|
||||
if e == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(e, "/") {
|
||||
if _, n, err := net.ParseCIDR(e); err == nil && n.Contains(parsed) {
|
||||
return true
|
||||
}
|
||||
} else if pe := net.ParseIP(e); pe != nil && pe.Equal(parsed) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseHeaders splits HAProxy raw headers ("Name: value\r\n…") and
|
||||
// calls fn for each valid header line.
|
||||
func parseHeaders(raw string, fn func(name, val string)) {
|
||||
|
||||
37
internal/waf/spoe_test.go
Normal file
37
internal/waf/spoe_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package waf
|
||||
|
||||
import "testing"
|
||||
|
||||
// Beweist Fix #2: Trusted-Proxy-XFF-Auflösung.
|
||||
func TestRightmostXFF(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"X-Forwarded-For: 203.0.113.7": "203.0.113.7",
|
||||
"X-Forwarded-For: 203.0.113.7, 10.0.0.1": "10.0.0.1", // rightmost
|
||||
"x-forwarded-for: 1.2.3.4 , 5.6.7.8": "5.6.7.8",
|
||||
"Host: x\r\nX-Forwarded-For: 2001:db8::1": "2001:db8::1",
|
||||
"X-Forwarded-For: not-an-ip": "",
|
||||
"User-Agent: foo": "",
|
||||
"": "",
|
||||
}
|
||||
for raw, want := range cases {
|
||||
if got := rightmostXFF(raw); got != want {
|
||||
t.Errorf("rightmostXFF(%q) = %q, want %q", raw, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPMatchesAny(t *testing.T) {
|
||||
list := []string{"10.0.0.5", "192.168.0.0/16", "2001:db8::/32"}
|
||||
yes := []string{"10.0.0.5", "192.168.4.7", "2001:db8::abcd"}
|
||||
no := []string{"10.0.0.6", "172.16.0.1", "2002::1", "garbage"}
|
||||
for _, ip := range yes {
|
||||
if !ipMatchesAny(ip, list) {
|
||||
t.Errorf("ipMatchesAny(%q) = false, want true", ip)
|
||||
}
|
||||
}
|
||||
for _, ip := range no {
|
||||
if ipMatchesAny(ip, list) {
|
||||
t.Errorf("ipMatchesAny(%q) = true, want false", ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,42 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
// wg-quick is managed via systemd unit instances (wg-quick@<iface>).
|
||||
// Reload-via-syncconf would be cheaper (no link flap) but needs more
|
||||
// per-change diffing — for v1 we restart the unit, which takes ~1s
|
||||
// and re-establishes peers cleanly. The sudoers entry shipped in
|
||||
// postinst whitelists exactly these three commands.
|
||||
// Für ein BEREITS laufendes Interface werden Config-Änderungen per
|
||||
// `wg syncconf` LIVE angewendet (siehe syncWGQuick) — ohne Link-Flap,
|
||||
// damit bestehende Tunnel nie abreißen. Nur das erstmalige Hochfahren
|
||||
// (Interface noch nicht vorhanden) nutzt `systemctl start`. restart bleibt
|
||||
// als Fallback, falls syncconf nicht erlaubt/möglich ist. Die sudoers-
|
||||
// Einträge (postinst) whitelisten exakt diese Kommandos.
|
||||
|
||||
// interfaceExists meldet ob das wg-Interface aktuell existiert (also von
|
||||
// wg-quick bereits hochgefahren wurde). `ip link show` braucht kein root.
|
||||
func interfaceExists(iface string) bool {
|
||||
return exec.Command("/usr/bin/ip", "link", "show", iface).Run() == nil
|
||||
}
|
||||
|
||||
// syncWGQuick wendet Config-Änderungen LIVE auf ein laufendes Interface an
|
||||
// (`wg syncconf`) — Peers werden hinzugefügt/entfernt/aktualisiert und der
|
||||
// Listen-Port gesetzt, OHNE den Tunnel abzureißen. `wg-quick strip` liefert
|
||||
// die reine wg-Config (ohne Address/MTU/Routes-Direktiven). Beides braucht
|
||||
// root (Config ist root:root 700) → sudo.
|
||||
func syncWGQuick(iface string) error {
|
||||
stripped, err := exec.Command("sudo", "-n", "/usr/bin/wg-quick", "strip", iface).Output()
|
||||
if err != nil {
|
||||
return fmt.Errorf("wg-quick strip %s: %w", iface, err)
|
||||
}
|
||||
sync := exec.Command("sudo", "-n", "/usr/bin/wg", "syncconf", iface, "/dev/stdin")
|
||||
sync.Stdin = bytes.NewReader(stripped)
|
||||
if out, err := sync.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("wg syncconf %s: %w: %s", iface, err, string(out))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func startWGQuick(iface string) error {
|
||||
cmd := exec.Command("sudo", "-n", "/usr/bin/systemctl", "start", "wg-quick@"+iface+".service")
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/configgen"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/models"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/services/secrets"
|
||||
wgsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/wireguard"
|
||||
@@ -27,10 +29,11 @@ import (
|
||||
const ConfDir = "/etc/edgeguard/wireguard"
|
||||
|
||||
type Generator struct {
|
||||
Pool *pgxpool.Pool
|
||||
Box *secrets.Box
|
||||
Ifaces *wgsvc.InterfacesRepo
|
||||
Peers *wgsvc.PeersRepo
|
||||
Pool *pgxpool.Pool
|
||||
Box *secrets.Box
|
||||
Ifaces *wgsvc.InterfacesRepo
|
||||
Peers *wgsvc.PeersRepo
|
||||
SkipReload bool // nur Configs schreiben, keine wg-quick@-Service-Aktionen
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, box *secrets.Box) *Generator {
|
||||
@@ -151,8 +154,10 @@ func (g *Generator) Render(ctx context.Context) error {
|
||||
continue
|
||||
}
|
||||
_ = os.Remove(filepath.Join(ConfDir, e.Name()))
|
||||
_ = stopWGQuick(ifaceName)
|
||||
_ = disableWGQuick(ifaceName)
|
||||
if !g.SkipReload {
|
||||
_ = stopWGQuick(ifaceName)
|
||||
_ = disableWGQuick(ifaceName)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -228,21 +233,46 @@ func (g *Generator) renderIface(ctx context.Context, ifc models.WireguardInterfa
|
||||
}
|
||||
|
||||
path := filepath.Join(ConfDir, ifc.Name+".conf")
|
||||
// Config (enthält den Private Key) ZUERST atomar schreiben — vorher
|
||||
// keinen Symlink/Service auf eine evtl. fehlende/abgeschnittene Datei
|
||||
// zeigen lassen. AtomicWrite = temp+fsync+rename, 0600.
|
||||
changed := true
|
||||
if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, body.Bytes()) {
|
||||
changed = false
|
||||
}
|
||||
if changed {
|
||||
if err := configgen.AtomicWrite(path, body.Bytes(), 0o600); err != nil {
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
}
|
||||
if g.SkipReload {
|
||||
return nil
|
||||
}
|
||||
// wg-quick@<iface>.service liest /etc/wireguard/<iface>.conf (Distro-
|
||||
// Default), nicht unseren ConfDir. Wir lassen die Quelle of truth in
|
||||
// /etc/edgeguard/wireguard/ und symlinken via sudo — /etc/wireguard/
|
||||
// ist root:root 700, daher braucht es sudo /bin/ln. Das sudoers-Entry
|
||||
// wird von postinst angelegt.
|
||||
// Default), nicht unseren ConfDir. Symlink via sudo (/etc/wireguard/
|
||||
// ist root:root 700). Das sudoers-Entry wird von postinst angelegt.
|
||||
if err := symlinkWGQuickConf(ifc.Name, path); err != nil {
|
||||
return fmt.Errorf("symlink: %w", err)
|
||||
}
|
||||
_ = enableWGQuick(ifc.Name)
|
||||
if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, body.Bytes()) {
|
||||
return startWGQuick(ifc.Name)
|
||||
|
||||
// Läuft das Interface schon, werden Änderungen LIVE per `wg syncconf`
|
||||
// angewendet — KEIN Tunnel-Abbruch (WireGuard darf nie abreißen). Nur
|
||||
// das erstmalige Hochfahren nutzt `systemctl start`.
|
||||
if interfaceExists(ifc.Name) {
|
||||
if !changed {
|
||||
return nil // läuft + Config unverändert → nichts zu tun
|
||||
}
|
||||
if err := syncWGQuick(ifc.Name); err != nil {
|
||||
// Fallback (z. B. sudoers noch ohne syncconf): voller Neustart.
|
||||
// Bricht den Tunnel kurz ab — nur Notnagel.
|
||||
slog.Warn("wireguard: wg syncconf fehlgeschlagen, Fallback auf restart (kurzer Tunnel-Flap)",
|
||||
"iface", ifc.Name, "error", err)
|
||||
return restartWGQuick(ifc.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := os.WriteFile(path, body.Bytes(), 0o600); err != nil {
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
return restartWGQuick(ifc.Name)
|
||||
// Interface noch nicht oben → erstmalig hochfahren.
|
||||
return startWGQuick(ifc.Name)
|
||||
}
|
||||
|
||||
|
||||
@@ -1372,6 +1372,7 @@
|
||||
"yes": "Ja",
|
||||
"no": "Nein",
|
||||
"or": "oder",
|
||||
"status": "Status",
|
||||
"save": "Speichern",
|
||||
"cancel": "Abbrechen",
|
||||
"loading": "Lädt …",
|
||||
|
||||
@@ -1372,6 +1372,7 @@
|
||||
"yes": "Yes",
|
||||
"no": "No",
|
||||
"or": "or",
|
||||
"status": "Status",
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"loading": "Loading …",
|
||||
|
||||
@@ -111,6 +111,9 @@ edgeguard ALL=(root) NOPASSWD: /bin/systemctl enable wg-quick@*.service
|
||||
edgeguard ALL=(root) NOPASSWD: /bin/systemctl disable wg-quick@*.service
|
||||
edgeguard ALL=(root) NOPASSWD: /usr/bin/wg show all dump
|
||||
edgeguard ALL=(root) NOPASSWD: /usr/bin/wg show *
|
||||
# WireGuard Live-Reload ohne Tunnel-Abbruch: wg syncconf + wg-quick strip
|
||||
edgeguard ALL=(root) NOPASSWD: /usr/bin/wg syncconf *
|
||||
edgeguard ALL=(root) NOPASSWD: /usr/bin/wg-quick strip *
|
||||
# WireGuard symlink: /etc/wireguard/ ist root:root 700; edgeguard-api
|
||||
# legt Symlinks an damit wg-quick@<iface> die Configs findet.
|
||||
edgeguard ALL=(root) NOPASSWD: /bin/ln -sf /etc/edgeguard/wireguard/* /etc/wireguard/*
|
||||
|
||||
Reference in New Issue
Block a user