Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a707e2e3f | ||
|
|
f85552a475 | ||
|
|
92c5e25557 | ||
|
|
9383b870b0 | ||
|
|
4416d361a0 |
@@ -58,6 +58,7 @@ import (
|
|||||||
"git.netcell-it.de/projekte/edgeguard-native/internal/services/setup"
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/setup"
|
||||||
"git.netcell-it.de/projekte/edgeguard-native/internal/services/tlscerts"
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/tlscerts"
|
||||||
wgsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/wireguard"
|
wgsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/wireguard"
|
||||||
|
oidcsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/oidc"
|
||||||
usersvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/users"
|
usersvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/users"
|
||||||
wafsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/waf"
|
wafsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/waf"
|
||||||
)
|
)
|
||||||
@@ -316,6 +317,14 @@ func main() {
|
|||||||
authed.Use(requireAuth, handlers.RequireAdminForMutations())
|
authed.Use(requireAuth, handlers.RequireAdminForMutations())
|
||||||
setupHdl.RegisterAuthed(authed)
|
setupHdl.RegisterAuthed(authed)
|
||||||
handlers.NewUsersHandler(usersRepo, auditRepo, nodeID).Register(authed)
|
handlers.NewUsersHandler(usersRepo, auditRepo, nodeID).Register(authed)
|
||||||
|
|
||||||
|
// OIDC/Keycloak SSO — public Flow-Endpoints auf v1 (hinter SetupGate),
|
||||||
|
// Admin-Settings auf authed (PUT nur admin via RequireAdminForMutations).
|
||||||
|
oidcRepo := oidcsvc.New(pool, secretsBox)
|
||||||
|
oidcHdl := handlers.NewOIDCHandler(oidcRepo, oidcsvc.NewClient(oidcRepo), usersRepo, signer, setupStore).
|
||||||
|
WithAudit(auditRepo, nodeID)
|
||||||
|
oidcHdl.RegisterPublic(v1)
|
||||||
|
oidcHdl.RegisterAdmin(authed)
|
||||||
handlers.NewDomainsHandler(domainsRepo, routingRepo, domainHeadersRepo, auditRepo, nodeID, haproxyReloader).Register(authed)
|
handlers.NewDomainsHandler(domainsRepo, routingRepo, domainHeadersRepo, auditRepo, nodeID, haproxyReloader).Register(authed)
|
||||||
handlers.NewBackendsHandler(backendsRepo, auditRepo, nodeID, haproxyReloader).Register(authed)
|
handlers.NewBackendsHandler(backendsRepo, auditRepo, nodeID, haproxyReloader).Register(authed)
|
||||||
handlers.NewBackendServersHandler(backendServersRepo, auditRepo, nodeID, haproxyReloader).Register(authed)
|
handlers.NewBackendServersHandler(backendServersRepo, auditRepo, nodeID, haproxyReloader).Register(authed)
|
||||||
|
|||||||
2
go.mod
2
go.mod
@@ -4,6 +4,7 @@ go 1.26.0
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/corazawaf/coraza/v3 v3.7.0
|
github.com/corazawaf/coraza/v3 v3.7.0
|
||||||
|
github.com/coreos/go-oidc/v3 v3.18.0
|
||||||
github.com/dropmorepackets/haproxy-go v0.0.8
|
github.com/dropmorepackets/haproxy-go v0.0.8
|
||||||
github.com/fsnotify/fsnotify v1.10.1
|
github.com/fsnotify/fsnotify v1.10.1
|
||||||
github.com/gin-gonic/gin v1.10.0
|
github.com/gin-gonic/gin v1.10.0
|
||||||
@@ -16,6 +17,7 @@ require (
|
|||||||
github.com/pressly/goose/v3 v3.27.1
|
github.com/pressly/goose/v3 v3.27.1
|
||||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||||
golang.org/x/crypto v0.51.0
|
golang.org/x/crypto v0.51.0
|
||||||
|
golang.org/x/oauth2 v0.36.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|||||||
4
go.sum
4
go.sum
@@ -19,6 +19,8 @@ github.com/corazawaf/coraza/v3 v3.7.0 h1:LIQqu1r+l6e/U/gyiZeykWaNNBY1TzRLz+aaI+Q
|
|||||||
github.com/corazawaf/coraza/v3 v3.7.0/go.mod h1:dOSt5evqC7EstouEv6ghhui01+oVUwp9X1vybWwqTlo=
|
github.com/corazawaf/coraza/v3 v3.7.0/go.mod h1:dOSt5evqC7EstouEv6ghhui01+oVUwp9X1vybWwqTlo=
|
||||||
github.com/corazawaf/libinjection-go v0.3.2 h1:9rrKt0lpg4WvUXt+lwS06GywfqRXXsa/7JcOw5cQLwI=
|
github.com/corazawaf/libinjection-go v0.3.2 h1:9rrKt0lpg4WvUXt+lwS06GywfqRXXsa/7JcOw5cQLwI=
|
||||||
github.com/corazawaf/libinjection-go v0.3.2/go.mod h1:Ik/+w3UmTWH9yn366RgS9D95K3y7Atb5m/H/gXzzPCk=
|
github.com/corazawaf/libinjection-go v0.3.2/go.mod h1:Ik/+w3UmTWH9yn366RgS9D95K3y7Atb5m/H/gXzzPCk=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
@@ -190,6 +192,8 @@ golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
|||||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||||
|
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||||
|
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
-- +goose Up
|
-- +goose Up
|
||||||
-- +goose StatementBegin
|
-- +goose StatementBegin
|
||||||
|
|
||||||
-- network_interfaces und ip_addresses werden in die Cluster-Replikation
|
-- HINWEIS (korrigiert v1.2.89): Diese Migration war urspr. dafür gedacht,
|
||||||
-- aufgenommen. Das ALTER PUBLICATION erfordert den Superuser (postgres),
|
-- network_interfaces und ip_addresses in die Cluster-Replikation aufzunehmen.
|
||||||
-- daher läuft es im postinst via `sudo -u postgres psql`, nicht hier.
|
-- Das wurde NICHT umgesetzt und ist auch NICHT gewollt: beide Tabellen sind
|
||||||
-- Diese Migration dient nur als Versions-Marker für goose.
|
-- node-spezifisch (jede Node hat eigene Mgmt-/Host-IPs) und stehen weiterhin
|
||||||
|
-- in cluster_replication.go localOnlyTables → sie werden bewusst NICHT
|
||||||
|
-- repliziert. Sie sind auch aus dem Drift-Hash (confighash.go) entfernt,
|
||||||
|
-- da sie sonst dauerhaften False-Positive-Drift erzeugen.
|
||||||
|
-- Diese Migration ist ein No-op / reiner Versions-Marker für goose.
|
||||||
SELECT 1;
|
SELECT 1;
|
||||||
|
|
||||||
-- +goose StatementEnd
|
-- +goose StatementEnd
|
||||||
|
|||||||
35
internal/database/migrations/0040_oidc_settings.sql
Normal file
35
internal/database/migrations/0040_oidc_settings.sql
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
-- +goose Up
|
||||||
|
-- +goose StatementBegin
|
||||||
|
|
||||||
|
-- OIDC / Keycloak SSO — Singleton-Settings (analog forward_proxy_settings).
|
||||||
|
-- client_secret_enc: secrets.Box.Seal-Output (AES-256-GCM), NULL = nicht gesetzt.
|
||||||
|
-- Rolle kommt bewusst NICHT aus dem Token, daher keine group/role-claim-Spalten.
|
||||||
|
CREATE TABLE IF NOT EXISTS oidc_settings (
|
||||||
|
id INTEGER PRIMARY KEY DEFAULT 1,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
issuer_url TEXT NOT NULL DEFAULT '',
|
||||||
|
client_id TEXT NOT NULL DEFAULT '',
|
||||||
|
client_secret_enc BYTEA,
|
||||||
|
scopes TEXT NOT NULL DEFAULT 'openid email profile',
|
||||||
|
email_claim TEXT NOT NULL DEFAULT 'email',
|
||||||
|
button_label TEXT NOT NULL DEFAULT 'Sign in with SSO',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT oidc_settings_singleton CHECK (id = 1)
|
||||||
|
);
|
||||||
|
INSERT INTO oidc_settings (id) VALUES (1) ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
-- Opportunistisches Linking: beim ersten SSO-Login wird der OIDC-'sub'
|
||||||
|
-- gespeichert; weicht er später ab, wird der Login abgelehnt. Nullable,
|
||||||
|
-- kein Backfill (Match-Schlüssel bleibt die verifizierte E-Mail).
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS oidc_subject TEXT;
|
||||||
|
|
||||||
|
-- +goose StatementEnd
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
-- +goose StatementBegin
|
||||||
|
|
||||||
|
ALTER TABLE users DROP COLUMN IF EXISTS oidc_subject;
|
||||||
|
DROP TABLE IF EXISTS oidc_settings;
|
||||||
|
|
||||||
|
-- +goose StatementEnd
|
||||||
@@ -22,6 +22,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
_ "embed"
|
_ "embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -138,6 +139,7 @@ type View struct {
|
|||||||
type WGSiteMasqEntry struct {
|
type WGSiteMasqEntry struct {
|
||||||
Iface string // wg interface name, e.g. "wg7"
|
Iface string // wg interface name, e.g. "wg7"
|
||||||
VPNNet string // network CIDR of the VPN subnet, e.g. "192.168.99.0/24"
|
VPNNet string // network CIDR of the VPN subnet, e.g. "192.168.99.0/24"
|
||||||
|
L3 string // "ip" oder "ip6" — Familie von VPNNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// AutoFWRule is one auto-emitted inbound rule. Proto is "tcp" or
|
// AutoFWRule is one auto-emitted inbound rule. Proto is "tcp" or
|
||||||
@@ -162,6 +164,10 @@ type RuleLeg struct {
|
|||||||
DstIfaces []string
|
DstIfaces []string
|
||||||
SrcAddrs []string
|
SrcAddrs []string
|
||||||
DstAddrs []string
|
DstAddrs []string
|
||||||
|
// L3 ist "ip" (IPv4) oder "ip6" (IPv6) für das Adress-Matching —
|
||||||
|
// gesetzt, sobald SrcAddrs/DstAddrs nicht leer sind. Bei adresslosen
|
||||||
|
// Regeln bleibt es "" (familienagnostisch, kein ip/ip6-Match).
|
||||||
|
L3 string
|
||||||
Service ResolvedService // Proto="" → no service match (any)
|
Service ResolvedService // Proto="" → no service match (any)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,6 +201,12 @@ type ResolvedNATRule struct {
|
|||||||
DPortStart, DPortEnd int
|
DPortStart, DPortEnd int
|
||||||
TargetAddr string
|
TargetAddr string
|
||||||
TargetPortStart, TargetPortEnd int
|
TargetPortStart, TargetPortEnd int
|
||||||
|
// L3 ist "ip" oder "ip6" — Adressfamilie der Regel (aus SrcCIDR/
|
||||||
|
// DstCIDR/TargetAddr abgeleitet). TargetHost ist TargetAddr, bei
|
||||||
|
// IPv6 MIT Port in eckigen Klammern ("[2001:db8::1]") für korrekte
|
||||||
|
// nft-dnat-Syntax.
|
||||||
|
L3 string
|
||||||
|
TargetHost string
|
||||||
Comment string
|
Comment string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,26 +292,15 @@ func (g *Generator) loadView(ctx context.Context) (*View, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Expand to one Leg per (rule × service); rules without a service
|
// Expand to one Leg per (rule × service × address-family). Rules
|
||||||
// produce one leg with empty Proto.
|
// without a service produce one leg-set with empty Proto.
|
||||||
for _, r := range rules {
|
for _, r := range rules {
|
||||||
if len(r.Services) == 0 {
|
if len(r.Services) == 0 {
|
||||||
view.Legs = append(view.Legs, RuleLeg{
|
view.Legs = append(view.Legs, expandFamilyLegs(r, ResolvedService{}, false)...)
|
||||||
RuleID: r.ID, Action: r.Action, Log: r.Log, Name: r.Name,
|
|
||||||
Comment: r.Comment,
|
|
||||||
SrcIfaces: r.SrcIfaces, DstIfaces: r.DstIfaces,
|
|
||||||
SrcAddrs: r.SrcAddrs, DstAddrs: r.DstAddrs,
|
|
||||||
})
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, svc := range r.Services {
|
for _, svc := range r.Services {
|
||||||
view.Legs = append(view.Legs, RuleLeg{
|
view.Legs = append(view.Legs, expandFamilyLegs(r, svc, true)...)
|
||||||
RuleID: r.ID, Action: r.Action, Log: r.Log, Name: r.Name,
|
|
||||||
Comment: r.Comment,
|
|
||||||
SrcIfaces: r.SrcIfaces, DstIfaces: r.DstIfaces,
|
|
||||||
SrcAddrs: r.SrcAddrs, DstAddrs: r.DstAddrs,
|
|
||||||
Service: svc,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,9 +324,14 @@ func (g *Generator) loadView(ctx context.Context) (*View, error) {
|
|||||||
if wgRows.Scan(&name, &cidr) == nil {
|
if wgRows.Scan(&name, &cidr) == nil {
|
||||||
view.WGServerIfaces = append(view.WGServerIfaces, name)
|
view.WGServerIfaces = append(view.WGServerIfaces, name)
|
||||||
if _, ipNet, err := net.ParseCIDR(cidr); err == nil {
|
if _, ipNet, err := net.ParseCIDR(cidr); err == nil {
|
||||||
|
l3 := addrFamily(ipNet.String())
|
||||||
|
if l3 == "" {
|
||||||
|
l3 = "ip"
|
||||||
|
}
|
||||||
view.WGSiteMasq = append(view.WGSiteMasq, WGSiteMasqEntry{
|
view.WGSiteMasq = append(view.WGSiteMasq, WGSiteMasqEntry{
|
||||||
Iface: name,
|
Iface: name,
|
||||||
VPNNet: ipNet.String(),
|
VPNNet: ipNet.String(),
|
||||||
|
L3: l3,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -435,6 +441,131 @@ func isLoopback(ip string) bool {
|
|||||||
return strings.HasPrefix(ip, "127.")
|
return strings.HasPrefix(ip, "127.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// addrFamily klassifiziert einen nft-Adressausdruck (host, CIDR oder
|
||||||
|
// range "a-b") als "ip" (IPv4), "ip6" (IPv6) oder "" (unbestimmt, z.B.
|
||||||
|
// FQDN-Platzhalter). Adressen enthalten selbst kein '-', daher trennt der
|
||||||
|
// erste Bindestrich sicher eine Range in ihr erstes Element.
|
||||||
|
func addrFamily(expr string) string {
|
||||||
|
expr = strings.TrimSpace(expr)
|
||||||
|
if expr == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if i := strings.IndexByte(expr, '-'); i > 0 {
|
||||||
|
expr = strings.TrimSpace(expr[:i])
|
||||||
|
}
|
||||||
|
if i := strings.IndexByte(expr, '/'); i > 0 {
|
||||||
|
expr = expr[:i]
|
||||||
|
}
|
||||||
|
ip := net.ParseIP(expr)
|
||||||
|
if ip == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if ip.To4() != nil {
|
||||||
|
return "ip"
|
||||||
|
}
|
||||||
|
return "ip6"
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitByFamily teilt eine Liste von nft-Adressausdrücken in v4 und v6.
|
||||||
|
// Unbestimmte (FQDN o.ä.) werden verworfen.
|
||||||
|
func splitByFamily(exprs []string) (v4, v6 []string) {
|
||||||
|
for _, e := range exprs {
|
||||||
|
switch addrFamily(e) {
|
||||||
|
case "ip":
|
||||||
|
v4 = append(v4, e)
|
||||||
|
case "ip6":
|
||||||
|
v6 = append(v6, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return v4, v6
|
||||||
|
}
|
||||||
|
|
||||||
|
// serviceL3: icmp ist v4-only, icmpv6 v6-only, tcp/udp/leer agnostisch.
|
||||||
|
func serviceL3(svc ResolvedService) string {
|
||||||
|
switch svc.Proto {
|
||||||
|
case "icmp":
|
||||||
|
return "ip"
|
||||||
|
case "icmpv6":
|
||||||
|
return "ip6"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// natFamily ermittelt die Adressfamilie einer NAT-Regel aus ihren
|
||||||
|
// Adressen. ok=false bei gemischten v4/v6-Adressen (ungültig → die Regel
|
||||||
|
// muss übersprungen werden, sonst bricht `nft -f` das gesamte Ruleset).
|
||||||
|
func natFamily(r ResolvedNATRule) (fam string, ok bool) {
|
||||||
|
for _, a := range []string{r.SrcCIDR, r.DstCIDR, r.TargetAddr} {
|
||||||
|
f := addrFamily(a)
|
||||||
|
if f == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fam == "" {
|
||||||
|
fam = f
|
||||||
|
} else if fam != f {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fam == "" {
|
||||||
|
fam = "ip" // keine Adressen (reine iface/proto-Regel) → v4-Default
|
||||||
|
}
|
||||||
|
return fam, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// expandFamilyLegs materialisiert die nft-Zeilen für eine Regel + optional
|
||||||
|
// einen Service, getrennt nach Adressfamilie. Adresslose Regeln ergeben eine
|
||||||
|
// einzige familienagnostische Zeile (unverändertes v4-Verhalten, greift
|
||||||
|
// zugleich für v6). Regeln mit Adressen werden pro Familie als separate
|
||||||
|
// Zeile emittiert — ein nft-Paket ist immer entweder v4 oder v6.
|
||||||
|
func expandFamilyLegs(r ResolvedRule, svc ResolvedService, hasSvc bool) []RuleLeg {
|
||||||
|
base := RuleLeg{
|
||||||
|
RuleID: r.ID, Action: r.Action, Log: r.Log, Name: r.Name, Comment: r.Comment,
|
||||||
|
SrcIfaces: r.SrcIfaces, DstIfaces: r.DstIfaces,
|
||||||
|
}
|
||||||
|
if hasSvc {
|
||||||
|
base.Service = svc
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(r.SrcAddrs) == 0 && len(r.DstAddrs) == 0 {
|
||||||
|
// Kein Adress-Match → eine Zeile, L3 leer. Die Proto-Render-Logik
|
||||||
|
// im Template setzt icmp/icmpv6 selbst familienkorrekt.
|
||||||
|
return []RuleLeg{base}
|
||||||
|
}
|
||||||
|
|
||||||
|
src4, src6 := splitByFamily(r.SrcAddrs)
|
||||||
|
dst4, dst6 := splitByFamily(r.DstAddrs)
|
||||||
|
svcFam := ""
|
||||||
|
if hasSvc {
|
||||||
|
svcFam = serviceL3(svc)
|
||||||
|
}
|
||||||
|
|
||||||
|
var legs []RuleLeg
|
||||||
|
for _, fam := range []string{"ip", "ip6"} {
|
||||||
|
if svcFam != "" && svcFam != fam {
|
||||||
|
continue // icmp nur auf v4, icmpv6 nur auf v6
|
||||||
|
}
|
||||||
|
srcF, dstF := src4, dst4
|
||||||
|
if fam == "ip6" {
|
||||||
|
srcF, dstF = src6, dst6
|
||||||
|
}
|
||||||
|
// Eine eingeschränkte Seite ohne Mitglied dieser Familie → die
|
||||||
|
// Zeile würde nichts (oder Falsches) matchen → überspringen.
|
||||||
|
if len(r.SrcAddrs) > 0 && len(srcF) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(r.DstAddrs) > 0 && len(dstF) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
leg := base
|
||||||
|
leg.L3 = fam
|
||||||
|
leg.SrcAddrs = srcF
|
||||||
|
leg.DstAddrs = dstF
|
||||||
|
legs = append(legs, leg)
|
||||||
|
}
|
||||||
|
return legs
|
||||||
|
}
|
||||||
|
|
||||||
// addrObjMap is keyed by id; value is the nft expression for that
|
// addrObjMap is keyed by id; value is the nft expression for that
|
||||||
// object (e.g. "1.2.3.4", "10.0.0.0/24", "1.2.3.4-1.2.3.10").
|
// object (e.g. "1.2.3.4", "10.0.0.0/24", "1.2.3.4-1.2.3.10").
|
||||||
type addrObjMap map[int64]string
|
type addrObjMap map[int64]string
|
||||||
@@ -693,6 +824,19 @@ ORDER BY priority DESC, id ASC`)
|
|||||||
if outZone != nil {
|
if outZone != nil {
|
||||||
r.OutIfaces = zoneIfaces[*outZone]
|
r.OutIfaces = zoneIfaces[*outZone]
|
||||||
}
|
}
|
||||||
|
fam, ok := natFamily(r)
|
||||||
|
if !ok {
|
||||||
|
// Gemischte v4/v6-Adressen → ungültige NAT-Regel. Überspringen
|
||||||
|
// statt das gesamte Ruleset mit `nft -f` zu brechen.
|
||||||
|
slog.Warn("firewall: NAT-Regel mit gemischten v4/v6-Adressen übersprungen", "id", r.ID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
r.L3 = fam
|
||||||
|
r.TargetHost = r.TargetAddr
|
||||||
|
if fam == "ip6" && r.TargetAddr != "" && r.TargetPortStart > 0 {
|
||||||
|
// nft braucht [v6]:port für dnat-Targets mit Port.
|
||||||
|
r.TargetHost = "[" + r.TargetAddr + "]"
|
||||||
|
}
|
||||||
out = append(out, r)
|
out = append(out, r)
|
||||||
}
|
}
|
||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
|
|||||||
132
internal/firewall/firewall_e2e_test.go
Normal file
132
internal/firewall/firewall_e2e_test.go
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
package firewall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestE2E_IPv6Render fährt den ECHTEN Generator gegen eine Test-DB:
|
||||||
|
// alle Migrations + v4/v6-Seed + RenderToString + nft -c. Nur aktiv, wenn
|
||||||
|
// EG_FWTEST_DSN gesetzt ist (sonst Skip — `go test ./...` bleibt DB-frei).
|
||||||
|
func TestE2E_IPv6Render(t *testing.T) {
|
||||||
|
dsn := os.Getenv("EG_FWTEST_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set EG_FWTEST_DSN to run the firewall end-to-end test")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := database.Migrate(ctx, dsn); err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
pool, err := database.Open(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open: %v", err)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
for _, tbl := range []string{
|
||||||
|
"firewall_nat_rules", "firewall_rules",
|
||||||
|
"firewall_address_group_members", "firewall_address_groups",
|
||||||
|
"firewall_address_objects", "network_interfaces",
|
||||||
|
} {
|
||||||
|
if _, err := pool.Exec(ctx, "DELETE FROM "+tbl); err != nil {
|
||||||
|
t.Fatalf("clean %s: %v", tbl, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mustExec := func(sql string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := pool.Exec(ctx, sql, args...); err != nil {
|
||||||
|
t.Fatalf("seed failed (%s): %v", sql, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
insID := func(sql string, args ...any) int64 {
|
||||||
|
t.Helper()
|
||||||
|
var id int64
|
||||||
|
if err := pool.QueryRow(ctx, sql, args...).Scan(&id); err != nil {
|
||||||
|
t.Fatalf("seed-id failed (%s): %v", sql, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
mustExec(`INSERT INTO network_interfaces (name,type,role) VALUES ('eth0','ethernet','wan'),('eth1','ethernet','lan')`)
|
||||||
|
|
||||||
|
v4net := insID(`INSERT INTO firewall_address_objects (name,kind,value) VALUES ('v4net','network','10.0.0.0/24') RETURNING id`)
|
||||||
|
v6net := insID(`INSERT INTO firewall_address_objects (name,kind,value) VALUES ('v6net','network','2001:db8:1::/64') RETURNING id`)
|
||||||
|
v6host := insID(`INSERT INTO firewall_address_objects (name,kind,value) VALUES ('v6host','host','2001:db8:2::5') RETURNING id`)
|
||||||
|
v6range := insID(`INSERT INTO firewall_address_objects (name,kind,value) VALUES ('v6range','range','2001:db8:3::1-2001:db8:3::9') RETURNING id`)
|
||||||
|
|
||||||
|
// Gemischte Gruppe (v4 + v6) → muss in zwei Familien-Zeilen splitten.
|
||||||
|
grp := insID(`INSERT INTO firewall_address_groups (name) VALUES ('mixed') RETURNING id`)
|
||||||
|
mustExec(`INSERT INTO firewall_address_group_members (group_id,object_id) VALUES ($1,$2),($1,$3)`, grp, v4net, v6net)
|
||||||
|
|
||||||
|
httpsSvc := insID(`INSERT INTO firewall_services (name,proto,port_start,port_end,builtin,description) VALUES ('t-https','tcp',443,443,false,'')
|
||||||
|
ON CONFLICT (name) DO UPDATE SET proto=excluded.proto RETURNING id`)
|
||||||
|
var pingV6 int64
|
||||||
|
_ = pool.QueryRow(ctx, `SELECT id FROM firewall_services WHERE proto='icmpv6' LIMIT 1`).Scan(&pingV6)
|
||||||
|
|
||||||
|
// (1) gemischte Gruppe + tcp443 → je eine ip- und ip6-Zeile.
|
||||||
|
mustExec(`INSERT INTO firewall_rules (name,action,src_zone,src_address_group_id,service_object_id) VALUES ('mixed-https','accept','any',$1,$2)`, grp, httpsSvc)
|
||||||
|
// (2) v6-host + icmpv6 → eine ip6-Zeile.
|
||||||
|
if pingV6 != 0 {
|
||||||
|
mustExec(`INSERT INTO firewall_rules (name,action,src_address_object_id,service_object_id) VALUES ('v6-ping','accept',$1,$2)`, v6host, pingV6)
|
||||||
|
}
|
||||||
|
// (3) v6-range src + v6net dst (kein Service).
|
||||||
|
mustExec(`INSERT INTO firewall_rules (name,action,src_address_object_id,dst_address_object_id) VALUES ('v6-range','drop',$1,$2)`, v6range, v6net)
|
||||||
|
|
||||||
|
// (a) v6-DNAT mit Port → dnat to [..]:port.
|
||||||
|
mustExec(`INSERT INTO firewall_nat_rules (name,kind,proto,match_dst_cidr,match_dport_start,target_addr,target_port_start) VALUES ('v6-dnat','dnat','tcp','2001:db8:9::/64',80,'2001:db8:9::2',8080)`)
|
||||||
|
// (b) v4-DNAT (Regression).
|
||||||
|
mustExec(`INSERT INTO firewall_nat_rules (name,kind,proto,match_dst_cidr,match_dport_start,target_addr,target_port_start) VALUES ('v4-dnat','dnat','tcp','1.2.3.4',80,'10.0.0.5',80)`)
|
||||||
|
// (c) gemischte Familie (v4 src, v6 target) → MUSS übersprungen werden.
|
||||||
|
mustExec(`INSERT INTO firewall_nat_rules (name,kind,proto,match_src_cidr,target_addr) VALUES ('mixed-snat','snat','any','10.0.0.0/24','2001:db8::99')`)
|
||||||
|
|
||||||
|
out, err := New(pool).RenderToString(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("render: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, w := range []string{
|
||||||
|
"ip saddr { 10.0.0.0/24 }",
|
||||||
|
"ip6 saddr { 2001:db8:1::/64 }",
|
||||||
|
"ip6 nexthdr icmpv6",
|
||||||
|
"ip6 saddr { 2001:db8:3::1-2001:db8:3::9 }",
|
||||||
|
"dnat to [2001:db8:9::2]:8080",
|
||||||
|
"dnat to 10.0.0.5:80",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(out, w) {
|
||||||
|
t.Errorf("rendered output missing %q\n----\n%s", w, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(out, "2001:db8::99") {
|
||||||
|
t.Errorf("mixed-family NAT rule was not skipped\n----\n%s", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
nft, err := exec.LookPath("nft")
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("nft not in PATH — skipping syntax check")
|
||||||
|
}
|
||||||
|
f, err := os.CreateTemp(t.TempDir(), "e2e-*.nft")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = f.WriteString(out)
|
||||||
|
f.Close()
|
||||||
|
var cmd *exec.Cmd
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
cmd = exec.Command(nft, "-c", "-f", f.Name())
|
||||||
|
} else {
|
||||||
|
cmd = exec.Command("sudo", "-n", nft, "-c", "-f", f.Name())
|
||||||
|
}
|
||||||
|
if combined, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
msg := string(combined)
|
||||||
|
if strings.Contains(msg, "Operation not permitted") || strings.Contains(msg, "password is required") {
|
||||||
|
t.Skipf("nft -c needs root (no usable sudo): %s", strings.TrimSpace(msg))
|
||||||
|
}
|
||||||
|
t.Fatalf("nft -c rejected the real-rendered ruleset: %v\n%s\n----\n%s", err, combined, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
183
internal/firewall/firewall_ipv6_test.go
Normal file
183
internal/firewall/firewall_ipv6_test.go
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
package firewall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAddrFamily(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"1.2.3.4": "ip",
|
||||||
|
"10.0.0.0/24": "ip",
|
||||||
|
"1.2.3.4-1.2.3.10": "ip",
|
||||||
|
"2001:db8::1": "ip6",
|
||||||
|
"fd00::/64": "ip6",
|
||||||
|
"2001:db8::1-2001:db8::5": "ip6",
|
||||||
|
"example.com": "",
|
||||||
|
"": "",
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := addrFamily(in); got != want {
|
||||||
|
t.Errorf("addrFamily(%q)=%q want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandFamilyLegs_splitsByFamily(t *testing.T) {
|
||||||
|
r := ResolvedRule{
|
||||||
|
ID: 1, Action: "accept",
|
||||||
|
SrcAddrs: []string{"10.0.0.0/24", "fd00::/64"},
|
||||||
|
DstAddrs: []string{"1.2.3.4", "2001:db8::1"},
|
||||||
|
}
|
||||||
|
legs := expandFamilyLegs(r, ResolvedService{}, false)
|
||||||
|
if len(legs) != 2 {
|
||||||
|
t.Fatalf("want 2 legs (v4+v6), got %d", len(legs))
|
||||||
|
}
|
||||||
|
var v4, v6 *RuleLeg
|
||||||
|
for i := range legs {
|
||||||
|
switch legs[i].L3 {
|
||||||
|
case "ip":
|
||||||
|
v4 = &legs[i]
|
||||||
|
case "ip6":
|
||||||
|
v6 = &legs[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v4 == nil || v6 == nil {
|
||||||
|
t.Fatalf("missing family leg: %+v", legs)
|
||||||
|
}
|
||||||
|
if len(v4.SrcAddrs) != 1 || v4.SrcAddrs[0] != "10.0.0.0/24" || v4.DstAddrs[0] != "1.2.3.4" {
|
||||||
|
t.Errorf("v4 leg wrong: src=%v dst=%v", v4.SrcAddrs, v4.DstAddrs)
|
||||||
|
}
|
||||||
|
if len(v6.SrcAddrs) != 1 || v6.SrcAddrs[0] != "fd00::/64" || v6.DstAddrs[0] != "2001:db8::1" {
|
||||||
|
t.Errorf("v6 leg wrong: src=%v dst=%v", v6.SrcAddrs, v6.DstAddrs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandFamilyLegs_addresslessIsAgnostic(t *testing.T) {
|
||||||
|
legs := expandFamilyLegs(ResolvedRule{ID: 2, Action: "accept"}, ResolvedService{}, false)
|
||||||
|
if len(legs) != 1 || legs[0].L3 != "" {
|
||||||
|
t.Fatalf("addressless rule must be a single agnostic leg, got %d legs L3=%q", len(legs), legs[0].L3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandFamilyLegs_oneFamilyOnly(t *testing.T) {
|
||||||
|
// src nur v4, dst nur v4 → genau eine v4-Zeile (kein leerer v6-Leg).
|
||||||
|
r := ResolvedRule{ID: 3, Action: "drop", SrcAddrs: []string{"10.0.0.0/8"}}
|
||||||
|
legs := expandFamilyLegs(r, ResolvedService{}, false)
|
||||||
|
if len(legs) != 1 || legs[0].L3 != "ip" {
|
||||||
|
t.Fatalf("v4-only rule want 1 ip leg, got %+v", legs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandFamilyLegs_icmpFamilyMatch(t *testing.T) {
|
||||||
|
r6 := ResolvedRule{ID: 4, Action: "accept", SrcAddrs: []string{"fd00::/64"}}
|
||||||
|
if legs := expandFamilyLegs(r6, ResolvedService{Proto: "icmpv6"}, true); len(legs) != 1 || legs[0].L3 != "ip6" {
|
||||||
|
t.Fatalf("icmpv6+v6 want 1 ip6 leg, got %+v", legs)
|
||||||
|
}
|
||||||
|
if legs := expandFamilyLegs(r6, ResolvedService{Proto: "icmp"}, true); len(legs) != 0 {
|
||||||
|
t.Fatalf("icmp on v6-only addrs want 0 legs, got %+v", legs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNatFamily(t *testing.T) {
|
||||||
|
if _, ok := natFamily(ResolvedNATRule{SrcCIDR: "10.0.0.0/24", TargetAddr: "2001:db8::1"}); ok {
|
||||||
|
t.Error("mixed v4/v6 NAT must be rejected (ok=false)")
|
||||||
|
}
|
||||||
|
if fam, ok := natFamily(ResolvedNATRule{TargetAddr: "2001:db8::1"}); !ok || fam != "ip6" {
|
||||||
|
t.Errorf("v6 NAT: fam=%q ok=%v want ip6/true", fam, ok)
|
||||||
|
}
|
||||||
|
if fam, ok := natFamily(ResolvedNATRule{SrcCIDR: "10.0.0.0/24"}); !ok || fam != "ip" {
|
||||||
|
t.Errorf("v4 NAT: fam=%q ok=%v want ip/true", fam, ok)
|
||||||
|
}
|
||||||
|
if fam, ok := natFamily(ResolvedNATRule{}); !ok || fam != "ip" {
|
||||||
|
t.Errorf("addressless NAT: fam=%q ok=%v want ip/true (v4 default)", fam, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderView ist ein gemischter v4/v6-View, der alle geänderten
|
||||||
|
// Template-Zweige berührt.
|
||||||
|
func renderView(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
view := &View{
|
||||||
|
PeerIPv4: []string{"10.0.0.1"},
|
||||||
|
PeerIPv6: []string{"fd00::1"},
|
||||||
|
Legs: []RuleLeg{
|
||||||
|
{RuleID: 1, Action: "accept", L3: "ip", SrcAddrs: []string{"10.0.0.0/24"}, Service: ResolvedService{Proto: "tcp", PortStart: 443}},
|
||||||
|
{RuleID: 1, Action: "accept", L3: "ip6", SrcAddrs: []string{"fd00::/64"}, Service: ResolvedService{Proto: "tcp", PortStart: 443}},
|
||||||
|
{RuleID: 2, Action: "accept", Service: ResolvedService{Proto: "icmpv6"}}, // adresslos, agnostisch
|
||||||
|
},
|
||||||
|
NATRules: []ResolvedNATRule{
|
||||||
|
{ID: 5, Kind: "dnat", L3: "ip6", DstCIDR: "2001:db8::/64", Proto: "tcp", DPortStart: 80, TargetAddr: "fd00::2", TargetHost: "[fd00::2]", TargetPortStart: 8080},
|
||||||
|
{ID: 6, Kind: "snat", L3: "ip6", SrcCIDR: "fd00::/64", TargetAddr: "2001:db8::99"},
|
||||||
|
{ID: 7, Kind: "dnat", L3: "ip", DstCIDR: "1.2.3.4", Proto: "tcp", DPortStart: 80, TargetAddr: "10.0.0.5", TargetHost: "10.0.0.5", TargetPortStart: 80},
|
||||||
|
},
|
||||||
|
WGSiteMasq: []WGSiteMasqEntry{{Iface: "wg7", VPNNet: "fd00:99::/64", L3: "ip6"}},
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := tpl.Execute(&buf, view); err != nil {
|
||||||
|
t.Fatalf("template execute: %v", err)
|
||||||
|
}
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTemplate_v6AndV4Render(t *testing.T) {
|
||||||
|
out := renderView(t)
|
||||||
|
mustContain := []string{
|
||||||
|
"ip saddr { 10.0.0.0/24 }", // v4-Regel unverändert
|
||||||
|
"ip6 saddr { fd00::/64 }", // v6-Regel
|
||||||
|
"ip6 daddr 2001:db8::/64", // v6-DNAT-Match
|
||||||
|
"dnat to [fd00::2]:8080", // v6-DNAT-Target geklammert
|
||||||
|
"dnat to 10.0.0.5:80", // v4-DNAT-Target unverändert
|
||||||
|
"ip6 saddr fd00::/64 snat to 2001:db8::99",
|
||||||
|
`oifname "wg7" ip6 saddr fd00:99::/64 masquerade`,
|
||||||
|
}
|
||||||
|
for _, w := range mustContain {
|
||||||
|
if !strings.Contains(out, w) {
|
||||||
|
t.Errorf("output missing %q\n----\n%s", w, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// v6-Adressen dürfen NIEMALS in einem ip-saddr/daddr-Set landen.
|
||||||
|
if strings.Contains(out, "ip saddr { fd00") || strings.Contains(out, "ip daddr { fd00") ||
|
||||||
|
strings.Contains(out, "ip saddr { 2001") {
|
||||||
|
t.Errorf("v6 address leaked into IPv4 match\n----\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTemplate_nftSyntax validiert das gerenderte Ruleset mit `nft -c -f`
|
||||||
|
// (Check-Modus, kein Apply). Wird übersprungen, wenn nft nicht installiert
|
||||||
|
// ist (z.B. CI ohne nft).
|
||||||
|
func TestTemplate_nftSyntax(t *testing.T) {
|
||||||
|
nft, err := exec.LookPath("nft")
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("nft binary not available — skipping syntax check")
|
||||||
|
}
|
||||||
|
out := renderView(t)
|
||||||
|
f, err := os.CreateTemp(t.TempDir(), "ruleset-*.nft")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := f.WriteString(out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f.Close()
|
||||||
|
// `nft -c` liest die Kernel-Ruleset-Cache via netlink → braucht root.
|
||||||
|
// Als nicht-root via sudo -n versuchen; klappt das nicht, skip statt fail
|
||||||
|
// (auf den Nodes rendert/prüft edgeguard ohnehin als root).
|
||||||
|
var cmd *exec.Cmd
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
cmd = exec.Command(nft, "-c", "-f", f.Name())
|
||||||
|
} else {
|
||||||
|
cmd = exec.Command("sudo", "-n", nft, "-c", "-f", f.Name())
|
||||||
|
}
|
||||||
|
combined, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
msg := string(combined)
|
||||||
|
if strings.Contains(msg, "Operation not permitted") || strings.Contains(msg, "a password is required") || strings.Contains(msg, "may not run sudo") {
|
||||||
|
t.Skipf("nft -c needs root (no usable sudo): %s", strings.TrimSpace(msg))
|
||||||
|
}
|
||||||
|
t.Fatalf("nft -c -f rejected the generated ruleset: %v\n%s\n----\n%s", err, combined, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -71,7 +71,7 @@ table inet edgeguard {
|
|||||||
die Comment-Zeile angehängt — sonst frisst nft die rule
|
die Comment-Zeile angehängt — sonst frisst nft die rule
|
||||||
als Teil des # Kommentars). */ -}}
|
als Teil des # Kommentars). */ -}}
|
||||||
{{""}}
|
{{""}}
|
||||||
{{if .SrcIfaces}}iifname { {{join .SrcIfaces ", "}} } {{end}}{{if .DstIfaces}}oifname { {{join .DstIfaces ", "}} } {{end}}{{if .SrcAddrs}}ip saddr { {{join .SrcAddrs ", "}} } {{end}}{{if .DstAddrs}}ip daddr { {{join .DstAddrs ", "}} } {{end}}{{with .Service}}{{if and (or (eq .Proto "tcp") (eq .Proto "udp")) .PortStart}}{{.Proto}} dport {{.PortStart}}{{if and .PortEnd (ne .PortEnd .PortStart)}}-{{.PortEnd}}{{end}} {{else if eq .Proto "icmp"}}ip protocol icmp {{else if eq .Proto "icmpv6"}}ip6 nexthdr icmpv6 {{end}}{{end}}{{if .Log}}log prefix "edgeguard:{{.RuleID}} " group 0 {{end}}counter {{.Action}} comment "egid:{{.RuleID}}"
|
{{if .SrcIfaces}}iifname { {{join .SrcIfaces ", "}} } {{end}}{{if .DstIfaces}}oifname { {{join .DstIfaces ", "}} } {{end}}{{if .SrcAddrs}}{{.L3}} saddr { {{join .SrcAddrs ", "}} } {{end}}{{if .DstAddrs}}{{.L3}} daddr { {{join .DstAddrs ", "}} } {{end}}{{with .Service}}{{if and (or (eq .Proto "tcp") (eq .Proto "udp")) .PortStart}}{{.Proto}} dport {{.PortStart}}{{if and .PortEnd (ne .PortEnd .PortStart)}}-{{.PortEnd}}{{end}} {{else if eq .Proto "icmp"}}ip protocol icmp {{else if eq .Proto "icmpv6"}}ip6 nexthdr icmpv6 {{end}}{{end}}{{if .Log}}log prefix "edgeguard:{{.RuleID}} " group 0 {{end}}counter {{.Action}} comment "egid:{{.RuleID}}"
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
# ── DEFAULT-DROP LOGGING ───────────────────────────────────────
|
# ── DEFAULT-DROP LOGGING ───────────────────────────────────────
|
||||||
@@ -101,7 +101,7 @@ table inet edgeguard {
|
|||||||
# nach und erlauben new-state-Pakete von dort. Return-Pakete
|
# nach und erlauben new-state-Pakete von dort. Return-Pakete
|
||||||
# gehen via ct state established schon durch.
|
# gehen via ct state established schon durch.
|
||||||
{{range .NATRules}}{{if or (eq .Kind "snat") (eq .Kind "masquerade")}}{{if .SrcCIDR}}
|
{{range .NATRules}}{{if or (eq .Kind "snat") (eq .Kind "masquerade")}}{{if .SrcCIDR}}
|
||||||
ip saddr {{.SrcCIDR}} ct state new accept comment "auto-forward for NAT rule {{.ID}}"
|
{{.L3}} saddr {{.SrcCIDR}} ct state new accept comment "auto-forward for NAT rule {{.ID}}"
|
||||||
{{end}}{{end}}{{end}}
|
{{end}}{{end}}{{end}}
|
||||||
|
|
||||||
# Auto-Forward für WireGuard-Server-Interfaces: Peer-to-Peer-
|
# Auto-Forward für WireGuard-Server-Interfaces: Peer-to-Peer-
|
||||||
@@ -128,7 +128,7 @@ table inet edgeguard {
|
|||||||
{{""}}
|
{{""}}
|
||||||
{{/* nft-Syntax: erst L3-match (ip saddr/daddr), DANN L4 (tcp/udp dport).
|
{{/* nft-Syntax: erst L3-match (ip saddr/daddr), DANN L4 (tcp/udp dport).
|
||||||
Sonst quittiert der parser '... unexpected ip' an dieser Stelle. */}}
|
Sonst quittiert der parser '... unexpected ip' an dieser Stelle. */}}
|
||||||
{{if .InIfaces}}iifname { {{join .InIfaces ", "}} } {{end}}{{if .SrcCIDR}}ip saddr {{.SrcCIDR}} {{end}}{{if .DstCIDR}}ip daddr {{.DstCIDR}} {{end}}{{if and .Proto (ne .Proto "any")}}{{.Proto}} {{else}}meta l4proto { tcp, udp } {{end}}{{if .DPortStart}}dport {{.DPortStart}}{{if and .DPortEnd (ne .DPortEnd .DPortStart)}}-{{.DPortEnd}}{{end}} {{end}}{{if .TargetAddr}}dnat to {{.TargetAddr}}{{if .TargetPortStart}}:{{.TargetPortStart}}{{if and .TargetPortEnd (ne .TargetPortEnd .TargetPortStart)}}-{{.TargetPortEnd}}{{end}}{{end}}{{end}}
|
{{if .InIfaces}}iifname { {{join .InIfaces ", "}} } {{end}}{{if .SrcCIDR}}{{.L3}} saddr {{.SrcCIDR}} {{end}}{{if .DstCIDR}}{{.L3}} daddr {{.DstCIDR}} {{end}}{{if and .Proto (ne .Proto "any")}}{{.Proto}} {{else}}meta l4proto { tcp, udp } {{end}}{{if .DPortStart}}dport {{.DPortStart}}{{if and .DPortEnd (ne .DPortEnd .DPortStart)}}-{{.DPortEnd}}{{end}} {{end}}{{if .TargetAddr}}dnat to {{.TargetHost}}{{if .TargetPortStart}}:{{.TargetPortStart}}{{if and .TargetPortEnd (ne .TargetPortEnd .TargetPortStart)}}-{{.TargetPortEnd}}{{end}}{{end}}{{end}}
|
||||||
{{end}}{{end}}
|
{{end}}{{end}}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,16 +152,16 @@ table inet edgeguard {
|
|||||||
# Masquerade schreibt die Source auf die lokale Tunnel-IP um; Return-Traffic
|
# Masquerade schreibt die Source auf die lokale Tunnel-IP um; Return-Traffic
|
||||||
# findet so den Weg zurück durch den Tunnel.
|
# findet so den Weg zurück durch den Tunnel.
|
||||||
{{range .WGSiteMasq}}
|
{{range .WGSiteMasq}}
|
||||||
oifname "{{.Iface}}" ip saddr {{.VPNNet}} masquerade comment "auto: WireGuard site-to-site masquerade {{.Iface}}"
|
oifname "{{.Iface}}" {{.L3}} saddr {{.VPNNet}} masquerade comment "auto: WireGuard site-to-site masquerade {{.Iface}}"
|
||||||
{{end}}
|
{{end}}
|
||||||
{{range .NATRules}}{{if eq .Kind "snat"}}
|
{{range .NATRules}}{{if eq .Kind "snat"}}
|
||||||
# NAT {{.ID}} (snat{{if .Comment}} — {{.Comment}}{{end}})
|
# NAT {{.ID}} (snat{{if .Comment}} — {{.Comment}}{{end}})
|
||||||
{{""}}
|
{{""}}
|
||||||
{{if .OutIfaces}}oifname { {{join .OutIfaces ", "}} } {{end}}{{if .SrcCIDR}}ip saddr {{.SrcCIDR}} {{end}}{{if .TargetAddr}}snat to {{.TargetAddr}}{{end}}
|
{{if .OutIfaces}}oifname { {{join .OutIfaces ", "}} } {{end}}{{if .SrcCIDR}}{{.L3}} saddr {{.SrcCIDR}} {{end}}{{if .TargetAddr}}snat to {{.TargetAddr}}{{end}}
|
||||||
{{end}}{{if eq .Kind "masquerade"}}
|
{{end}}{{if eq .Kind "masquerade"}}
|
||||||
# NAT {{.ID}} (masquerade{{if .Comment}} — {{.Comment}}{{end}})
|
# NAT {{.ID}} (masquerade{{if .Comment}} — {{.Comment}}{{end}})
|
||||||
{{""}}
|
{{""}}
|
||||||
{{if .OutIfaces}}oifname { {{join .OutIfaces ", "}} } {{end}}{{if .SrcCIDR}}ip saddr {{.SrcCIDR}} {{end}}masquerade
|
{{if .OutIfaces}}oifname { {{join .OutIfaces ", "}} } {{end}}{{if .SrcCIDR}}{{.L3}} saddr {{.SrcCIDR}} {{end}}masquerade
|
||||||
{{end}}{{end}}
|
{{end}}{{end}}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
349
internal/handlers/oidc.go
Normal file
349
internal/handlers/oidc.go
Normal file
@@ -0,0 +1,349 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/handlers/response"
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/audit"
|
||||||
|
oidcsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/oidc"
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/session"
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/setup"
|
||||||
|
usersvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/users"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OIDC / Keycloak SSO. Additiv zum lokalen Passwort-Login. Regeln:
|
||||||
|
// - kein Auto-Provisioning (E-Mail muss als User existieren),
|
||||||
|
// - Rolle kommt aus der DB-Row (nie aus dem Token),
|
||||||
|
// - lokaler Login + TOTP bleiben unangetastet.
|
||||||
|
//
|
||||||
|
// Flow-State (state/PKCE-verifier/nonce) liegt stateless in einem 5-min
|
||||||
|
// signierten HttpOnly-Cookie (SameSite=Lax, da der IdP-Redirect ein
|
||||||
|
// top-level cross-site GET ist). Nach Erfolg wird dieselbe Session wie
|
||||||
|
// beim lokalen Login ausgestellt (setSessionCookie + Signer).
|
||||||
|
|
||||||
|
const (
|
||||||
|
oidcFlowCookie = "edgeguard_oidc_flow"
|
||||||
|
oidcFlowTTL = 5 * time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
type OIDCHandler struct {
|
||||||
|
Repo *oidcsvc.Repo
|
||||||
|
Auth oidcsvc.Authenticator
|
||||||
|
Users *usersvc.Repo
|
||||||
|
Signer *session.Signer
|
||||||
|
Setup *setup.Store
|
||||||
|
Audit *audit.Repo
|
||||||
|
NodeID string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewOIDCHandler(repo *oidcsvc.Repo, auth oidcsvc.Authenticator, users *usersvc.Repo, signer *session.Signer, setupStore *setup.Store) *OIDCHandler {
|
||||||
|
return &OIDCHandler{Repo: repo, Auth: auth, Users: users, Signer: signer, Setup: setupStore}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OIDCHandler) WithAudit(a *audit.Repo, nodeID string) *OIDCHandler {
|
||||||
|
h.Audit = a
|
||||||
|
h.NodeID = nodeID
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterPublic mountet die unauth. Endpoints (auf v1, hinter SetupGate).
|
||||||
|
func (h *OIDCHandler) RegisterPublic(rg *gin.RouterGroup) {
|
||||||
|
g := rg.Group("/auth/oidc")
|
||||||
|
g.GET("/settings", h.PublicSettings)
|
||||||
|
g.GET("/login", h.Login)
|
||||||
|
g.GET("/callback", h.Callback)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterAdmin mountet die Admin-Endpoints (auf authed: requireAuth +
|
||||||
|
// RequireAdminForMutations → GET für alle, PUT nur admin).
|
||||||
|
func (h *OIDCHandler) RegisterAdmin(rg *gin.RouterGroup) {
|
||||||
|
g := rg.Group("/oidc")
|
||||||
|
g.GET("/settings", h.GetSettings)
|
||||||
|
g.PUT("/settings", h.UpdateSettings)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublicSettings: nur, was die Login-Seite braucht.
|
||||||
|
func (h *OIDCHandler) PublicSettings(c *gin.Context) {
|
||||||
|
s, err := h.Repo.Get(c.Request.Context())
|
||||||
|
if err != nil {
|
||||||
|
// Kein Datensatz/kein DB → SSO einfach „aus".
|
||||||
|
response.OK(c, gin.H{"enabled": false, "button_label": ""})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.OK(c, gin.H{"enabled": s.Enabled, "button_label": s.ButtonLabel})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSettings: Admin-Sicht ohne Secret, mit secret_configured + redirect_uri.
|
||||||
|
func (h *OIDCHandler) GetSettings(c *gin.Context) {
|
||||||
|
s, err := h.Repo.Get(c.Request.Context())
|
||||||
|
if err != nil {
|
||||||
|
response.Internal(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hasSecret, _ := h.Repo.HasSecret(c.Request.Context())
|
||||||
|
response.OK(c, gin.H{
|
||||||
|
"enabled": s.Enabled,
|
||||||
|
"issuer_url": s.IssuerURL,
|
||||||
|
"client_id": s.ClientID,
|
||||||
|
"scopes": s.Scopes,
|
||||||
|
"email_claim": s.EmailClaim,
|
||||||
|
"button_label": s.ButtonLabel,
|
||||||
|
"secret_configured": hasSecret,
|
||||||
|
"redirect_uri": h.redirectURI(c),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type oidcUpdateBody struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
IssuerURL string `json:"issuer_url"`
|
||||||
|
ClientID string `json:"client_id"`
|
||||||
|
ClientSecret *string `json:"client_secret"` // nil = unverändert, "" = löschen
|
||||||
|
Scopes string `json:"scopes"`
|
||||||
|
EmailClaim string `json:"email_claim"`
|
||||||
|
ButtonLabel string `json:"button_label"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSettings: PUT (admin via RequireAdminForMutations).
|
||||||
|
func (h *OIDCHandler) UpdateSettings(c *gin.Context) {
|
||||||
|
var body oidcUpdateBody
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
response.BadRequest(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body.IssuerURL = strings.TrimSpace(body.IssuerURL)
|
||||||
|
body.ClientID = strings.TrimSpace(body.ClientID)
|
||||||
|
if body.Scopes == "" {
|
||||||
|
body.Scopes = "openid email profile"
|
||||||
|
}
|
||||||
|
if body.EmailClaim == "" {
|
||||||
|
body.EmailClaim = "email"
|
||||||
|
}
|
||||||
|
if body.ButtonLabel == "" {
|
||||||
|
body.ButtonLabel = "Sign in with SSO"
|
||||||
|
}
|
||||||
|
|
||||||
|
if body.Enabled {
|
||||||
|
if body.IssuerURL == "" || body.ClientID == "" {
|
||||||
|
response.BadRequest(c, errors.New("issuer_url und client_id sind erforderlich, wenn OIDC aktiviert ist"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if u, err := url.Parse(body.IssuerURL); err != nil || u.Scheme != "https" || u.Host == "" {
|
||||||
|
response.BadRequest(c, errors.New("issuer_url muss eine gültige https-URL sein"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hasSecret, _ := h.Repo.HasSecret(c.Request.Context())
|
||||||
|
providing := body.ClientSecret != nil && *body.ClientSecret != ""
|
||||||
|
if !hasSecret && !providing {
|
||||||
|
response.BadRequest(c, errors.New("client_secret ist erforderlich (noch keins gespeichert)"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.Repo.Update(c.Request.Context(), oidcsvc.UpdateInput{
|
||||||
|
Enabled: body.Enabled,
|
||||||
|
IssuerURL: body.IssuerURL,
|
||||||
|
ClientID: body.ClientID,
|
||||||
|
Scopes: body.Scopes,
|
||||||
|
EmailClaim: body.EmailClaim,
|
||||||
|
ButtonLabel: body.ButtonLabel,
|
||||||
|
ClientSecret: body.ClientSecret,
|
||||||
|
}); err != nil {
|
||||||
|
response.Internal(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.audit(c, actorOf(c), "oidc.settings.updated", actorOf(c),
|
||||||
|
gin.H{"enabled": body.Enabled, "issuer": body.IssuerURL})
|
||||||
|
response.OK(c, gin.H{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login: 302 zum IdP. Setzt das signierte Flow-Cookie.
|
||||||
|
func (h *OIDCHandler) Login(c *gin.Context) {
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
s, err := h.Repo.Get(ctx)
|
||||||
|
if err != nil || !s.Enabled {
|
||||||
|
h.fail(c, "disabled")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state, err1 := randToken(24)
|
||||||
|
nonce, err2 := randToken(24)
|
||||||
|
if err1 != nil || err2 != nil {
|
||||||
|
h.fail(c, "server")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
verifier := oauth2.GenerateVerifier()
|
||||||
|
redirectURI := h.redirectURI(c)
|
||||||
|
|
||||||
|
authURL, err := h.Auth.AuthCodeURL(ctx, redirectURI, state, nonce, verifier)
|
||||||
|
if err != nil {
|
||||||
|
h.fail(c, "config")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
blob, _ := json.Marshal(oidcFlow{State: state, Verifier: verifier, Nonce: nonce})
|
||||||
|
signed, err := h.Signer.SignBlob(blob, oidcFlowTTL)
|
||||||
|
if err != nil {
|
||||||
|
h.fail(c, "server")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.setFlowCookie(c, signed)
|
||||||
|
c.Redirect(http.StatusFound, authURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Callback: verifiziert Flow + Token, mappt auf DB-User, stellt Session aus.
|
||||||
|
func (h *OIDCHandler) Callback(c *gin.Context) {
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
|
// Flow-Cookie lesen + sofort entwerten (single-use).
|
||||||
|
rawFlow, _ := c.Cookie(oidcFlowCookie)
|
||||||
|
h.clearFlowCookie(c)
|
||||||
|
if rawFlow == "" {
|
||||||
|
h.fail(c, "expired")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload, err := h.Signer.VerifyBlob(rawFlow)
|
||||||
|
if err != nil {
|
||||||
|
h.fail(c, "expired")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var flow oidcFlow
|
||||||
|
if json.Unmarshal(payload, &flow) != nil {
|
||||||
|
h.fail(c, "expired")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.Query("error") != "" {
|
||||||
|
h.fail(c, "denied")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if subtle.ConstantTimeCompare([]byte(c.Query("state")), []byte(flow.State)) != 1 {
|
||||||
|
h.fail(c, "state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := c.Query("code")
|
||||||
|
if code == "" {
|
||||||
|
h.fail(c, "exchange")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
claims, err := h.Auth.Exchange(ctx, h.redirectURI(c), code, flow.Verifier)
|
||||||
|
if err != nil {
|
||||||
|
h.fail(c, "token")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(flow.Nonce)) != 1 {
|
||||||
|
h.fail(c, "nonce")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !claims.EmailVerified || claims.Email == "" {
|
||||||
|
h.audit(c, claims.Email, "auth.login.failed", claims.Email,
|
||||||
|
gin.H{"via": "oidc", "reason": "email_unverified", "remote": c.ClientIP()})
|
||||||
|
h.fail(c, "unverified")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
u, _, err := h.Users.FindByEmail(ctx, claims.Email)
|
||||||
|
if err != nil {
|
||||||
|
reason := "oidc_no_account"
|
||||||
|
if !errors.Is(err, usersvc.ErrNotFound) {
|
||||||
|
reason = "server"
|
||||||
|
}
|
||||||
|
h.audit(c, claims.Email, "auth.login.failed", claims.Email,
|
||||||
|
gin.H{"via": "oidc", "reason": reason, "remote": c.ClientIP()})
|
||||||
|
h.fail(c, map[bool]string{true: "no_account", false: "server"}[reason == "oidc_no_account"])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !u.Active {
|
||||||
|
h.audit(c, u.Email, "auth.login.failed", u.Email,
|
||||||
|
gin.H{"via": "oidc", "reason": "account_disabled", "remote": c.ClientIP()})
|
||||||
|
h.fail(c, "disabled")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opportunistisches sub-Linking + Schutz gegen E-Mail-Reassignment.
|
||||||
|
if stored, err := h.Users.GetOIDCSubject(ctx, u.ID); err == nil {
|
||||||
|
if stored != "" && stored != claims.Subject {
|
||||||
|
h.audit(c, u.Email, "auth.login.failed", u.Email,
|
||||||
|
gin.H{"via": "oidc", "reason": "subject_mismatch", "remote": c.ClientIP()})
|
||||||
|
h.fail(c, "subject_mismatch")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if stored == "" {
|
||||||
|
_ = h.Users.SetOIDCSubject(ctx, u.ID, claims.Subject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Users.RecordLogin(ctx, u.ID)
|
||||||
|
|
||||||
|
// Rolle STRIKT aus der DB-Row (nie aus Claims).
|
||||||
|
raw, tok, err := h.Signer.IssueWithRole(u.Email, u.Role)
|
||||||
|
if err != nil {
|
||||||
|
h.fail(c, "server")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setSessionCookie(c, raw, tok.Exp)
|
||||||
|
h.audit(c, u.Email, "auth.login.success", u.Email,
|
||||||
|
gin.H{"via": "oidc", "role": u.Role, "remote": c.ClientIP()})
|
||||||
|
c.Redirect(http.StatusFound, "/dashboard")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type oidcFlow struct {
|
||||||
|
State string `json:"s"`
|
||||||
|
Verifier string `json:"v"`
|
||||||
|
Nonce string `json:"n"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// redirectURI = https://<FQDN>/api/v1/auth/oidc/callback (FQDN aus setup.json,
|
||||||
|
// Fallback Request-Host). Muss im IdP als Redirect-URI registriert sein.
|
||||||
|
func (h *OIDCHandler) redirectURI(c *gin.Context) string {
|
||||||
|
host := ""
|
||||||
|
if h.Setup != nil {
|
||||||
|
if st, err := h.Setup.Load(); err == nil && st != nil {
|
||||||
|
host = strings.TrimSpace(st.FQDN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if host == "" {
|
||||||
|
host = c.Request.Host
|
||||||
|
}
|
||||||
|
return "https://" + host + "/api/v1/auth/oidc/callback"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OIDCHandler) fail(c *gin.Context, reason string) {
|
||||||
|
c.Redirect(http.StatusFound, "/login?sso_error="+url.QueryEscape(reason))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OIDCHandler) audit(c *gin.Context, actor, action, subject string, detail any) {
|
||||||
|
if h.Audit != nil {
|
||||||
|
_ = h.Audit.Log(c.Request.Context(), actor, action, subject, detail, h.NodeID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OIDCHandler) setFlowCookie(c *gin.Context, raw string) {
|
||||||
|
c.SetSameSite(http.SameSiteLaxMode)
|
||||||
|
c.SetCookie(oidcFlowCookie, raw, int(oidcFlowTTL.Seconds()), "/", "", true, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OIDCHandler) clearFlowCookie(c *gin.Context) {
|
||||||
|
c.SetSameSite(http.SameSiteLaxMode)
|
||||||
|
c.SetCookie(oidcFlowCookie, "", -1, "/", "", true, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func randToken(n int) (string, error) {
|
||||||
|
b := make([]byte, n)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||||
|
}
|
||||||
202
internal/handlers/oidc_test.go
Normal file
202
internal/handlers/oidc_test.go
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
||||||
|
oidcsvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/oidc"
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/session"
|
||||||
|
usersvc "git.netcell-it.de/projekte/edgeguard-native/internal/services/users"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mockAuth erfüllt oidcsvc.Authenticator und liefert vorgegebene Claims —
|
||||||
|
// kein echter IdP nötig.
|
||||||
|
type mockAuth struct {
|
||||||
|
claims *oidcsvc.Claims
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockAuth) AuthCodeURL(_ context.Context, _, state, _, _ string) (string, error) {
|
||||||
|
return "https://idp.example/authorize?state=" + state, nil
|
||||||
|
}
|
||||||
|
func (m *mockAuth) Exchange(_ context.Context, _, _, _ string) (*oidcsvc.Claims, error) {
|
||||||
|
return m.claims, m.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func oidcTestSetup(t *testing.T) (*usersvc.Repo, *pgxpool.Pool, *session.Signer) {
|
||||||
|
t.Helper()
|
||||||
|
dsn := os.Getenv("EG_FWTEST_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set EG_FWTEST_DSN to run the oidc handler test")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
// Retry: goose-Erst-Apply ist nicht concurrency-safe, wenn mehrere
|
||||||
|
// guarded Test-Pakete dieselbe frische DB parallel migrieren.
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
return usersvc.New(pool), pool, session.NewSigner([]byte("0123456789abcdef0123456789abcdef"), nil, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedUser(t *testing.T, repo *usersvc.Repo, pool *pgxpool.Pool, email, role string, active bool) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
_, _ = pool.Exec(ctx, `DELETE FROM users WHERE email=$1`, email)
|
||||||
|
if _, err := repo.Create(ctx, email, "Sup3rSecret-pw-123", role, active); err != nil {
|
||||||
|
t.Fatalf("seed user: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCallback(t *testing.T, h *OIDCHandler, flow oidcFlow, queryState, code string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(rec)
|
||||||
|
blob, _ := json.Marshal(flow)
|
||||||
|
signed, err := h.Signer.SignBlob(blob, oidcFlowTTL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodGet,
|
||||||
|
"/api/v1/auth/oidc/callback?state="+queryState+"&code="+code, nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: oidcFlowCookie, Value: signed})
|
||||||
|
c.Request = req
|
||||||
|
h.Callback(c)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func sessionCookie(rec *httptest.ResponseRecorder) string {
|
||||||
|
for _, ck := range rec.Result().Cookies() {
|
||||||
|
if ck.Name == cookieName && ck.Value != "" && ck.MaxAge >= 0 {
|
||||||
|
return ck.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallback_KnownActiveUser_RoleFromDB(t *testing.T) {
|
||||||
|
users, pool, signer := oidcTestSetup(t)
|
||||||
|
seedUser(t, users, pool, "sso-viewer@test.local", "viewer", true)
|
||||||
|
|
||||||
|
h := NewOIDCHandler(nil, &mockAuth{claims: &oidcsvc.Claims{
|
||||||
|
Email: "sso-viewer@test.local", EmailVerified: true, Subject: "sub-1", Nonce: "N",
|
||||||
|
}}, users, signer, nil)
|
||||||
|
|
||||||
|
rec := runCallback(t, h, oidcFlow{State: "S", Verifier: "v", Nonce: "N"}, "S", "code")
|
||||||
|
|
||||||
|
if loc := rec.Header().Get("Location"); loc != "/dashboard" {
|
||||||
|
t.Fatalf("expected redirect to /dashboard, got %q (body proves failure path)", loc)
|
||||||
|
}
|
||||||
|
raw := sessionCookie(rec)
|
||||||
|
if raw == "" {
|
||||||
|
t.Fatal("expected a session cookie to be set")
|
||||||
|
}
|
||||||
|
tok, err := signer.Verify(raw)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("session token invalid: %v", err)
|
||||||
|
}
|
||||||
|
// Kernbeweis: Rolle kommt aus der DB-Row (viewer), nicht aus Claims.
|
||||||
|
if tok.Role != "viewer" {
|
||||||
|
t.Errorf("token role = %q, want viewer (role must come from DB)", tok.Role)
|
||||||
|
}
|
||||||
|
if tok.Actor != "sso-viewer@test.local" {
|
||||||
|
t.Errorf("token actor = %q", tok.Actor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallback_UnknownEmail_Rejected(t *testing.T) {
|
||||||
|
users, pool, signer := oidcTestSetup(t)
|
||||||
|
_, _ = pool.Exec(context.Background(), `DELETE FROM users WHERE email=$1`, "ghost@test.local")
|
||||||
|
|
||||||
|
h := NewOIDCHandler(nil, &mockAuth{claims: &oidcsvc.Claims{
|
||||||
|
Email: "ghost@test.local", EmailVerified: true, Subject: "x", Nonce: "N",
|
||||||
|
}}, users, signer, nil)
|
||||||
|
|
||||||
|
rec := runCallback(t, h, oidcFlow{State: "S", Nonce: "N"}, "S", "code")
|
||||||
|
if !strings.Contains(rec.Header().Get("Location"), "sso_error=no_account") {
|
||||||
|
t.Fatalf("expected sso_error=no_account, got %q", rec.Header().Get("Location"))
|
||||||
|
}
|
||||||
|
if sessionCookie(rec) != "" {
|
||||||
|
t.Fatal("no session cookie expected for unknown user")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallback_InactiveUser_Rejected(t *testing.T) {
|
||||||
|
users, pool, signer := oidcTestSetup(t)
|
||||||
|
seedUser(t, users, pool, "sso-disabled@test.local", "admin", false)
|
||||||
|
|
||||||
|
h := NewOIDCHandler(nil, &mockAuth{claims: &oidcsvc.Claims{
|
||||||
|
Email: "sso-disabled@test.local", EmailVerified: true, Subject: "x", Nonce: "N",
|
||||||
|
}}, users, signer, nil)
|
||||||
|
|
||||||
|
rec := runCallback(t, h, oidcFlow{State: "S", Nonce: "N"}, "S", "code")
|
||||||
|
if !strings.Contains(rec.Header().Get("Location"), "sso_error=disabled") {
|
||||||
|
t.Fatalf("expected sso_error=disabled, got %q", rec.Header().Get("Location"))
|
||||||
|
}
|
||||||
|
if sessionCookie(rec) != "" {
|
||||||
|
t.Fatal("no session cookie expected for inactive user")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallback_EmailUnverified_Rejected(t *testing.T) {
|
||||||
|
users, pool, signer := oidcTestSetup(t)
|
||||||
|
seedUser(t, users, pool, "sso-unverified@test.local", "admin", true)
|
||||||
|
|
||||||
|
h := NewOIDCHandler(nil, &mockAuth{claims: &oidcsvc.Claims{
|
||||||
|
Email: "sso-unverified@test.local", EmailVerified: false, Subject: "x", Nonce: "N",
|
||||||
|
}}, users, signer, nil)
|
||||||
|
|
||||||
|
rec := runCallback(t, h, oidcFlow{State: "S", Nonce: "N"}, "S", "code")
|
||||||
|
if !strings.Contains(rec.Header().Get("Location"), "sso_error=unverified") {
|
||||||
|
t.Fatalf("expected sso_error=unverified, got %q", rec.Header().Get("Location"))
|
||||||
|
}
|
||||||
|
if sessionCookie(rec) != "" {
|
||||||
|
t.Fatal("no session cookie expected for unverified email")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallback_NonceMismatch_Rejected(t *testing.T) {
|
||||||
|
users, pool, signer := oidcTestSetup(t)
|
||||||
|
seedUser(t, users, pool, "sso-nonce@test.local", "admin", true)
|
||||||
|
|
||||||
|
h := NewOIDCHandler(nil, &mockAuth{claims: &oidcsvc.Claims{
|
||||||
|
Email: "sso-nonce@test.local", EmailVerified: true, Subject: "x", Nonce: "WRONG",
|
||||||
|
}}, users, signer, nil)
|
||||||
|
|
||||||
|
rec := runCallback(t, h, oidcFlow{State: "S", Nonce: "N"}, "S", "code")
|
||||||
|
if !strings.Contains(rec.Header().Get("Location"), "sso_error=nonce") {
|
||||||
|
t.Fatalf("expected sso_error=nonce, got %q", rec.Header().Get("Location"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallback_StateMismatch_Rejected(t *testing.T) {
|
||||||
|
users, _, signer := oidcTestSetup(t)
|
||||||
|
h := NewOIDCHandler(nil, &mockAuth{claims: &oidcsvc.Claims{}}, users, signer, nil)
|
||||||
|
|
||||||
|
rec := runCallback(t, h, oidcFlow{State: "S", Nonce: "N"}, "WRONG", "code")
|
||||||
|
if !strings.Contains(rec.Header().Get("Location"), "sso_error=state") {
|
||||||
|
t.Fatalf("expected sso_error=state, got %q", rec.Header().Get("Location"))
|
||||||
|
}
|
||||||
|
}
|
||||||
21
internal/models/oidc_settings.go
Normal file
21
internal/models/oidc_settings.go
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// OIDCSettings ist die Singleton-Konfiguration für OIDC/Keycloak-SSO.
|
||||||
|
// ClientSecretEnc trägt den verschlüsselten Client-Secret (secrets.Box)
|
||||||
|
// und wird NIE serialisiert (json:"-").
|
||||||
|
type OIDCSettings struct {
|
||||||
|
ID int `gorm:"column:id;primaryKey" json:"id"`
|
||||||
|
Enabled bool `gorm:"column:enabled" json:"enabled"`
|
||||||
|
IssuerURL string `gorm:"column:issuer_url" json:"issuer_url"`
|
||||||
|
ClientID string `gorm:"column:client_id" json:"client_id"`
|
||||||
|
ClientSecretEnc []byte `gorm:"column:client_secret_enc" json:"-"`
|
||||||
|
Scopes string `gorm:"column:scopes" json:"scopes"`
|
||||||
|
EmailClaim string `gorm:"column:email_claim" json:"email_claim"`
|
||||||
|
ButtonLabel string `gorm:"column:button_label" json:"button_label"`
|
||||||
|
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||||
|
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (OIDCSettings) TableName() string { return "oidc_settings" }
|
||||||
181
internal/services/oidc/client.go
Normal file
181
internal/services/oidc/client.go
Normal file
@@ -0,0 +1,181 @@
|
|||||||
|
package oidc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
gooidc "github.com/coreos/go-oidc/v3/oidc"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Claims sind die aus dem ID-Token extrahierten Felder, die der Login-
|
||||||
|
// Flow braucht. Bewusst minimal — Rolle kommt NIE aus dem Token.
|
||||||
|
type Claims struct {
|
||||||
|
Subject string
|
||||||
|
Email string
|
||||||
|
EmailVerified bool
|
||||||
|
Nonce string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticator ist der testbare Seam: Aufbau der Auth-URL und der
|
||||||
|
// Code-Exchange inkl. ID-Token-Verifikation + Claim-Extraktion. Der
|
||||||
|
// Handler hängt nur hieran, sodass Tests einen Fake injizieren können.
|
||||||
|
type Authenticator interface {
|
||||||
|
// AuthCodeURL baut die Redirect-URL zum IdP (state + nonce + PKCE-Challenge).
|
||||||
|
AuthCodeURL(ctx context.Context, redirectURI, state, nonce, pkceVerifier string) (string, error)
|
||||||
|
// Exchange tauscht den Code (PKCE), verifiziert das ID-Token und gibt
|
||||||
|
// die Claims zurück. Prüft Issuer/Audience/Signatur/Expiry.
|
||||||
|
Exchange(ctx context.Context, redirectURI, code, pkceVerifier string) (*Claims, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client implementiert Authenticator gegen einen echten OIDC-Provider.
|
||||||
|
// Provider+Verifier werden lazy aufgebaut und gecached; bei geänderten
|
||||||
|
// Settings (Fingerprint) neu aufgebaut.
|
||||||
|
type Client struct {
|
||||||
|
repo *Repo
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
cacheKey string
|
||||||
|
provider *gooidc.Provider
|
||||||
|
verifier *gooidc.IDTokenVerifier
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewClient(repo *Repo) *Client { return &Client{repo: repo} }
|
||||||
|
|
||||||
|
// loaded baut (oder reused) Provider+Verifier aus den aktuellen Settings.
|
||||||
|
// Cache-Key = Fingerprint(issuer, client_id, scopes); Rebuild bei Änderung.
|
||||||
|
func (c *Client) loaded(ctx context.Context) (*gooidc.Provider, *gooidc.IDTokenVerifier, error) {
|
||||||
|
s, err := c.repo.Get(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if !s.Enabled {
|
||||||
|
return nil, nil, ErrDisabled
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(s.IssuerURL) == "" || strings.TrimSpace(s.ClientID) == "" {
|
||||||
|
return nil, nil, fmt.Errorf("oidc: issuer_url and client_id required")
|
||||||
|
}
|
||||||
|
key := fingerprint(s.IssuerURL, s.ClientID, s.Scopes)
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if c.provider == nil || c.cacheKey != key {
|
||||||
|
prov, err := gooidc.NewProvider(ctx, s.IssuerURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("oidc: discovery: %w", err)
|
||||||
|
}
|
||||||
|
c.provider = prov
|
||||||
|
c.verifier = prov.Verifier(&gooidc.Config{ClientID: s.ClientID})
|
||||||
|
c.cacheKey = key
|
||||||
|
}
|
||||||
|
return c.provider, c.verifier, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) oauthConfig(prov *gooidc.Provider, clientID, secret, redirectURI, scopes string) oauth2.Config {
|
||||||
|
return oauth2.Config{
|
||||||
|
ClientID: clientID,
|
||||||
|
ClientSecret: secret,
|
||||||
|
Endpoint: prov.Endpoint(),
|
||||||
|
RedirectURL: redirectURI,
|
||||||
|
Scopes: splitScopes(scopes),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthCodeURL implementiert Authenticator.
|
||||||
|
func (c *Client) AuthCodeURL(ctx context.Context, redirectURI, state, nonce, pkceVerifier string) (string, error) {
|
||||||
|
s, err := c.repo.Get(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
prov, _, err := c.loaded(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
secret, _ := c.repo.ClientSecret(ctx)
|
||||||
|
cfg := c.oauthConfig(prov, s.ClientID, secret, redirectURI, s.Scopes)
|
||||||
|
return cfg.AuthCodeURL(state,
|
||||||
|
gooidc.Nonce(nonce),
|
||||||
|
oauth2.S256ChallengeOption(pkceVerifier),
|
||||||
|
), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange implementiert Authenticator.
|
||||||
|
func (c *Client) Exchange(ctx context.Context, redirectURI, code, pkceVerifier string) (*Claims, error) {
|
||||||
|
s, err := c.repo.Get(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
prov, verifier, err := c.loaded(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
secret, _ := c.repo.ClientSecret(ctx)
|
||||||
|
cfg := c.oauthConfig(prov, s.ClientID, secret, redirectURI, s.Scopes)
|
||||||
|
|
||||||
|
tok, err := cfg.Exchange(ctx, code, oauth2.VerifierOption(pkceVerifier))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("oidc: code exchange: %w", err)
|
||||||
|
}
|
||||||
|
rawID, ok := tok.Extra("id_token").(string)
|
||||||
|
if !ok || rawID == "" {
|
||||||
|
return nil, errors.New("oidc: no id_token in response")
|
||||||
|
}
|
||||||
|
idToken, err := verifier.Verify(ctx, rawID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("oidc: id_token verify: %w", err)
|
||||||
|
}
|
||||||
|
return extractClaims(idToken, s.EmailClaim)
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractClaims liest E-Mail (via konfigurierbarem Claim), email_verified,
|
||||||
|
// sub und nonce aus dem verifizierten ID-Token.
|
||||||
|
func extractClaims(idToken *gooidc.IDToken, emailClaim string) (*Claims, error) {
|
||||||
|
var raw map[string]any
|
||||||
|
if err := idToken.Claims(&raw); err != nil {
|
||||||
|
return nil, fmt.Errorf("oidc: decode claims: %w", err)
|
||||||
|
}
|
||||||
|
if emailClaim == "" {
|
||||||
|
emailClaim = "email"
|
||||||
|
}
|
||||||
|
out := &Claims{Subject: idToken.Subject}
|
||||||
|
if v, ok := raw[emailClaim].(string); ok {
|
||||||
|
out.Email = strings.TrimSpace(strings.ToLower(v))
|
||||||
|
}
|
||||||
|
// email_verified kann bool oder "true"/"false" sein.
|
||||||
|
switch ev := raw["email_verified"].(type) {
|
||||||
|
case bool:
|
||||||
|
out.EmailVerified = ev
|
||||||
|
case string:
|
||||||
|
out.EmailVerified = ev == "true"
|
||||||
|
}
|
||||||
|
if n, ok := raw["nonce"].(string); ok {
|
||||||
|
out.Nonce = n
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitScopes(s string) []string {
|
||||||
|
out := []string{}
|
||||||
|
for _, p := range strings.Fields(s) {
|
||||||
|
if p != "" {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
out = []string{gooidc.ScopeOpenID, "email", "profile"}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func fingerprint(parts ...string) string {
|
||||||
|
h := sha256.New()
|
||||||
|
for _, p := range parts {
|
||||||
|
h.Write([]byte(p))
|
||||||
|
h.Write([]byte{0})
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
111
internal/services/oidc/settings.go
Normal file
111
internal/services/oidc/settings.go
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
// Package oidc kapselt die OIDC/Keycloak-SSO-Konfiguration (Singleton-
|
||||||
|
// Settings + verschlüsseltes Client-Secret) und einen lazy aufgebauten
|
||||||
|
// OIDC-Provider/Verifier. Login-Flow-State ist stateless (signiertes
|
||||||
|
// Cookie im Handler), daher hält dieses Paket keinen Request-State.
|
||||||
|
package oidc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/models"
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/secrets"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrDisabled signalisiert, dass OIDC nicht aktiviert/konfiguriert ist.
|
||||||
|
var ErrDisabled = errors.New("oidc: not enabled")
|
||||||
|
|
||||||
|
// Repo liest/schreibt die oidc_settings-Singleton-Row und ver-/entschlüsselt
|
||||||
|
// das Client-Secret via secrets.Box.
|
||||||
|
type Repo struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
box *secrets.Box
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(pool *pgxpool.Pool, box *secrets.Box) *Repo {
|
||||||
|
return &Repo{pool: pool, box: box}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get liefert die Settings (client_secret_enc als Bytes, NULL → nil).
|
||||||
|
func (r *Repo) Get(ctx context.Context) (*models.OIDCSettings, error) {
|
||||||
|
var s models.OIDCSettings
|
||||||
|
if err := r.pool.QueryRow(ctx, `
|
||||||
|
SELECT id, enabled, issuer_url, client_id, client_secret_enc,
|
||||||
|
scopes, email_claim, button_label, created_at, updated_at
|
||||||
|
FROM oidc_settings WHERE id = 1`).Scan(
|
||||||
|
&s.ID, &s.Enabled, &s.IssuerURL, &s.ClientID, &s.ClientSecretEnc,
|
||||||
|
&s.Scopes, &s.EmailClaim, &s.ButtonLabel, &s.CreatedAt, &s.UpdatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientSecret entschlüsselt das gespeicherte Client-Secret ("" wenn keins).
|
||||||
|
func (r *Repo) ClientSecret(ctx context.Context) (string, error) {
|
||||||
|
s, err := r.Get(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(s.ClientSecretEnc) == 0 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
pt, err := r.box.Open(s.ClientSecretEnc)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(pt), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasSecret meldet, ob ein Client-Secret hinterlegt ist (für die Admin-UI,
|
||||||
|
// ohne das Secret selbst preiszugeben).
|
||||||
|
func (r *Repo) HasSecret(ctx context.Context) (bool, error) {
|
||||||
|
var present bool
|
||||||
|
err := r.pool.QueryRow(ctx,
|
||||||
|
`SELECT client_secret_enc IS NOT NULL FROM oidc_settings WHERE id = 1`).Scan(&present)
|
||||||
|
return present, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateInput beschreibt eine Settings-Änderung. ClientSecret nutzt
|
||||||
|
// write-only-Semantik: nil = unverändert, "" = löschen, sonst neu sealen.
|
||||||
|
type UpdateInput struct {
|
||||||
|
Enabled bool
|
||||||
|
IssuerURL string
|
||||||
|
ClientID string
|
||||||
|
Scopes string
|
||||||
|
EmailClaim string
|
||||||
|
ButtonLabel string
|
||||||
|
ClientSecret *string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update schreibt die Settings. Das Secret wird nur angefasst, wenn
|
||||||
|
// ClientSecret != nil.
|
||||||
|
func (r *Repo) Update(ctx context.Context, in UpdateInput) error {
|
||||||
|
if in.ClientSecret == nil {
|
||||||
|
_, err := r.pool.Exec(ctx, `
|
||||||
|
UPDATE oidc_settings
|
||||||
|
SET enabled=$1, issuer_url=$2, client_id=$3, scopes=$4,
|
||||||
|
email_claim=$5, button_label=$6, updated_at=NOW()
|
||||||
|
WHERE id=1`,
|
||||||
|
in.Enabled, in.IssuerURL, in.ClientID, in.Scopes, in.EmailClaim, in.ButtonLabel)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var enc []byte
|
||||||
|
if *in.ClientSecret != "" {
|
||||||
|
sealed, err := r.box.Seal([]byte(*in.ClientSecret))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
enc = sealed
|
||||||
|
}
|
||||||
|
_, err := r.pool.Exec(ctx, `
|
||||||
|
UPDATE oidc_settings
|
||||||
|
SET enabled=$1, issuer_url=$2, client_id=$3, scopes=$4,
|
||||||
|
email_claim=$5, button_label=$6, client_secret_enc=$7, updated_at=NOW()
|
||||||
|
WHERE id=1`,
|
||||||
|
in.Enabled, in.IssuerURL, in.ClientID, in.Scopes, in.EmailClaim, in.ButtonLabel, enc)
|
||||||
|
return err
|
||||||
|
}
|
||||||
90
internal/services/oidc/settings_test.go
Normal file
90
internal/services/oidc/settings_test.go
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
package oidc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
||||||
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/secrets"
|
||||||
|
)
|
||||||
|
|
||||||
|
// migrateRetry umgeht die goose-Erst-Apply-Race, wenn mehrere guarded
|
||||||
|
// Test-Pakete dieselbe frische DB parallel migrieren.
|
||||||
|
func migrateRetry(ctx context.Context, dsn string) error {
|
||||||
|
var err error
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if err = database.Migrate(ctx, dsn); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
time.Sleep(700 * time.Millisecond)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Guarded integration test: set EG_FWTEST_DSN (sonst skip).
|
||||||
|
func testRepo(t *testing.T) *Repo {
|
||||||
|
t.Helper()
|
||||||
|
dsn := os.Getenv("EG_FWTEST_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set EG_FWTEST_DSN to run the oidc settings test")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := migrateRetry(ctx, dsn); err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
pool, err := database.Open(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
box := secrets.New(t.TempDir() + "/master_key")
|
||||||
|
// Settings auf einen sauberen Default zurücksetzen.
|
||||||
|
if _, err := pool.Exec(ctx, `UPDATE oidc_settings SET enabled=false, issuer_url='', client_id='', client_secret_enc=NULL WHERE id=1`); err != nil {
|
||||||
|
t.Fatalf("reset: %v", err)
|
||||||
|
}
|
||||||
|
return New(pool, box)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSettings_SecretWriteOnly(t *testing.T) {
|
||||||
|
r := testRepo(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
str := func(s string) *string { return &s }
|
||||||
|
|
||||||
|
// 1) Neues Secret setzen.
|
||||||
|
if err := r.Update(ctx, UpdateInput{Enabled: true, IssuerURL: "https://idp.example/realms/x", ClientID: "eg", ClientSecret: str("s3cr3t")}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if has, _ := r.HasSecret(ctx); !has {
|
||||||
|
t.Fatal("HasSecret should be true after setting a secret")
|
||||||
|
}
|
||||||
|
got, err := r.ClientSecret(ctx)
|
||||||
|
if err != nil || got != "s3cr3t" {
|
||||||
|
t.Fatalf("ClientSecret = %q, %v; want s3cr3t", got, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Update mit nil → Secret bleibt unverändert.
|
||||||
|
if err := r.Update(ctx, UpdateInput{Enabled: true, IssuerURL: "https://idp.example/realms/x", ClientID: "eg2", ClientSecret: nil}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, _ = r.ClientSecret(ctx)
|
||||||
|
if got != "s3cr3t" {
|
||||||
|
t.Fatalf("secret should be preserved on nil update, got %q", got)
|
||||||
|
}
|
||||||
|
if s, _ := r.Get(ctx); s.ClientID != "eg2" {
|
||||||
|
t.Fatalf("client_id should update to eg2, got %q", s.ClientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) Update mit "" → Secret gelöscht.
|
||||||
|
if err := r.Update(ctx, UpdateInput{Enabled: false, IssuerURL: "", ClientID: "", ClientSecret: str("")}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if has, _ := r.HasSecret(ctx); has {
|
||||||
|
t.Fatal("HasSecret should be false after clearing the secret")
|
||||||
|
}
|
||||||
|
got, _ = r.ClientSecret(ctx)
|
||||||
|
if got != "" {
|
||||||
|
t.Fatalf("secret should be empty after clear, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -174,3 +174,67 @@ var (
|
|||||||
ErrInvalidToken = errors.New("invalid session token")
|
ErrInvalidToken = errors.New("invalid session token")
|
||||||
ErrExpiredToken = errors.New("session token expired")
|
ErrExpiredToken = errors.New("session token expired")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// blobEnvelope umhüllt eine beliebige Payload mit einem Ablaufzeitpunkt.
|
||||||
|
type blobEnvelope struct {
|
||||||
|
Exp int64 `json:"exp"`
|
||||||
|
Payload []byte `json:"p"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignBlob signiert beliebige Bytes mit dem Session-Secret (HMAC-SHA256,
|
||||||
|
// gleiches Format wie Tokens: base64url(json).base64url(sig)) und einer
|
||||||
|
// TTL. Für stateless, cluster-sichere Kurzzeit-Cookies (z.B. der
|
||||||
|
// OIDC-Flow-State). Das Secret ist clusterweit synchron (.jwt_fingerprint).
|
||||||
|
func (s *Signer) SignBlob(payload []byte, ttl time.Duration) (string, error) {
|
||||||
|
env := blobEnvelope{
|
||||||
|
Exp: s.Now().Add(ttl).Unix(),
|
||||||
|
Payload: payload,
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(env)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, s.Secret)
|
||||||
|
mac.Write(data)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(data) + "." +
|
||||||
|
base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyBlob prüft Signatur + Ablauf und gibt die ursprüngliche Payload
|
||||||
|
// zurück. ErrInvalidToken / ErrExpiredToken bei Fehlern.
|
||||||
|
func (s *Signer) VerifyBlob(raw string) ([]byte, error) {
|
||||||
|
if raw == "" {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
dot := -1
|
||||||
|
for i := 0; i < len(raw); i++ {
|
||||||
|
if raw[i] == '.' {
|
||||||
|
dot = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dot <= 0 || dot >= len(raw)-1 {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
payload, err := base64.RawURLEncoding.DecodeString(raw[:dot])
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
sig, err := base64.RawURLEncoding.DecodeString(raw[dot+1:])
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, s.Secret)
|
||||||
|
mac.Write(payload)
|
||||||
|
if subtle.ConstantTimeCompare(mac.Sum(nil), sig) != 1 {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
var env blobEnvelope
|
||||||
|
if err := json.Unmarshal(payload, &env); err != nil {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
if s.Now().Unix() >= env.Exp {
|
||||||
|
return nil, ErrExpiredToken
|
||||||
|
}
|
||||||
|
return env.Payload, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -240,6 +240,21 @@ func (r *Repo) RecordLogin(ctx context.Context, id int64) {
|
|||||||
_, _ = r.pool.Exec(ctx, `UPDATE users SET last_login_at=NOW() WHERE id=$1`, id)
|
_, _ = r.pool.Exec(ctx, `UPDATE users SET last_login_at=NOW() WHERE id=$1`, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOIDCSubject liefert den gespeicherten OIDC-'sub' des Users ("" wenn
|
||||||
|
// noch nicht verknüpft).
|
||||||
|
func (r *Repo) GetOIDCSubject(ctx context.Context, id int64) (string, error) {
|
||||||
|
var sub string
|
||||||
|
err := r.pool.QueryRow(ctx, `SELECT COALESCE(oidc_subject, '') FROM users WHERE id=$1`, id).Scan(&sub)
|
||||||
|
return sub, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetOIDCSubject speichert den OIDC-'sub' beim ersten erfolgreichen
|
||||||
|
// SSO-Login (opportunistisches Linking).
|
||||||
|
func (r *Repo) SetOIDCSubject(ctx context.Context, id int64, sub string) error {
|
||||||
|
_, err := r.pool.Exec(ctx, `UPDATE users SET oidc_subject=$1, updated_at=NOW() WHERE id=$2`, sub, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// VerifyPassword is a constant-time bcrypt compare.
|
// VerifyPassword is a constant-time bcrypt compare.
|
||||||
func VerifyPassword(hash, password string) bool {
|
func VerifyPassword(hash, password string) bool {
|
||||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Suspense, lazy, useEffect, type ReactNode } from 'react'
|
import { Suspense, lazy, useEffect, useState, type ReactNode } from 'react'
|
||||||
import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom'
|
import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom'
|
||||||
import ErrorBoundary from './components/ErrorBoundary'
|
import ErrorBoundary from './components/ErrorBoundary'
|
||||||
import { ConfigProvider, Spin } from 'antd'
|
import { ConfigProvider, Spin } from 'antd'
|
||||||
@@ -79,11 +79,37 @@ const antdTheme = {
|
|||||||
|
|
||||||
function RequireAuth({ children }: { children: ReactNode }) {
|
function RequireAuth({ children }: { children: ReactNode }) {
|
||||||
const user = useAuthStore((s) => s.user)
|
const user = useAuthStore((s) => s.user)
|
||||||
|
const setUser = useAuthStore((s) => s.set)
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
if (!user) {
|
// Wenn kein Store-User da ist (z.B. direkt nach SSO-Callback: Cookie
|
||||||
return <Navigate to="/login" replace state={{ from: location }} />
|
// gesetzt, sessionStorage leer — oder Hard-Refresh), einmal /auth/me
|
||||||
|
// probieren, bevor wir nach /login umleiten.
|
||||||
|
const [checking, setChecking] = useState(user === null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user !== null) {
|
||||||
|
setChecking(false)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return <>{children}</>
|
let cancelled = false
|
||||||
|
apiClient.get('/auth/me')
|
||||||
|
.then((r) => {
|
||||||
|
if (!cancelled && isEnvelope(r.data)) setUser(r.data.data as SessionUser)
|
||||||
|
})
|
||||||
|
.catch(() => { /* 401 → Interceptor leitet auf /login */ })
|
||||||
|
.finally(() => { if (!cancelled) setChecking(false) })
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [user, setUser])
|
||||||
|
|
||||||
|
if (user) return <>{children}</>
|
||||||
|
if (checking) {
|
||||||
|
return (
|
||||||
|
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||||
|
<Spin size="large" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return <Navigate to="/login" replace state={{ from: location }} />
|
||||||
}
|
}
|
||||||
|
|
||||||
function SetupGate({ children }: { children: ReactNode }) {
|
function SetupGate({ children }: { children: ReactNode }) {
|
||||||
|
|||||||
@@ -289,6 +289,24 @@
|
|||||||
"forgotPassword": "Passwort vergessen?",
|
"forgotPassword": "Passwort vergessen?",
|
||||||
"viewerBadge": "Nur lesen",
|
"viewerBadge": "Nur lesen",
|
||||||
"viewerHint": "Dieser Account hat die Rolle Betrachter — Änderungen sind gesperrt. Ein Admin kann die Rolle anpassen.",
|
"viewerHint": "Dieser Account hat die Rolle Betrachter — Änderungen sind gesperrt. Ein Admin kann die Rolle anpassen.",
|
||||||
|
"sso": {
|
||||||
|
"login": "Mit SSO anmelden",
|
||||||
|
"err": {
|
||||||
|
"no_account": "Kein EdgeGuard-Konto für diese E-Mail. Bitte wende dich an einen Administrator.",
|
||||||
|
"disabled": "Dieses Konto ist deaktiviert.",
|
||||||
|
"unverified": "Die E-Mail-Adresse ist beim Identity-Provider nicht verifiziert.",
|
||||||
|
"state": "Sicherheitsprüfung fehlgeschlagen (State). Bitte erneut versuchen.",
|
||||||
|
"nonce": "Sicherheitsprüfung fehlgeschlagen (Nonce). Bitte erneut versuchen.",
|
||||||
|
"token": "Das Token vom Identity-Provider konnte nicht verifiziert werden.",
|
||||||
|
"exchange": "Code-Austausch mit dem Identity-Provider fehlgeschlagen.",
|
||||||
|
"expired": "Die Anmeldesitzung ist abgelaufen. Bitte erneut versuchen.",
|
||||||
|
"denied": "Anmeldung beim Identity-Provider abgebrochen.",
|
||||||
|
"subject_mismatch": "Die Identität passt nicht zum hinterlegten Konto.",
|
||||||
|
"config": "SSO ist nicht korrekt konfiguriert.",
|
||||||
|
"server": "Interner Fehler bei der SSO-Anmeldung.",
|
||||||
|
"generic": "SSO-Anmeldung fehlgeschlagen."
|
||||||
|
}
|
||||||
|
},
|
||||||
"totp": {
|
"totp": {
|
||||||
"prompt": "Bitte gib den 6-stelligen Code aus deiner Authenticator-App ein.",
|
"prompt": "Bitte gib den 6-stelligen Code aus deiner Authenticator-App ein.",
|
||||||
"verify": "Code bestätigen",
|
"verify": "Code bestätigen",
|
||||||
@@ -907,6 +925,24 @@
|
|||||||
"configPreviewBtn": "Vorschau laden",
|
"configPreviewBtn": "Vorschau laden",
|
||||||
"configPreviewHint": "Rendert die gewählte Service-Config aus dem aktuellen DB-State. Nur Lesezugriff — es wird nichts auf Disk geschrieben oder neu geladen.",
|
"configPreviewHint": "Rendert die gewählte Service-Config aus dem aktuellen DB-State. Nur Lesezugriff — es wird nichts auf Disk geschrieben oder neu geladen.",
|
||||||
"configCopied": "Config in Zwischenablage kopiert",
|
"configCopied": "Config in Zwischenablage kopiert",
|
||||||
|
"oidc": {
|
||||||
|
"title": "Single Sign-On (OIDC)",
|
||||||
|
"intro": "SSO-Login per OpenID Connect (z. B. Keycloak), zusätzlich zum lokalen Login. Anmeldung gelingt nur für bereits angelegte Benutzer; die Rolle wird in EdgeGuard verwaltet.",
|
||||||
|
"enabled": "SSO aktiviert",
|
||||||
|
"issuerUrl": "Issuer-URL",
|
||||||
|
"issuerHint": "Basis-URL des Realms, z. B. https://keycloak.example.com/realms/edgeguard",
|
||||||
|
"clientId": "Client-ID",
|
||||||
|
"clientSecret": "Client-Secret",
|
||||||
|
"secretSet": "Gespeichert — leer lassen, um es unverändert zu lassen.",
|
||||||
|
"secretUnset": "Noch kein Secret gespeichert.",
|
||||||
|
"scopes": "Scopes",
|
||||||
|
"emailClaim": "E-Mail-Claim",
|
||||||
|
"buttonLabel": "Button-Beschriftung",
|
||||||
|
"redirectUri": "Redirect-URI",
|
||||||
|
"redirectHint": "Diese URL im Keycloak-Client als gültige Redirect-URI eintragen (pro Cluster-Node die jeweilige FQDN).",
|
||||||
|
"saved": "OIDC-Einstellungen gespeichert",
|
||||||
|
"saveFailed": "Speichern der OIDC-Einstellungen fehlgeschlagen"
|
||||||
|
},
|
||||||
"passwordCardTitle": "Admin-Passwort ändern",
|
"passwordCardTitle": "Admin-Passwort ändern",
|
||||||
"currentPassword": "Aktuelles Passwort",
|
"currentPassword": "Aktuelles Passwort",
|
||||||
"newPassword": "Neues Passwort",
|
"newPassword": "Neues Passwort",
|
||||||
@@ -1287,6 +1323,7 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"yes": "Ja",
|
"yes": "Ja",
|
||||||
"no": "Nein",
|
"no": "Nein",
|
||||||
|
"or": "oder",
|
||||||
"save": "Speichern",
|
"save": "Speichern",
|
||||||
"cancel": "Abbrechen",
|
"cancel": "Abbrechen",
|
||||||
"loading": "Lädt …",
|
"loading": "Lädt …",
|
||||||
|
|||||||
@@ -289,6 +289,24 @@
|
|||||||
"forgotPassword": "Forgot your password?",
|
"forgotPassword": "Forgot your password?",
|
||||||
"viewerBadge": "Read-only",
|
"viewerBadge": "Read-only",
|
||||||
"viewerHint": "Your account has viewer role — all changes are blocked. Contact an admin to change your role.",
|
"viewerHint": "Your account has viewer role — all changes are blocked. Contact an admin to change your role.",
|
||||||
|
"sso": {
|
||||||
|
"login": "Sign in with SSO",
|
||||||
|
"err": {
|
||||||
|
"no_account": "No EdgeGuard account for this email. Please contact an administrator.",
|
||||||
|
"disabled": "This account is disabled.",
|
||||||
|
"unverified": "The email address is not verified at the identity provider.",
|
||||||
|
"state": "Security check failed (state). Please try again.",
|
||||||
|
"nonce": "Security check failed (nonce). Please try again.",
|
||||||
|
"token": "Could not verify the token from the identity provider.",
|
||||||
|
"exchange": "Code exchange with the identity provider failed.",
|
||||||
|
"expired": "The sign-in session expired. Please try again.",
|
||||||
|
"denied": "Sign-in at the identity provider was cancelled.",
|
||||||
|
"subject_mismatch": "The identity does not match the linked account.",
|
||||||
|
"config": "SSO is not configured correctly.",
|
||||||
|
"server": "Internal error during SSO sign-in.",
|
||||||
|
"generic": "SSO sign-in failed."
|
||||||
|
}
|
||||||
|
},
|
||||||
"totp": {
|
"totp": {
|
||||||
"prompt": "Enter the 6-digit code from your authenticator app.",
|
"prompt": "Enter the 6-digit code from your authenticator app.",
|
||||||
"verify": "Verify code",
|
"verify": "Verify code",
|
||||||
@@ -907,6 +925,24 @@
|
|||||||
"configPreviewBtn": "Load preview",
|
"configPreviewBtn": "Load preview",
|
||||||
"configPreviewHint": "Renders the selected service config from the current DB state. Read-only — nothing is written to disk or reloaded.",
|
"configPreviewHint": "Renders the selected service config from the current DB state. Read-only — nothing is written to disk or reloaded.",
|
||||||
"configCopied": "Config copied to clipboard",
|
"configCopied": "Config copied to clipboard",
|
||||||
|
"oidc": {
|
||||||
|
"title": "Single Sign-On (OIDC)",
|
||||||
|
"intro": "SSO login via OpenID Connect (e.g. Keycloak), in addition to local login. Only existing users can sign in; the role is managed in EdgeGuard.",
|
||||||
|
"enabled": "SSO enabled",
|
||||||
|
"issuerUrl": "Issuer URL",
|
||||||
|
"issuerHint": "Realm base URL, e.g. https://keycloak.example.com/realms/edgeguard",
|
||||||
|
"clientId": "Client ID",
|
||||||
|
"clientSecret": "Client secret",
|
||||||
|
"secretSet": "Stored — leave empty to keep unchanged.",
|
||||||
|
"secretUnset": "No secret stored yet.",
|
||||||
|
"scopes": "Scopes",
|
||||||
|
"emailClaim": "Email claim",
|
||||||
|
"buttonLabel": "Button label",
|
||||||
|
"redirectUri": "Redirect URI",
|
||||||
|
"redirectHint": "Register this URL as a valid redirect URI in the Keycloak client (per cluster node its own FQDN).",
|
||||||
|
"saved": "OIDC settings saved",
|
||||||
|
"saveFailed": "Failed to save OIDC settings"
|
||||||
|
},
|
||||||
"passwordCardTitle": "Change admin password",
|
"passwordCardTitle": "Change admin password",
|
||||||
"currentPassword": "Current password",
|
"currentPassword": "Current password",
|
||||||
"newPassword": "New password",
|
"newPassword": "New password",
|
||||||
@@ -1287,6 +1323,7 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"yes": "Yes",
|
"yes": "Yes",
|
||||||
"no": "No",
|
"no": "No",
|
||||||
|
"or": "or",
|
||||||
"save": "Save",
|
"save": "Save",
|
||||||
"cancel": "Cancel",
|
"cancel": "Cancel",
|
||||||
"loading": "Loading …",
|
"loading": "Loading …",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Button, Card, Form, Input, message, Typography } from 'antd'
|
import { Button, Card, Divider, Form, Input, message, Typography } from 'antd'
|
||||||
import { KeyOutlined } from '@ant-design/icons'
|
import { KeyOutlined, LoginOutlined } from '@ant-design/icons'
|
||||||
import { Link, useNavigate } from 'react-router-dom'
|
import { Link, useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
@@ -22,6 +22,28 @@ export default function LoginPage({ onLogin }: Props) {
|
|||||||
const [totpRequired, setTotpRequired] = useState(false)
|
const [totpRequired, setTotpRequired] = useState(false)
|
||||||
const [totpCode, setTotpCode] = useState('')
|
const [totpCode, setTotpCode] = useState('')
|
||||||
const [verifying, setVerifying] = useState(false)
|
const [verifying, setVerifying] = useState(false)
|
||||||
|
const [ssoEnabled, setSsoEnabled] = useState(false)
|
||||||
|
const [ssoLabel, setSsoLabel] = useState('')
|
||||||
|
|
||||||
|
// SSO-Verfügbarkeit prüfen + evtl. ?sso_error vom Callback anzeigen.
|
||||||
|
useEffect(() => {
|
||||||
|
apiClient.get('/auth/oidc/settings')
|
||||||
|
.then((r) => {
|
||||||
|
if (!isEnvelope(r.data)) return
|
||||||
|
const d = r.data.data as { enabled?: boolean; button_label?: string }
|
||||||
|
setSsoEnabled(!!d.enabled)
|
||||||
|
setSsoLabel(d.button_label || '')
|
||||||
|
})
|
||||||
|
.catch(() => { /* SSO optional */ })
|
||||||
|
|
||||||
|
const reason = new URLSearchParams(window.location.search).get('sso_error')
|
||||||
|
if (reason) {
|
||||||
|
const key = `auth.sso.err.${reason}`
|
||||||
|
const txt = t(key)
|
||||||
|
message.error(txt === key ? t('auth.sso.err.generic') : txt)
|
||||||
|
window.history.replaceState({}, '', window.location.pathname)
|
||||||
|
}
|
||||||
|
}, [t])
|
||||||
|
|
||||||
const onFinish = async (vals: LoginValues) => {
|
const onFinish = async (vals: LoginValues) => {
|
||||||
try {
|
try {
|
||||||
@@ -106,6 +128,20 @@ export default function LoginPage({ onLogin }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!totpRequired && ssoEnabled && (
|
||||||
|
<>
|
||||||
|
<Divider plain style={{ fontSize: 12, color: '#94a3b8' }}>{t('common.or')}</Divider>
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
icon={<LoginOutlined />}
|
||||||
|
style={{ marginBottom: 12 }}
|
||||||
|
onClick={() => { window.location.href = '/api/v1/auth/oidc/login' }}
|
||||||
|
>
|
||||||
|
{ssoLabel || t('auth.sso.login')}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{!totpRequired && (
|
{!totpRequired && (
|
||||||
<div style={{ textAlign: 'center', fontSize: 12 }}>
|
<div style={{ textAlign: 'center', fontSize: 12 }}>
|
||||||
<Link to="/reset-password">{t('auth.forgotPassword')}</Link>
|
<Link to="/reset-password">{t('auth.forgotPassword')}</Link>
|
||||||
|
|||||||
@@ -46,6 +46,27 @@ interface VIPSettingsValues {
|
|||||||
gw_check_ip?: string
|
gw_check_ip?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface OIDCSettingsView {
|
||||||
|
enabled: boolean
|
||||||
|
issuer_url: string
|
||||||
|
client_id: string
|
||||||
|
scopes: string
|
||||||
|
email_claim: string
|
||||||
|
button_label: string
|
||||||
|
secret_configured: boolean
|
||||||
|
redirect_uri: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OIDCFormValues {
|
||||||
|
enabled: boolean
|
||||||
|
issuer_url: string
|
||||||
|
client_id: string
|
||||||
|
client_secret?: string
|
||||||
|
scopes: string
|
||||||
|
email_claim: string
|
||||||
|
button_label: string
|
||||||
|
}
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient()
|
||||||
@@ -93,6 +114,41 @@ export default function SettingsPage() {
|
|||||||
onError: (e: Error) => msg.error(t('cluster.vipCard.saveFailed') + ': ' + e.message),
|
onError: (e: Error) => msg.error(t('cluster.vipCard.saveFailed') + ': ' + e.message),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const [oidcForm] = Form.useForm<OIDCFormValues>()
|
||||||
|
const { data: oidc } = useQuery({
|
||||||
|
queryKey: ['oidc', 'settings'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const r = await apiClient.get('/oidc/settings')
|
||||||
|
return isEnvelope(r.data) ? r.data.data as OIDCSettingsView : null
|
||||||
|
},
|
||||||
|
})
|
||||||
|
useEffect(() => {
|
||||||
|
if (oidc) {
|
||||||
|
oidcForm.setFieldsValue({
|
||||||
|
enabled: oidc.enabled,
|
||||||
|
issuer_url: oidc.issuer_url,
|
||||||
|
client_id: oidc.client_id,
|
||||||
|
scopes: oidc.scopes,
|
||||||
|
email_claim: oidc.email_claim,
|
||||||
|
button_label: oidc.button_label,
|
||||||
|
client_secret: '',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}, [oidc, oidcForm])
|
||||||
|
const updateOIDC = useMutation({
|
||||||
|
mutationFn: async (v: OIDCFormValues) => {
|
||||||
|
const body: Record<string, unknown> = { ...v }
|
||||||
|
// leeres Secret = unverändert → Feld weglassen (Backend: nil)
|
||||||
|
if (!v.client_secret) delete body.client_secret
|
||||||
|
return apiClient.put('/oidc/settings', body)
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
msg.success(t('settings.oidc.saved'))
|
||||||
|
void qc.invalidateQueries({ queryKey: ['oidc', 'settings'] })
|
||||||
|
},
|
||||||
|
onError: (e: Error) => msg.error(t('settings.oidc.saveFailed') + ': ' + e.message),
|
||||||
|
})
|
||||||
|
|
||||||
const [emailForm] = Form.useForm<ContactEmailValues>()
|
const [emailForm] = Form.useForm<ContactEmailValues>()
|
||||||
const updateEmails = useMutation({
|
const updateEmails = useMutation({
|
||||||
mutationFn: async (v: ContactEmailValues) => {
|
mutationFn: async (v: ContactEmailValues) => {
|
||||||
@@ -879,6 +935,49 @@ export default function SettingsPage() {
|
|||||||
</Form>
|
</Form>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<Card title={<><GlobalOutlined /> {t('settings.oidc.title')}</>} className="mb-12" size="small">
|
||||||
|
<Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
|
||||||
|
{t('settings.oidc.intro')}
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<Form<OIDCFormValues> form={oidcForm} layout="vertical" onFinish={(v) => updateOIDC.mutate(v)}>
|
||||||
|
<Form.Item label={t('settings.oidc.enabled')} name="enabled" valuePropName="checked">
|
||||||
|
<Switch disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('settings.oidc.issuerUrl')} name="issuer_url" extra={t('settings.oidc.issuerHint')}>
|
||||||
|
<Input placeholder="https://keycloak.example.com/realms/edgeguard" disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('settings.oidc.clientId')} name="client_id">
|
||||||
|
<Input disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
label={t('settings.oidc.clientSecret')}
|
||||||
|
name="client_secret"
|
||||||
|
extra={oidc?.secret_configured ? t('settings.oidc.secretSet') : t('settings.oidc.secretUnset')}
|
||||||
|
>
|
||||||
|
<Input.Password placeholder={oidc?.secret_configured ? '••••••••' : ''} autoComplete="new-password" disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('settings.oidc.scopes')} name="scopes">
|
||||||
|
<Input placeholder="openid email profile" disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('settings.oidc.emailClaim')} name="email_claim">
|
||||||
|
<Input placeholder="email" disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('settings.oidc.buttonLabel')} name="button_label">
|
||||||
|
<Input disabled={isViewer} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('settings.oidc.redirectUri')} extra={t('settings.oidc.redirectHint')}>
|
||||||
|
<Typography.Text copyable code style={{ fontSize: 12 }}>{oidc?.redirect_uri || ''}</Typography.Text>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item style={{ marginBottom: 0 }}>
|
||||||
|
<Tooltip title={isViewer ? t('auth.viewerBadge') : undefined}>
|
||||||
|
<Button type="primary" htmlType="submit" loading={updateOIDC.isPending} disabled={isViewer}>
|
||||||
|
{t('common.save')}
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Card>
|
||||||
|
|
||||||
<Card title={<><LockOutlined /> {t('settings.passwordCardTitle')}</>} size="small">
|
<Card title={<><LockOutlined /> {t('settings.passwordCardTitle')}</>} size="small">
|
||||||
<Form<ChangePasswordValues>
|
<Form<ChangePasswordValues>
|
||||||
form={pwForm}
|
form={pwForm}
|
||||||
|
|||||||
Reference in New Issue
Block a user