Refactor architecture: extract reconciler, add interfaces, reduce complexity, improve test coverage

Architecture:
- Extract reconcileNetworking into internal/reconcile package with 7 consumer-side interfaces
- Add locked modifyState helper to fix state.yaml read-modify-write race condition
- Extract CrowdSec and VPN handler groups with interfaces documenting dependency surface
- Replace raw map[string]any YAML manipulation with typed AddDHCPStaticLease/RemoveDHCPStaticLease
- Extract Cloudflare API functions into cfClient struct, eliminating repeated auth boilerplate

Complexity reduction:
- haproxy.GenerateWithOpts: 50 → 6 (extracted 8 focused helpers)
- reconcile.Reconcile: 42 → 11 (extracted buildRoutes, buildDNSEntries, writeHAProxyConfig)
- AutheliaUpdateConfig: 25 → 10 (extracted enableAuthelia/disableAuthelia)

Test coverage improvements:
- reconcile: 4.5% → 56.8% (stub-based tests for route building, DNS entries, orchestration)
- dnsfilter: 10.7% → 45.6% (Manager.Compile, AddList, ToggleList, custom entries)
- config: 67.3% → 89.8% (DHCP static lease mutation tests)
This commit is contained in:
2026-07-14 04:21:30 +00:00
parent 1e7d93256e
commit 428d47f876
35 changed files with 1856 additions and 1194 deletions

View File

@@ -114,91 +114,73 @@ func (api *API) AutheliaUpdateConfig(w http.ResponseWriter, r *http.Request) {
_ = api.secrets.SetSecret("authelia.smtpPassword", *req.SMTPPassword)
}
// Enabling Authelia
if state.Cloud.Authelia.Enabled {
if !api.authelia.IsInstalled() {
respondError(w, http.StatusBadRequest, "Authelia is not installed. Install it first (apt install authelia).")
return
}
if state.Cloud.Authelia.Domain == "" {
respondError(w, http.StatusBadRequest, "Auth portal domain is required when enabling Authelia")
return
}
if !api.authelia.HasLuaScript() {
respondError(w, http.StatusBadRequest,
"HAProxy auth-request Lua script not found at /etc/haproxy/lua/haproxy-auth-request.lua. "+
"Install it: sudo mkdir -p /etc/haproxy/lua && sudo curl -fsSL -o /etc/haproxy/lua/haproxy-auth-request.lua "+
"https://raw.githubusercontent.com/TimWolla/haproxy-auth-request/main/auth-request.lua")
return
}
// Ensure data directory exists
if err := api.authelia.EnsureDataDir(); err != nil {
respondError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to create data directory: %v", err))
return
}
// Auto-generate secrets if missing
if err := api.ensureAutheliaSecrets(); err != nil {
respondError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to generate secrets: %v", err))
return
}
// Generate JWKS key pair for OIDC
if err := api.authelia.EnsureJWKS(); err != nil {
respondError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to generate JWKS: %v", err))
return
}
// Ensure user database exists
if err := api.authelia.EnsureUsersDB(); err != nil {
respondError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to initialize user database: %v", err))
return
}
// Generate config
if err := api.generateAutheliaConfig(state); err != nil {
respondError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to generate config: %v", err))
return
}
// Register auth portal domain
api.ensureAuthDomain(state.Cloud.Authelia.Domain)
// Start service — requires at least one user
startErr := error(nil)
if api.authelia.UserCount() > 0 {
startErr = api.authelia.RestartService()
}
// Save state and reconcile regardless of whether the service started
if err := config.SaveState(state, api.statePath()); err != nil {
respondError(w, http.StatusInternalServerError, "Failed to save state")
return
}
go api.reconcileNetworking()
api.broadcastAutheliaEvent("authelia:config", "Authelia configuration updated")
if startErr != nil {
respondError(w, http.StatusInternalServerError, fmt.Sprintf("Configuration saved but Authelia failed to start: %v", startErr))
if err := api.enableAuthelia(state); err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
} else {
// Disabling — stop service and deregister domain
_ = api.authelia.StopService()
api.deregisterAuthDomain()
if err := config.SaveState(state, api.statePath()); err != nil {
respondError(w, http.StatusInternalServerError, "Failed to save state")
return
}
go api.reconcileNetworking()
api.broadcastAutheliaEvent("authelia:config", "Authelia configuration updated")
api.disableAuthelia(state)
}
if err := config.SaveState(state, api.statePath()); err != nil {
respondError(w, http.StatusInternalServerError, "Failed to save state")
return
}
go api.reconciler.Reconcile()
api.broadcastAutheliaEvent("authelia:config", "Authelia configuration updated")
respondMessage(w, http.StatusOK, "Authelia configuration updated")
}
// enableAuthelia validates prerequisites, sets up services, generates config,
// and starts Authelia. Returns a user-facing error message or nil.
func (api *API) enableAuthelia(state *config.State) error {
if !api.authelia.IsInstalled() {
return fmt.Errorf("Authelia is not installed. Install it first (apt install authelia).")
}
if state.Cloud.Authelia.Domain == "" {
return fmt.Errorf("Auth portal domain is required when enabling Authelia")
}
if !api.authelia.HasLuaScript() {
return fmt.Errorf(
"HAProxy auth-request Lua script not found at /etc/haproxy/lua/haproxy-auth-request.lua. " +
"Install it: sudo mkdir -p /etc/haproxy/lua && sudo curl -fsSL -o /etc/haproxy/lua/haproxy-auth-request.lua " +
"https://raw.githubusercontent.com/TimWolla/haproxy-auth-request/main/auth-request.lua")
}
if err := api.authelia.EnsureDataDir(); err != nil {
return fmt.Errorf("Failed to create data directory: %v", err)
}
if err := api.ensureAutheliaSecrets(); err != nil {
return fmt.Errorf("Failed to generate secrets: %v", err)
}
if err := api.authelia.EnsureJWKS(); err != nil {
return fmt.Errorf("Failed to generate JWKS: %v", err)
}
if err := api.authelia.EnsureUsersDB(); err != nil {
return fmt.Errorf("Failed to initialize user database: %v", err)
}
if err := api.generateAutheliaConfig(state); err != nil {
return fmt.Errorf("Failed to generate config: %v", err)
}
api.ensureAuthDomain(state.Cloud.Authelia.Domain)
if api.authelia.UserCount() > 0 {
if err := api.authelia.RestartService(); err != nil {
return fmt.Errorf("Configuration saved but Authelia failed to start: %v", err)
}
}
return nil
}
// disableAuthelia stops the service and removes auth domain registrations.
func (api *API) disableAuthelia(_ *config.State) {
_ = api.authelia.StopService()
api.deregisterAuthDomain()
}
// AutheliaRestart restarts the Authelia service
func (api *API) AutheliaRestart(w http.ResponseWriter, r *http.Request) {
if err := api.authelia.RestartService(); err != nil {