Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(license): add audit_logging, advanced_sso, advanced_reporting to Pro tier
rcourtman668cdf339345
diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsxindex ea150dea6e..b5a318fb33 100644--- a/frontend-modern/src/components/Settings/AISettings.tsx+++ b/frontend-modern/src/components/Settings/AISettings.tsx@@ -8,7 +8,7 @@ import { formField, labelClass, controlClass } from '@/components/shared/Form';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import { AIAPI } from '@/api/ai';-import { isEnterprise, loadLicenseStatus } from '@/stores/license';+import { hasFeature, loadLicenseStatus } from '@/stores/license';import type { AISettings as AISettingsType, AIProvider, AuthMethod } from '@/types/ai';// Providers are now configured via accordion sections, not a single-provider selector@@ -93,8 +93,8 @@ export const AISettings: Component = () => {// Per-provider test stateconst [testingProvider, setTestingProvider] = createSignal<string | null>(null);const [providerTestResult, setProviderTestResult] = createSignal<{ provider: string; success: boolean; message: string } | null>(null);- const hasAlertAnalysisFeature = createMemo(() => isEnterprise());- const hasAutoFixFeature = createMemo(() => isEnterprise());+ const hasAlertAnalysisFeature = createMemo(() => hasFeature('ai_alerts'));+ const hasAutoFixFeature = createMemo(() => hasFeature('ai_autofix'));const alertAnalysisLocked = createMemo(() => !hasAlertAnalysisFeature());const autoFixLocked = createMemo(() => !hasAutoFixFeature());diff --git a/frontend-modern/src/components/Settings/AuditLogPanel.tsx b/frontend-modern/src/components/Settings/AuditLogPanel.tsxindex 72806e3855..4727870405 100644--- a/frontend-modern/src/components/Settings/AuditLogPanel.tsx+++ b/frontend-modern/src/components/Settings/AuditLogPanel.tsx@@ -16,7 +16,7 @@ import {STORAGE_KEYS,} from '@/utils/localStorage';import { showSuccess, showWarning, showToast } from '@/utils/toast';-import { isEnterprise, loadLicenseStatus } from '@/stores/license';+import { hasFeature, loadLicenseStatus } from '@/stores/license';interface AuditEvent {id: string;@@ -499,7 +499,7 @@ export default function AuditLogPanel() {</div>{/* Upgrade CTA */}- <Show when={!isEnterprise() && !loading()}>+ <Show when={!hasFeature('audit_logging') && !loading()}><div class="p-6 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/20 dark:to-purple-900/20 border border-indigo-100 dark:border-indigo-800 rounded-xl"><div class="flex flex-col sm:flex-row items-center gap-4"><div class="flex-1">diff --git a/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx b/frontend-modern/src/components/Settings/AuditWebhookPanel.tsxindex a703e36147..2de34ae97f 100644--- a/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx+++ b/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx@@ -8,7 +8,7 @@ import { Card } from '@/components/shared/Card';import { SectionHeader } from '@/components/shared/SectionHeader';import { showSuccess, showWarning } from '@/utils/toast';import { apiFetchJSON } from '@/utils/apiClient';-import { isEnterprise, loadLicenseStatus } from '@/stores/license';+import { hasFeature, loadLicenseStatus } from '@/stores/license';export function AuditWebhookPanel() {const [webhookUrls, setWebhookUrls] = createSignal<string[]>([]);@@ -21,7 +21,7 @@ export function AuditWebhookPanel() {});createEffect(() => {- if (isEnterprise()) {+ if (hasFeature('audit_logging')) {fetchWebhooks();} else {setLoading(false);diff --git a/frontend-modern/src/components/Settings/OIDCPanel.tsx b/frontend-modern/src/components/Settings/OIDCPanel.tsxindex 8dc1abc9d9..c7d8227b7a 100644--- a/frontend-modern/src/components/Settings/OIDCPanel.tsx+++ b/frontend-modern/src/components/Settings/OIDCPanel.tsx@@ -6,7 +6,7 @@ import { Toggle } from '@/components/shared/Toggle';import { formField, labelClass, controlClass, formHelpText } from '@/components/shared/Form';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';-import { isEnterprise, loadLicenseStatus } from '@/stores/license';+import { hasFeature, loadLicenseStatus } from '@/stores/license';interface OIDCConfigResponse {enabled: boolean;@@ -279,7 +279,7 @@ export const OIDCPanel: Component<Props> = (props) => {/></div></div>- <Show when={!isEnterprise() && !loading()}>+ <Show when={!hasFeature('sso') && !loading()}><div class="mx-6 mt-6 p-5 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/20 dark:to-purple-900/20 border border-indigo-100 dark:border-indigo-800 rounded-xl"><div class="flex flex-col sm:flex-row items-center gap-4"><div class="flex-1">diff --git a/frontend-modern/src/components/Settings/RolesPanel.tsx b/frontend-modern/src/components/Settings/RolesPanel.tsxindex 375351d0ff..503fe05029 100644--- a/frontend-modern/src/components/Settings/RolesPanel.tsx+++ b/frontend-modern/src/components/Settings/RolesPanel.tsx@@ -4,7 +4,7 @@ import { RBACAPI } from '@/api/rbac';import type { Role, Permission } from '@/types/rbac';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';-import { isEnterprise, loadLicenseStatus } from '@/stores/license';+import { hasFeature, loadLicenseStatus } from '@/stores/license';import Plus from 'lucide-solid/icons/plus';import Pencil from 'lucide-solid/icons/pencil';import Trash2 from 'lucide-solid/icons/trash-2';@@ -147,7 +147,7 @@ export const RolesPanel: Component = () => {</button></div>- <Show when={!isEnterprise() && !loading()}>+ <Show when={!hasFeature('rbac') && !loading()}><div class="p-4 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/20 dark:to-purple-900/20 border border-indigo-100 dark:border-indigo-800 rounded-xl"><div class="flex flex-col sm:flex-row items-center gap-4"><div class="flex-1">diff --git a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsxindex b6bb49fd77..d270c0e2e0 100644--- a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx+++ b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx@@ -4,7 +4,7 @@ import { RBACAPI } from '@/api/rbac';import type { Role, UserRoleAssignment, Permission } from '@/types/rbac';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';-import { isEnterprise, loadLicenseStatus } from '@/stores/license';+import { hasFeature, loadLicenseStatus } from '@/stores/license';import Users from 'lucide-solid/icons/users';import Shield from 'lucide-solid/icons/shield';import BadgeCheck from 'lucide-solid/icons/badge-check';@@ -129,7 +129,7 @@ export const UserAssignmentsPanel: Component = () => {</div></div>- <Show when={!isEnterprise() && !loading()}>+ <Show when={!hasFeature('rbac') && !loading()}><div class="p-4 bg-gradient-to-r from-teal-50 to-emerald-50 dark:from-teal-900/20 dark:to-emerald-900/20 border border-teal-100 dark:border-teal-800 rounded-xl"><div class="flex flex-col sm:flex-row items-center gap-4"><div class="flex-1">diff --git a/internal/api/audit_handlers.go b/internal/api/audit_handlers.goindex 529468be06..718c9e3c18 100644--- a/internal/api/audit_handlers.go+++ b/internal/api/audit_handlers.go@@ -3,7 +3,10 @@ package apiimport ("encoding/json""fmt"+ "net""net/http"+ "net/url"+ "regexp""strconv""strings""time"@@ -11,6 +14,9 @@ import ("github.com/rcourtman/pulse-go-rewrite/pkg/audit")+// validAuditEventID matches alphanumeric IDs with hyphens (UUID format)+var validAuditEventID = regexp.MustCompile(`^[a-zA-Z0-9\-]+$`)+// AuditHandlers provides HTTP handlers for audit log endpoints.type AuditHandlers struct{}@@ -19,8 +25,7 @@ func NewAuditHandlers() *AuditHandlers {return &AuditHandlers{}}-// HandleListAuditEvents returns audit events matching query parameters.-// Query params: user, event, startTime, endTime, limit, offset, success+// HandleListAuditEvents handles GET /api/auditfunc (h *AuditHandlers) HandleListAuditEvents(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -101,21 +106,24 @@ func (h *AuditHandlers) HandleListAuditEvents(w http.ResponseWriter, r *http.Reqjson.NewEncoder(w).Encode(response)}-// HandleVerifyAuditEvent verifies the signature of a specific audit event.-// This is only functional with enterprise audit logging.+// HandleVerifyAuditEvent handles GET /api/audit/{id}/verifyfunc (h *AuditHandlers) HandleVerifyAuditEvent(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- path := strings.TrimPrefix(r.URL.Path, "/api/audit/")- parts := strings.Split(strings.Trim(path, "/"), "/")- if len(parts) != 2 || parts[1] != "verify" || parts[0] == "" {- http.Error(w, "Not found", http.StatusNotFound)+ eventID := r.PathValue("id")+ if eventID == "" {+ writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Missing event ID", nil)+ return+ }++ // Validate event ID format to prevent injection+ if !validAuditEventID.MatchString(eventID) || len(eventID) > 64 {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_id", "Invalid event ID format", nil)return}- eventID := parts[0]// For OSS, return not_availableif !isPersistentLogger() {@@ -184,23 +192,118 @@ func (h *AuditHandlers) HandleUpdateWebhooks(w http.ResponseWriter, r *http.Requreturn}+ // Limit request body size to prevent memory exhaustion+ r.Body = http.MaxBytesReader(w, r.Body, 64*1024) // 64KB max+var req struct {URLs []string `json:"urls"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request", http.StatusBadRequest)+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)return}+ // Validate all webhook URLs+ var validatedURLs []string+ for _, rawURL := range req.URLs {+ if err := validateWebhookURL(rawURL); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_url", fmt.Sprintf("Invalid webhook URL: %s", err.Error()), map[string]string{"url": rawURL})+ return+ }+ validatedURLs = append(validatedURLs, rawURL)+ }+logger := audit.GetLogger()- if err := logger.UpdateWebhookURLs(req.URLs); err != nil {- http.Error(w, fmt.Sprintf("Failed to update webhooks: %v", err), http.StatusInternalServerError)+ if err := logger.UpdateWebhookURLs(validatedURLs); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "update_failed", "Failed to update webhooks", nil)return}w.WriteHeader(http.StatusNoContent)}+// validateWebhookURL validates a webhook URL for security.+// Returns an error if the URL is invalid or potentially dangerous (SSRF).+func validateWebhookURL(rawURL string) error {+ if strings.TrimSpace(rawURL) == "" {+ return fmt.Errorf("URL cannot be empty")+ }++ parsed, err := url.Parse(rawURL)+ if err != nil {+ return fmt.Errorf("invalid URL format")+ }++ // Only allow http and https schemes+ if parsed.Scheme != "http" && parsed.Scheme != "https" {+ return fmt.Errorf("URL scheme must be http or https")+ }++ // Ensure host is present+ if parsed.Host == "" {+ return fmt.Errorf("URL must have a host")+ }++ // Extract hostname (without port)+ hostname := parsed.Hostname()+ if hostname == "" {+ return fmt.Errorf("URL must have a hostname")+ }++ // Block localhost and loopback addresses+ if hostname == "localhost" || hostname == "127.0.0.1" || hostname == "::1" {+ return fmt.Errorf("localhost URLs are not allowed")+ }++ // Check if hostname is an IP address+ ip := net.ParseIP(hostname)+ if ip != nil {+ // Block private/internal IP ranges (SSRF protection)+ if isPrivateOrReservedIP(ip) {+ return fmt.Errorf("private or reserved IP addresses are not allowed")+ }+ }++ // Block common internal hostnames+ lowerHost := strings.ToLower(hostname)+ blockedPatterns := []string{+ "metadata.google",+ "169.254.169.254", // AWS/GCP metadata+ "metadata.azure",+ "internal",+ ".local",+ ".localhost",+ }+ for _, pattern := range blockedPatterns {+ if strings.Contains(lowerHost, pattern) {+ return fmt.Errorf("internal hostnames are not allowed")+ }+ }++ return nil+}++// isPrivateOrReservedIP checks if an IP is private, loopback, or reserved.+func isPrivateOrReservedIP(ip net.IP) bool {+ if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {+ return true+ }++ // Additional checks for reserved ranges+ // 169.254.0.0/16 - Link-local (also covers cloud metadata endpoints)+ if ip4 := ip.To4(); ip4 != nil {+ if ip4[0] == 169 && ip4[1] == 254 {+ return true+ }+ // 0.0.0.0/8+ if ip4[0] == 0 {+ return true+ }+ }++ return false+}+// isPersistentLogger checks if we're using a persistent audit logger (enterprise).func isPersistentLogger() bool {logger := audit.GetLogger()diff --git a/internal/api/audit_handlers_test.go b/internal/api/audit_handlers_test.goindex 1a1bbc82f9..80b6340735 100644--- a/internal/api/audit_handlers_test.go+++ b/internal/api/audit_handlers_test.go@@ -101,7 +101,6 @@ func setAuditLogger(t *testing.T, logger audit.Logger) {audit.SetLogger(prev)})}-func TestHandleVerifyAuditEvent_InvalidPath(t *testing.T) {handler := NewAuditHandlers()@@ -110,8 +109,8 @@ func TestHandleVerifyAuditEvent_InvalidPath(t *testing.T) {handler.HandleVerifyAuditEvent(rec, req)- if rec.Code != http.StatusNotFound {- t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)}}@@ -120,6 +119,7 @@ func TestHandleVerifyAuditEvent_NotPersistent(t *testing.T) {handler := NewAuditHandlers()req := httptest.NewRequest(http.MethodGet, "/api/audit/abc/verify", nil)+ req.SetPathValue("id", "abc")rec := httptest.NewRecorder()handler.HandleVerifyAuditEvent(rec, req)@@ -145,6 +145,7 @@ func TestHandleVerifyAuditEvent_NoVerifier(t *testing.T) {handler := NewAuditHandlers()req := httptest.NewRequest(http.MethodGet, "/api/audit/abc/verify", nil)+ req.SetPathValue("id", "abc")rec := httptest.NewRecorder()handler.HandleVerifyAuditEvent(rec, req)@@ -159,6 +160,7 @@ func TestHandleVerifyAuditEvent_NotFound(t *testing.T) {handler := NewAuditHandlers()req := httptest.NewRequest(http.MethodGet, "/api/audit/abc/verify", nil)+ req.SetPathValue("id", "abc")rec := httptest.NewRecorder()handler.HandleVerifyAuditEvent(rec, req)@@ -176,6 +178,7 @@ func TestHandleVerifyAuditEvent_Verified(t *testing.T) {handler := NewAuditHandlers()req := httptest.NewRequest(http.MethodGet, "/api/audit/abc/verify", nil)+ req.SetPathValue("id", "abc")rec := httptest.NewRecorder()handler.HandleVerifyAuditEvent(rec, req)@@ -204,6 +207,7 @@ func TestHandleVerifyAuditEvent_Failed(t *testing.T) {handler := NewAuditHandlers()req := httptest.NewRequest(http.MethodGet, "/api/audit/abc/verify", nil)+ req.SetPathValue("id", "abc")rec := httptest.NewRecorder()handler.HandleVerifyAuditEvent(rec, req)diff --git a/internal/api/auth.go b/internal/api/auth.goindex 08d06a31d6..bb03c01afa 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -14,6 +14,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log")@@ -421,12 +422,12 @@ func CheckAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request) boolreturn false}- // Store session persistently+ // Store session persistently (including username for restart survival)userAgent := r.Header.Get("User-Agent")clientIP := GetClientIP(r)- GetSessionStore().CreateSession(token, 24*time.Hour, userAgent, clientIP)+ GetSessionStore().CreateSession(token, 24*time.Hour, userAgent, clientIP, parts[0])- // Track session for user+ // Track session for user (in-memory for fast lookups)TrackUserSession(parts[0], token)// Generate CSRF token@@ -621,7 +622,7 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc}// RequirePermission middleware checks for authentication and specific RBAC permissions-func RequirePermission(cfg *config.Config, authorizer internalauth.Authorizer, action string, resource string, next http.HandlerFunc) http.HandlerFunc {+func RequirePermission(cfg *config.Config, authorizer auth.Authorizer, action, resource string, next http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {// First check if user is authenticated (using RequireAdmin logic as base)if !CheckAuth(cfg, w, r) {@@ -688,29 +689,10 @@ func RequirePermission(cfg *config.Config, authorizer internalauth.Authorizer, a// Session-based (browser) requests bypass the scope check.func RequireScope(scope string, handler http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {- if scope == "" {- handler(w, r)+ if !ensureScope(w, r, scope) {return}-- record := getAPITokenRecordFromRequest(r)- if record == nil {- // Session-authenticated request- handler(w, r)- return- }-- if record.HasScope(scope) {- handler(w, r)- return- }-- log.Warn().- Str("token_id", record.ID).- Str("required_scope", scope).- Msg("API token missing required scope")-- respondMissingScope(w, scope)+ handler(w, r)}}diff --git a/internal/api/auth_helpers_test.go b/internal/api/auth_helpers_test.goindex a958271e3c..7c5a09f1d9 100644--- a/internal/api/auth_helpers_test.go+++ b/internal/api/auth_helpers_test.go@@ -345,7 +345,7 @@ func TestValidateSession_ValidToken(t *testing.T) {// Create a valid session with a generated tokenstore := GetSessionStore()token := generateSessionToken()- store.CreateSession(token, 24*time.Hour, "test-agent", "127.0.0.1")+ store.CreateSession(token, 24*time.Hour, "test-agent", "127.0.0.1", "testuser")result := ValidateSession(token)if !result {@@ -360,7 +360,7 @@ func TestValidateSession_ExpiredToken(t *testing.T) {// Create a session and manually expire itstore := GetSessionStore()token := generateSessionToken()- store.CreateSession(token, 24*time.Hour, "test-agent", "127.0.0.1")+ store.CreateSession(token, 24*time.Hour, "test-agent", "127.0.0.1", "testuser")// Manually expire the session by modifying the storestore.mu.Lock()@@ -683,7 +683,7 @@ func TestCheckAuth_OIDCSessionValid(t *testing.T) {// Create a session and track it for a userstore := GetSessionStore()sessionToken := generateSessionToken()- store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1")+ store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1", "testuser")TrackUserSession("oidcuser", sessionToken)cfg := &config.Config{@@ -740,7 +740,7 @@ func TestCheckAuth_SessionCookieValid(t *testing.T) {// Create a sessionstore := GetSessionStore()sessionToken := generateSessionToken()- store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1")+ store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1", "testuser")cfg := &config.Config{AuthUser: "testuser",@@ -766,7 +766,7 @@ func TestCheckAuth_SessionCookieExpired(t *testing.T) {// Create and expire a sessionstore := GetSessionStore()sessionToken := generateSessionToken()- store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1")+ store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1", "testuser")// Manually expire the sessionstore.mu.Lock()@@ -817,7 +817,7 @@ func TestCheckAuth_ValidSessionWithSlidingExpiration(t *testing.T) {store := GetSessionStore()sessionToken := generateSessionToken()- store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1")+ store.CreateSession(sessionToken, 24*time.Hour, "test-agent", "127.0.0.1", "testuser")cfg := &config.Config{// No auth configured, so session alone should workdiff --git a/internal/api/oidc_handlers.go b/internal/api/oidc_handlers.goindex aae996c445..11ff70d8e5 100644--- a/internal/api/oidc_handlers.go+++ b/internal/api/oidc_handlers.go@@ -269,7 +269,10 @@ func (r *Router) handleOIDCCallback(w http.ResponseWriter, req *http.Request) {Msg("Auto-assigning roles based on OIDC group mapping")if err := authManager.UpdateUserRoles(username, rolesToAssign); err != nil {log.Error().Err(err).Str("user", username).Msg("Failed to auto-assign OIDC roles")+ LogAuditEvent("oidc_role_assignment", username, GetClientIP(req), req.URL.Path, false, "Failed to auto-assign roles: "+strings.Join(rolesToAssign, ", "))// We don't fail the login here, but log the error+ } else {+ LogAuditEvent("oidc_role_assignment", username, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))}}}diff --git a/internal/api/rbac_handlers.go b/internal/api/rbac_handlers.goindex c03a6476c5..c2c2f71c2e 100644--- a/internal/api/rbac_handlers.go+++ b/internal/api/rbac_handlers.go@@ -2,13 +2,21 @@ package apiimport ("encoding/json"+ "fmt""net/http"+ "regexp""strings""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/pkg/auth")+// validRoleID matches alphanumeric IDs with hyphens and underscores (1-64 chars)+var validRoleID = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)++// validUsername matches reasonable username formats (1-128 chars, alphanumeric, plus common chars)+var validUsername = regexp.MustCompile(`^[a-zA-Z0-9._@+-]{1,128}$`)+// RBACHandlers provides HTTP handlers for RBAC management.type RBACHandlers struct {config *config.Config@@ -31,6 +39,12 @@ func (h *RBACHandlers) HandleRoles(w http.ResponseWriter, r *http.Request) {id = strings.TrimPrefix(id, "/")id = strings.TrimSuffix(id, "/")+ // Validate role ID format if provided+ if id != "" && !validRoleID.MatchString(id) {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_role_id", "Invalid role ID format", nil)+ return+ }+switch r.Method {case http.MethodGet:if id == "" {@@ -54,15 +68,25 @@ func (h *RBACHandlers) HandleRoles(w http.ResponseWriter, r *http.Request) {writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "POST is for creating roles; do not include an ID in the path", nil)return}++ // Limit request body size+ r.Body = http.MaxBytesReader(w, r.Body, 64*1024) // 64KB max+var role auth.Roleif err := json.NewDecoder(r.Body).Decode(&role); err != nil {writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid role data", nil)return}+ // Validate role ID in body+ if role.ID != "" && !validRoleID.MatchString(role.ID) {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_role_id", "Invalid role ID format", nil)+ return+ }+if err := manager.SaveRole(role); err != nil {- LogAuditEvent("role_create_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, "Failed to create role "+role.ID+": "+err.Error())- writeErrorResponse(w, http.StatusInternalServerError, "save_failed", err.Error(), nil)+ LogAuditEvent("role_create_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, fmt.Sprintf("Failed to create role %s", role.ID))+ writeErrorResponse(w, http.StatusInternalServerError, "save_failed", "Failed to save role", nil)return}@@ -71,6 +95,9 @@ func (h *RBACHandlers) HandleRoles(w http.ResponseWriter, r *http.Request) {json.NewEncoder(w).Encode(role)case http.MethodPut:+ // Limit request body size+ r.Body = http.MaxBytesReader(w, r.Body, 64*1024) // 64KB max+var role auth.Roleif err := json.NewDecoder(r.Body).Decode(&role); err != nil {writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid role data", nil)@@ -81,9 +108,15 @@ func (h *RBACHandlers) HandleRoles(w http.ResponseWriter, r *http.Request) {role.ID = id}+ // Validate role ID+ if role.ID != "" && !validRoleID.MatchString(role.ID) {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_role_id", "Invalid role ID format", nil)+ return+ }+if err := manager.SaveRole(role); err != nil {- LogAuditEvent("role_update_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, "Failed to update role "+role.ID+": "+err.Error())- writeErrorResponse(w, http.StatusInternalServerError, "save_failed", err.Error(), nil)+ LogAuditEvent("role_update_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, fmt.Sprintf("Failed to update role %s", role.ID))+ writeErrorResponse(w, http.StatusInternalServerError, "save_failed", "Failed to save role", nil)return}@@ -98,8 +131,8 @@ func (h *RBACHandlers) HandleRoles(w http.ResponseWriter, r *http.Request) {}if err := manager.DeleteRole(id); err != nil {- LogAuditEvent("role_delete_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, "Failed to delete role "+id+": "+err.Error())- writeErrorResponse(w, http.StatusInternalServerError, "delete_failed", err.Error(), nil)+ LogAuditEvent("role_delete_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, fmt.Sprintf("Failed to delete role %s", id))+ writeErrorResponse(w, http.StatusInternalServerError, "delete_failed", "Failed to delete role", nil)return}@@ -146,8 +179,17 @@ func (h *RBACHandlers) HandleUserRoleActions(w http.ResponseWriter, r *http.Requ}username := parts[0]+ // Validate username format to prevent injection+ if !validUsername.MatchString(username) {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_username", "Invalid username format", nil)+ return+ }+switch r.Method {case http.MethodPut, http.MethodPost:+ // Limit request body size+ r.Body = http.MaxBytesReader(w, r.Body, 64*1024) // 64KB max+var req struct {RoleIDs []string `json:"roleIds"`}@@ -156,9 +198,17 @@ func (h *RBACHandlers) HandleUserRoleActions(w http.ResponseWriter, r *http.Requreturn}+ // Validate all role IDs+ for _, roleID := range req.RoleIDs {+ if !validRoleID.MatchString(roleID) {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_role_id", fmt.Sprintf("Invalid role ID format: %s", roleID), nil)+ return+ }+ }+if err := manager.UpdateUserRoles(username, req.RoleIDs); err != nil {- LogAuditEvent("user_roles_update_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, "Failed to update roles for user "+username+": "+err.Error())- writeErrorResponse(w, http.StatusInternalServerError, "update_failed", err.Error(), nil)+ LogAuditEvent("user_roles_update_failed", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false, fmt.Sprintf("Failed to update roles for user %s", username))+ writeErrorResponse(w, http.StatusInternalServerError, "update_failed", "Failed to update user roles", nil)return}diff --git a/internal/api/reporting_handlers.go b/internal/api/reporting_handlers.goindex 4477e3251d..07ca5bb89b 100644--- a/internal/api/reporting_handlers.go+++ b/internal/api/reporting_handlers.go@@ -3,11 +3,16 @@ package apiimport ("fmt""net/http"+ "regexp"+ "strings""time""github.com/rcourtman/pulse-go-rewrite/pkg/reporting")+// validResourceID matches safe resource identifiers for filenames+var validResourceID = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)+// ReportingHandlers handles reporting-related requeststype ReportingHandlers struct{}@@ -25,7 +30,7 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.engine := reporting.GetEngine()if engine == nil {- http.Error(w, "Reporting engine not initialized", http.StatusInternalServerError)+ writeErrorResponse(w, http.StatusInternalServerError, "engine_unavailable", "Reporting engine not initialized", nil)return}@@ -35,10 +40,26 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.format = reporting.FormatPDF}+ // Validate format is one of known values+ if format != reporting.FormatPDF && format != reporting.FormatCSV {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_format", "Format must be 'pdf' or 'csv'", nil)+ return+ }+resourceType := q.Get("resourceType")resourceID := q.Get("resourceId")if resourceType == "" || resourceID == "" {- http.Error(w, "resourceType and resourceId are required", http.StatusBadRequest)+ writeErrorResponse(w, http.StatusBadRequest, "missing_params", "resourceType and resourceId are required", nil)+ return+ }++ // Validate resourceType and resourceID format to prevent injection in filename+ if !validResourceID.MatchString(resourceType) || len(resourceType) > 64 {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_resource_type", "Invalid resourceType format", nil)+ return+ }+ if !validResourceID.MatchString(resourceID) || len(resourceID) > 128 {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_resource_id", "Invalid resourceId format", nil)return}@@ -71,13 +92,30 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.data, contentType, err := engine.Generate(req)if err != nil {- http.Error(w, fmt.Sprintf("Failed to generate report: %v", err), http.StatusInternalServerError)+ writeErrorResponse(w, http.StatusInternalServerError, "generation_failed", "Failed to generate report", nil)return}w.Header().Set("Content-Type", contentType)- // Suggest a filename- filename := fmt.Sprintf("report-%s-%s.%s", resourceID, time.Now().Format("20060102"), format)+ // Build safe filename - sanitize resourceID to prevent header injection+ safeResourceID := sanitizeFilename(resourceID)+ filename := fmt.Sprintf("report-%s-%s.%s", safeResourceID, time.Now().Format("20060102"), format)w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))w.Write(data)}++// sanitizeFilename removes or replaces characters that could cause issues in filenames or headers+func sanitizeFilename(s string) string {+ // Remove any characters that could break Content-Disposition header+ s = strings.ReplaceAll(s, "\"", "")+ s = strings.ReplaceAll(s, "\\", "")+ s = strings.ReplaceAll(s, "/", "-")+ s = strings.ReplaceAll(s, "\r", "")+ s = strings.ReplaceAll(s, "\n", "")++ // Limit length+ if len(s) > 64 {+ s = s[:64]+ }+ return s+}diff --git a/internal/api/router.go b/internal/api/router.goindex df804182d9..73dd4a5df6 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -39,7 +39,6 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rcourtman/pulse-go-rewrite/internal/websocket""github.com/rcourtman/pulse-go-rewrite/pkg/auth"- internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log")@@ -72,7 +71,7 @@ type Router struct {persistence *config.ConfigPersistenceoidcMu sync.MutexoidcService *OIDCService- authorizer internalauth.Authorizer+ authorizer auth.Authorizerwrapped http.HandlerserverVersion stringprojectRoot string@@ -145,7 +144,7 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, wsHub *websocketexportLimiter: NewRateLimiter(5, 1*time.Minute), // 5 attempts per minutedownloadLimiter: NewRateLimiter(60, 1*time.Minute), // downloads/installers per minute per IPpersistence: config.NewConfigPersistence(cfg.DataPath),- authorizer: internalauth.GetAuthorizer(),+ authorizer: auth.GetAuthorizer(),serverVersion: strings.TrimSpace(serverVersion),projectRoot: projectRoot,checksumCache: make(map[string]checksumCacheEntry),@@ -153,12 +152,13 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, wsHub *websocket// Sync the configured admin user to the authorizer (if supported)if cfg.AuthUser != "" {- internalauth.SetAdminUser(cfg.AuthUser)+ auth.SetAdminUser(cfg.AuthUser)}r.initializeBootstrapToken()r.setupRoutes()+ log.Debug().Msg("Routes registered successfully")// Start forwarding update progress to WebSocketgo r.forwardUpdateProgress()@@ -506,8 +506,9 @@ func (r *Router) setupRoutes() {// Audit log routes (Enterprise feature)auditHandlers := NewAuditHandlers()- r.mux.HandleFunc("/api/audit", RequirePermission(r.config, r.authorizer, internalauth.ActionRead, internalauth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureAuditLogging, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListAuditEvents))))- r.mux.HandleFunc("/api/audit/", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureAuditLogging, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleVerifyAuditEvent))))+ r.mux.HandleFunc("GET /api/audit", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureAuditLogging, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListAuditEvents))))+ r.mux.HandleFunc("GET /api/audit/", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureAuditLogging, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListAuditEvents))))+ r.mux.HandleFunc("GET /api/audit/{id}/verify", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureAuditLogging, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleVerifyAuditEvent))))// RBAC routes (Phase 2 - Enterprise feature)r.mux.HandleFunc("/api/admin/roles", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureRBAC, rbacHandlers.HandleRoles)))@@ -535,7 +536,7 @@ func (r *Router) setupRoutes() {r.mux.HandleFunc("/api/security/oidc", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.handleOIDCConfig)))r.mux.HandleFunc("/api/oidc/login", r.handleOIDCLogin)r.mux.HandleFunc(config.DefaultOIDCCallbackPath, r.handleOIDCCallback)- r.mux.HandleFunc("/api/security/tokens", RequirePermission(r.config, r.authorizer, internalauth.ActionAdmin, internalauth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {+ r.mux.HandleFunc("/api/security/tokens", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {switch req.Method {case http.MethodGet:if !ensureScope(w, req, config.ScopeSettingsRead) {@@ -551,7 +552,7 @@ func (r *Router) setupRoutes() {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}}))- r.mux.HandleFunc("/api/security/tokens/", RequirePermission(r.config, r.authorizer, internalauth.ActionAdmin, internalauth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {+ r.mux.HandleFunc("/api/security/tokens/", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {if !ensureScope(w, req, config.ScopeSettingsWrite) {return}@@ -1209,7 +1210,7 @@ func (r *Router) setupRoutes() {}// Fall back to legacy single token if setif r.config.APIToken != "" {- return internalauth.CompareAPIToken(token, r.config.APIToken)+ return auth.CompareAPIToken(token, r.config.APIToken)}return false})@@ -1251,10 +1252,10 @@ func (r *Router) setupRoutes() {})}}- r.mux.HandleFunc("/api/settings/ai", RequirePermission(r.config, r.authorizer, internalauth.ActionRead, internalauth.ResourceSettings, RequireScope(config.ScopeSettingsRead, r.aiSettingsHandler.HandleGetAISettings)))- r.mux.HandleFunc("/api/settings/ai/update", RequirePermission(r.config, r.authorizer, internalauth.ActionWrite, internalauth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleUpdateAISettings)))- r.mux.HandleFunc("/api/ai/test", RequirePermission(r.config, r.authorizer, internalauth.ActionWrite, internalauth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleTestAIConnection)))- r.mux.HandleFunc("/api/ai/test/{provider}", RequirePermission(r.config, r.authorizer, internalauth.ActionWrite, internalauth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleTestProvider)))+ r.mux.HandleFunc("/api/settings/ai", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceSettings, RequireScope(config.ScopeSettingsRead, r.aiSettingsHandler.HandleGetAISettings)))+ r.mux.HandleFunc("/api/settings/ai/update", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleUpdateAISettings)))+ r.mux.HandleFunc("/api/ai/test", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleTestAIConnection)))+ r.mux.HandleFunc("/api/ai/test/{provider}", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleTestProvider)))r.mux.HandleFunc("/api/ai/models", RequireAuth(r.config, r.aiSettingsHandler.HandleListModels))r.mux.HandleFunc("/api/ai/execute", RequireAuth(r.config, r.aiSettingsHandler.HandleExecute))r.mux.HandleFunc("/api/ai/execute/stream", RequireAuth(r.config, r.aiSettingsHandler.HandleExecuteStream))@@ -1976,13 +1977,44 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {SecurityHeadersWithConfig(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {// Add CORS headers if configuredif r.config.AllowedOrigins != "" {- w.Header().Set("Access-Control-Allow-Origin", r.config.AllowedOrigins)- w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")- w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Token, X-CSRF-Token, X-Setup-Token")- w.Header().Set("Access-Control-Expose-Headers", "X-CSRF-Token, X-Authenticated-User, X-Auth-Method")- // Allow credentials when origin is specific (not *)- if r.config.AllowedOrigins != "*" {- w.Header().Set("Access-Control-Allow-Credentials", "true")+ reqOrigin := req.Header.Get("Origin")+ allowedOrigin := ""++ if r.config.AllowedOrigins == "*" {+ allowedOrigin = "*"+ } else if reqOrigin != "" {+ // Parse comma-separated origins and check for match+ origins := strings.Split(r.config.AllowedOrigins, ",")+ for _, o := range origins {+ o = strings.TrimSpace(o)+ if o == "" {+ continue+ }+ if o == reqOrigin {+ allowedOrigin = o+ break+ }+ }+ } else {+ // No Origin header (same-origin or direct request)+ // Set to first allowed origin for simple responses, though not strictly required for same-origin+ origins := strings.Split(r.config.AllowedOrigins, ",")+ if len(origins) > 0 {+ allowedOrigin = strings.TrimSpace(origins[0])+ }+ }++ if allowedOrigin != "" {+ w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")+ w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Token, X-CSRF-Token, X-Setup-Token")+ w.Header().Set("Access-Control-Expose-Headers", "X-CSRF-Token, X-Authenticated-User, X-Auth-Method")+ // Allow credentials when origin is specific (not *)+ if allowedOrigin != "*" {+ w.Header().Set("Access-Control-Allow-Credentials", "true")+ // Must add Vary: Origin when Origin is used to decide the response+ w.Header().Add("Vary", "Origin")+ }}}@@ -2217,6 +2249,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {// Check if this is an API or WebSocket routelog.Debug().Str("path", req.URL.Path).Msg("Routing request")+if strings.HasPrefix(req.URL.Path, "/api/") ||strings.HasPrefix(req.URL.Path, "/ws") ||strings.HasPrefix(req.URL.Path, "/socket.io/") ||@@ -2452,7 +2485,7 @@ func isRequestAuthenticated(cfg *config.Config, req *http.Request) bool {if authHeader := req.Header.Get("Authorization"); strings.HasPrefix(authHeader, prefix) {if decoded, err := base64.StdEncoding.DecodeString(authHeader[len(prefix):]); err == nil {if parts := strings.SplitN(string(decoded), ":", 2); len(parts) == 2 {- if parts[0] == cfg.AuthUser && internalauth.CheckPasswordHash(parts[1], cfg.AuthPass) {+ if parts[0] == cfg.AuthUser && auth.CheckPasswordHash(parts[1], cfg.AuthPass) {return true}}@@ -2542,7 +2575,7 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)}// Validate new password complexity- if err := internalauth.ValidatePasswordComplexity(changeReq.NewPassword); err != nil {+ if err := auth.ValidatePasswordComplexity(changeReq.NewPassword); err != nil {writeErrorResponse(w, http.StatusBadRequest, "invalid_password",err.Error(), nil)return@@ -2578,7 +2611,7 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)username = parts[0]useAuthHeader = true// Verify the password from the header matches- if !internalauth.CheckPasswordHash(parts[1], r.config.AuthPass) {+ if !auth.CheckPasswordHash(parts[1], r.config.AuthPass) {log.Warn().Str("ip", req.RemoteAddr).Str("username", username).@@ -2597,7 +2630,7 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)// If we didn't use the auth header, or need to double-check, verify from JSON bodyif !useAuthHeader || changeReq.CurrentPassword != "" {// Verify current password from JSON body- if !internalauth.CheckPasswordHash(changeReq.CurrentPassword, r.config.AuthPass) {+ if !auth.CheckPasswordHash(changeReq.CurrentPassword, r.config.AuthPass) {log.Warn().Str("ip", req.RemoteAddr).Str("username", username).@@ -2609,7 +2642,7 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)}// Hash the new password before storing- hashedPassword, err := internalauth.HashPassword(changeReq.NewPassword)+ hashedPassword, err := auth.HashPassword(changeReq.NewPassword)if err != nil {log.Error().Err(err).Msg("Failed to hash new password")writeErrorResponse(w, http.StatusInternalServerError, "hash_error",@@ -2826,7 +2859,7 @@ func (r *Router) establishSession(w http.ResponseWriter, req *http.Request, useruserAgent := req.Header.Get("User-Agent")clientIP := GetClientIP(req)- GetSessionStore().CreateSession(token, 24*time.Hour, userAgent, clientIP)+ GetSessionStore().CreateSession(token, 24*time.Hour, userAgent, clientIP, username)if username != "" {TrackUserSession(username, token)@@ -2867,8 +2900,8 @@ func (r *Router) establishOIDCSession(w http.ResponseWriter, req *http.Request,userAgent := req.Header.Get("User-Agent")clientIP := GetClientIP(req)- // Create session with OIDC tokens- GetSessionStore().CreateOIDCSession(token, 24*time.Hour, userAgent, clientIP, oidcTokens)+ // Create session with OIDC tokens (including username for restart survival)+ GetSessionStore().CreateOIDCSession(token, 24*time.Hour, userAgent, clientIP, username, oidcTokens)if username != "" {TrackUserSession(username, token)@@ -2963,7 +2996,7 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {}// Verify credentials- if loginReq.Username == r.config.AuthUser && internalauth.CheckPasswordHash(loginReq.Password, r.config.AuthPass) {+ if loginReq.Username == r.config.AuthUser && auth.CheckPasswordHash(loginReq.Password, r.config.AuthPass) {// Clear failed login attemptsClearFailedLogins(loginReq.Username)ClearFailedLogins(clientIP)@@ -2976,15 +3009,15 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {return}- // Store session persistently with appropriate duration+ // Store session persistently with appropriate duration (including username for restart survival)userAgent := req.Header.Get("User-Agent")sessionDuration := 24 * time.Hourif loginReq.RememberMe {sessionDuration = 30 * 24 * time.Hour // 30 days}- GetSessionStore().CreateSession(token, sessionDuration, userAgent, clientIP)+ GetSessionStore().CreateSession(token, sessionDuration, userAgent, clientIP, loginReq.Username)- // Track session for user+ // Track session for user (in-memory for fast lookups)TrackUserSession(loginReq.Username, token)// Generate CSRF token@@ -4842,7 +4875,7 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, reqname = fmt.Sprintf("Docker host: %s", displayName)}- rawToken, err := internalauth.GenerateAPIToken()+ rawToken, err := auth.GenerateAPIToken()if err != nil {log.Error().Err(err).Msg("Failed to generate docker migration token")writeErrorResponse(w, http.StatusInternalServerError, "token_generation_failed", "Failed to generate API token", nil)diff --git a/internal/api/security.go b/internal/api/security.goindex 0823df904b..f9cebf90a5 100644--- a/internal/api/security.go+++ b/internal/api/security.go@@ -506,16 +506,25 @@ func TrackUserSession(user, sessionID string) {// GetSessionUsername returns the username associated with a session IDfunc GetSessionUsername(sessionID string) string {+ // First check in-memory mapsessionsMu.RLock()- defer sessionsMu.RUnlock()-for user, sessions := range allSessions {for _, sid := range sessions {if sid == sessionID {+ sessionsMu.RUnlock()return user}}}+ sessionsMu.RUnlock()++ // Fall back to persisted username in session store (survives restarts)+ if session := GetSessionStore().GetSession(sessionID); session != nil && session.Username != "" {+ // Re-populate in-memory map for faster future lookups+ TrackUserSession(session.Username, sessionID)+ return session.Username+ }+return ""}diff --git a/internal/api/session_oidc_test.go b/internal/api/session_oidc_test.goindex ebdb5fd884..bd465da7be 100644--- a/internal/api/session_oidc_test.go+++ b/internal/api/session_oidc_test.go@@ -26,7 +26,7 @@ func TestCreateOIDCSession(t *testing.T) {ClientID: "test-client-id",}- store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", oidcInfo)+ store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", "testuser", oidcInfo)// Verify session was createdif !store.ValidateSession(token) {@@ -74,7 +74,7 @@ func TestUpdateOIDCTokens(t *testing.T) {ClientID: "test-client-id",}- store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", oidcInfo)+ store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", "testuser", oidcInfo)// Update the tokens (simulating a refresh)newExpiry := time.Now().Add(2 * time.Hour)@@ -112,7 +112,7 @@ func TestOIDCSessionPersistence(t *testing.T) {// Create session in first store instancestore1 := NewSessionStore(tmpDir)- store1.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", oidcInfo)+ store1.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", "testuser", oidcInfo)// Verify file was writtensessionFile := filepath.Join(tmpDir, "sessions.json")@@ -149,7 +149,7 @@ func TestCreateOIDCSession_NilTokenInfo(t *testing.T) {// Create OIDC session with nil token info (no refresh token available)token := "test-session-no-refresh"- store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", nil)+ store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", "testuser", nil)// Verify session was createdif !store.ValidateSession(token) {@@ -183,7 +183,7 @@ func TestInvalidateSession(t *testing.T) {ClientID: "test-client-id",}- store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", oidcInfo)+ store.CreateOIDCSession(token, 24*time.Hour, "TestAgent", "127.0.0.1", "testuser", oidcInfo)// Verify session existsif !store.ValidateSession(token) {diff --git a/internal/api/session_store.go b/internal/api/session_store.goindex 0e7acdeda9..e12fd86d92 100644--- a/internal/api/session_store.go+++ b/internal/api/session_store.go@@ -28,6 +28,7 @@ func sessionHash(token string) string {type sessionPersisted struct {Key string `json:"key"`+ Username string `json:"username,omitempty"`ExpiresAt time.Time `json:"expires_at"`CreatedAt time.Time `json:"created_at"`UserAgent string `json:"user_agent,omitempty"`@@ -43,6 +44,7 @@ type sessionPersisted struct {// SessionData represents a user sessiontype SessionData struct {+ Username string `json:"username,omitempty"` // The authenticated userExpiresAt time.Time `json:"expires_at"`CreatedAt time.Time `json:"created_at"`UserAgent string `json:"user_agent,omitempty"`@@ -89,12 +91,13 @@ func (s *SessionStore) backgroundWorker() {}// CreateSession creates a new session-func (s *SessionStore) CreateSession(token string, duration time.Duration, userAgent, ip string) {+func (s *SessionStore) CreateSession(token string, duration time.Duration, userAgent, ip, username string) {s.mu.Lock()defer s.mu.Unlock()key := sessionHash(token)s.sessions[key] = &SessionData{+ Username: username,ExpiresAt: time.Now().Add(duration),CreatedAt: time.Now(),UserAgent: userAgent,@@ -115,12 +118,13 @@ type OIDCTokenInfo struct {}// CreateOIDCSession creates a new session with OIDC token information-func (s *SessionStore) CreateOIDCSession(token string, duration time.Duration, userAgent, ip string, oidc *OIDCTokenInfo) {+func (s *SessionStore) CreateOIDCSession(token string, duration time.Duration, userAgent, ip, username string, oidc *OIDCTokenInfo) {s.mu.Lock()defer s.mu.Unlock()key := sessionHash(token)session := &SessionData{+ Username: username,ExpiresAt: time.Now().Add(duration),CreatedAt: time.Now(),UserAgent: userAgent,@@ -279,6 +283,7 @@ func (s *SessionStore) saveUnsafe() {for key, session := range s.sessions {persisted = append(persisted, sessionPersisted{Key: key,+ Username: session.Username,ExpiresAt: session.ExpiresAt,CreatedAt: session.CreatedAt,UserAgent: session.UserAgent,@@ -335,6 +340,7 @@ func (s *SessionStore) load() {continue}s.sessions[entry.Key] = &SessionData{+ Username: entry.Username,ExpiresAt: entry.ExpiresAt,CreatedAt: entry.CreatedAt,UserAgent: entry.UserAgent,diff --git a/internal/api/session_store_test.go b/internal/api/session_store_test.goindex 3d7b1c1db0..01aa13c75d 100644--- a/internal/api/session_store_test.go+++ b/internal/api/session_store_test.go@@ -133,7 +133,7 @@ func TestSessionStore_CreateAndValidate(t *testing.T) {duration := time.Hour// Create session- store.CreateSession(token, duration, "TestAgent", "127.0.0.1")+ store.CreateSession(token, duration, "TestAgent", "127.0.0.1", "testuser")// Validate sessionif !store.ValidateSession(token) {@@ -207,7 +207,7 @@ func TestSessionStore_DeleteSession(t *testing.T) {token := "delete-me-token"// Create session- store.CreateSession(token, time.Hour, "", "")+ store.CreateSession(token, time.Hour, "", "", "testuser")// Verify existsif !store.ValidateSession(token) {@@ -234,7 +234,7 @@ func TestSessionStore_ValidateAndExtendSession(t *testing.T) {duration := time.Hour// Create session- store.CreateSession(token, duration, "", "")+ store.CreateSession(token, duration, "", "", "testuser")// Get original expirystore.mu.RLock()@@ -343,7 +343,7 @@ func TestSessionStore_MultipleSessions(t *testing.T) {// Create multiple sessionsfor _, token := range tokens {- store.CreateSession(token, time.Hour, "Agent-"+token, "")+ store.CreateSession(token, time.Hour, "Agent-"+token, "", "testuser")}// All should be valid@@ -379,7 +379,7 @@ func TestSessionStore_Persistence(t *testing.T) {}token := "persistent-token"- store1.CreateSession(token, time.Hour, "PersistAgent", "10.0.0.1")+ store1.CreateSession(token, time.Hour, "PersistAgent", "10.0.0.1", "persistuser")// Verify file was createdsessionsFile := filepath.Join(tmpDir, "sessions.json")diff --git a/internal/license/features.go b/internal/license/features.goindex 7b2720627a..0f68c033a6 100644--- a/internal/license/features.go+++ b/internal/license/features.go@@ -16,18 +16,18 @@ const (// Free tier features - MonitoringFeatureUpdateAlerts = "update_alerts" // Alerts for pending container/package updates (free feature)- // MSP tier features (FUTURE - not in v1 launch)- FeatureRBAC = "rbac" // Role-Based Access Control- FeatureMultiUser = "multi_user" // Multi-user (likely merged with RBAC)- FeatureWhiteLabel = "white_label" // Custom branding - NOT IMPLEMENTED YET- FeatureMultiTenant = "multi_tenant" // Multi-tenant - NOT IMPLEMENTED YET- FeatureUnlimited = "unlimited" // Unlimited instances (explicit for contracts)-- // Enterprise tier features+ // Pro tier features - Team & Compliance+ FeatureRBAC = "rbac" // Role-Based Access ControlFeatureAuditLogging = "audit_logging" // Persistent audit logs with signingFeatureSSO = "sso" // OIDC/SSO authentication (Basic)FeatureAdvancedSSO = "advanced_sso" // SAML, Multi-provider, Role MappingFeatureAdvancedReporting = "advanced_reporting" // PDF/CSV reporting engine++ // MSP/Enterprise tier features (for volume deals)+ FeatureMultiUser = "multi_user" // Multi-user (likely merged with RBAC)+ FeatureWhiteLabel = "white_label" // Custom branding - NOT IMPLEMENTED YET+ FeatureMultiTenant = "multi_tenant" // Multi-tenant - NOT IMPLEMENTED YET+ FeatureUnlimited = "unlimited" // Unlimited instances (for MSP/volume deals))// Tier represents a license tier.@@ -57,7 +57,10 @@ var TierFeatures = map[Tier][]string{FeatureAgentProfiles,FeatureUpdateAlerts,FeatureSSO,+ FeatureAdvancedSSO,FeatureRBAC,+ FeatureAuditLogging,+ FeatureAdvancedReporting,},TierProAnnual: {FeatureAIPatrol,@@ -67,7 +70,10 @@ var TierFeatures = map[Tier][]string{FeatureAgentProfiles,FeatureUpdateAlerts,FeatureSSO,+ FeatureAdvancedSSO,FeatureRBAC,+ FeatureAuditLogging,+ FeatureAdvancedReporting,},TierLifetime: {FeatureAIPatrol,@@ -77,7 +83,10 @@ var TierFeatures = map[Tier][]string{FeatureAgentProfiles,FeatureUpdateAlerts,FeatureSSO,+ FeatureAdvancedSSO,FeatureRBAC,+ FeatureAuditLogging,+ FeatureAdvancedReporting,},TierMSP: {FeatureAIPatrol,@@ -88,6 +97,10 @@ var TierFeatures = map[Tier][]string{FeatureUpdateAlerts,FeatureUnlimited,FeatureSSO,+ FeatureAdvancedSSO,+ FeatureRBAC,+ FeatureAuditLogging,+ FeatureAdvancedReporting,// Note: FeatureMultiUser, FeatureWhiteLabel, FeatureMultiTenant// are on the roadmap but NOT included until implemented},diff --git a/internal/license/license_test.go b/internal/license/license_test.goindex bb215dedbe..1332c8c356 100644--- a/internal/license/license_test.go+++ b/internal/license/license_test.go@@ -33,7 +33,8 @@ func TestTierHasFeature(t *testing.T) {{"enterprise has multi-user", TierEnterprise, FeatureMultiUser, true},{"enterprise has white-label", TierEnterprise, FeatureWhiteLabel, true},{"pro has Basic SSO", TierPro, FeatureSSO, true},- {"pro does not have Advanced SSO", TierPro, FeatureAdvancedSSO, false},+ {"pro has Advanced SSO", TierPro, FeatureAdvancedSSO, true},+ {"pro has audit logging", TierPro, FeatureAuditLogging, true},{"enterprise has Advanced SSO", TierEnterprise, FeatureAdvancedSSO, true},{"enterprise has audit logging", TierEnterprise, FeatureAuditLogging, true},{"enterprise has SSO", TierEnterprise, FeatureSSO, true},diff --git a/pkg/auth/rbac.go b/pkg/auth/rbac.goindex 86c331cdb2..d87c5aa343 100644--- a/pkg/auth/rbac.go+++ b/pkg/auth/rbac.go@@ -2,6 +2,7 @@ package authimport ("context"+ "sync""time")@@ -58,15 +59,23 @@ type Manager interface {GetUserPermissions(username string) []Permission}-var globalManager Manager+var (+ globalManager Manager+ managerMu sync.RWMutex+)// SetManager sets the global RBAC manager instance.+// This should be called during application initialization.func SetManager(m Manager) {+ managerMu.Lock()+ defer managerMu.Unlock()globalManager = m}// GetManager returns the global RBAC manager instance.func GetManager() Manager {+ managerMu.RLock()+ defer managerMu.RUnlock()return globalManager}diff --git a/pkg/server/server.go b/pkg/server/server.goindex c5382e9c74..1c236bd253 100644--- a/pkg/server/server.go+++ b/pkg/server/server.go@@ -34,7 +34,9 @@ var (// BusinessHooks allows enterprise features to hook into the server lifecycle.type BusinessHooks struct {- OnMonitorInitialized func(m *monitoring.Monitor)+ // OnMetricsStoreReady is called when the metrics store is initialized.+ // This allows enterprise features to access metrics for reporting.+ OnMetricsStoreReady func(store *metrics.Store)}var (@@ -122,21 +124,20 @@ func Run(ctx context.Context, version string) error {}// Trigger enterprise hooks if registered- var onMonitorInitialized func(*monitoring.Monitor)globalHooksMu.Lock()- if globalHooks.OnMonitorInitialized != nil {- onMonitorInitialized = globalHooks.OnMonitorInitialized- }+ onMetricsStoreReady := globalHooks.OnMetricsStoreReadyglobalHooksMu.Unlock()- if onMonitorInitialized != nil {+ if onMetricsStoreReady != nil {func() {defer func() {if r := recover(); r != nil {- log.Error().Interface("panic", r).Msg("Enterprise OnMonitorInitialized hook panicked")+ log.Error().Interface("panic", r).Msg("Enterprise OnMetricsStoreReady hook panicked")}}()- onMonitorInitialized(reloadableMonitor.GetMonitor())+ if store := reloadableMonitor.GetMonitor().GetMetricsStore(); store != nil {+ onMetricsStoreReady(store)+ }}()}diff --git a/scripts/hot-dev.sh b/scripts/hot-dev.shindex 96225f6ceb..2bfbd135ec 100755--- a/scripts/hot-dev.sh+++ b/scripts/hot-dev.sh@@ -1,4 +1,30 @@#!/bin/bash+# hot-dev.sh - Development server with hot-reload for Pulse+#+# This script runs a local development environment with:+# - Go backend with auto-rebuild on file changes (via inotifywait)+# - Vite frontend dev server with HMR+# - Automatic enterprise binary support when /opt/pulse-enterprise exists+#+# Environment Variables:+# HOT_DEV_USE_PROD_DATA=true Use /etc/pulse for data (sessions, config, etc.)+# HOT_DEV_USE_ENTERPRISE=true Build enterprise binary (default: true if available)+# PULSE_MOCK_MODE=true Use isolated mock data directory+# PULSE_DATA_DIR=/path Override data directory+# PULSE_DEV_API_PORT=7656 Backend API port (default: 7656)+# FRONTEND_DEV_PORT=5173 Frontend dev server port (default: 5173)+#+# Enterprise Mode:+# When /opt/pulse-enterprise exists and HOT_DEV_USE_ENTERPRISE is not "false",+# the script builds and runs the enterprise binary which includes:+# - SQLite-based persistent audit logging+# - RBAC (Role-Based Access Control)+# - HMAC event signing for tamper detection+#+# Usage:+# ./scripts/hot-dev.sh # Standard dev mode+# HOT_DEV_USE_PROD_DATA=true ./scripts/hot-dev.sh # Use production data+#set -euo pipefailSCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)@@ -59,7 +85,7 @@ load_env_file "${ROOT_DIR}/.env"load_env_file "${ROOT_DIR}/.env.local"load_env_file "${ROOT_DIR}/.env.dev"-FRONTEND_PORT=${FRONTEND_PORT:-${PORT:-7655}}+FRONTEND_PORT=${FRONTEND_PORT:-${PORT:-5173}}PORT=${PORT:-${FRONTEND_PORT}}# Detect LAN IP@@ -96,7 +122,20 @@ fi# Set specific allowed origin for CORS with credentials# Use the frontend dev URL so cross-port SSE requests work with auth cookies+# Added localhost and 127.0.0.1 by default for flexibility (both 7655 and 5173)ALLOWED_ORIGINS="http://${PULSE_DEV_API_HOST:-127.0.0.1}:${FRONTEND_DEV_PORT:-7655}"+ALLOWED_ORIGINS="${ALLOWED_ORIGINS},http://localhost:${FRONTEND_DEV_PORT:-7655},http://127.0.0.1:${FRONTEND_DEV_PORT:-7655}"+ALLOWED_ORIGINS="${ALLOWED_ORIGINS},http://localhost:5173,http://127.0.0.1:5173"++# Detect and add all system IPs (V4)+for ip in $(hostname -I); do+ if [[ "${ip}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ if [[ "${ip}" != "127.0.0.1" ]]; then+ ALLOWED_ORIGINS="${ALLOWED_ORIGINS},http://${ip}:${FRONTEND_DEV_PORT:-7655}"+ ALLOWED_ORIGINS="${ALLOWED_ORIGINS},http://${ip}:5173"+ fi+ fi+doneexport FRONTEND_PORT PORTexport FRONTEND_DEV_HOST FRONTEND_DEV_PORT@@ -233,7 +272,23 @@ cd "${ROOT_DIR}"mkdir -p internal/api/frontend-modern/disttouch internal/api/frontend-modern/dist/index.html-go build -o pulse ./cmd/pulse+# Check if enterprise module is available and use it for full audit logging support+ENTERPRISE_DIR="/opt/pulse-enterprise"+if [[ -d "${ENTERPRISE_DIR}" ]] && [[ ${HOT_DEV_USE_ENTERPRISE:-true} == "true" ]]; then+ log_info "Building enterprise binary (includes persistent audit logging)..."+ cd "${ENTERPRISE_DIR}"+ go build -buildvcs=false -o "${ROOT_DIR}/pulse" ./cmd/pulse-enterprise 2>/dev/null || {+ log_warn "Enterprise build failed, falling back to OSS binary"+ cd "${ROOT_DIR}"+ go build -o pulse ./cmd/pulse+ }+ cd "${ROOT_DIR}"+ # Set up audit directory for enterprise features+ export PULSE_AUDIT_DIR="${PULSE_DATA_DIR:-/etc/pulse}"+ log_info "Enterprise audit logging enabled (SQLite storage in ${PULSE_AUDIT_DIR})"+else+ go build -o pulse ./cmd/pulse+fiFRONTEND_PORT=${PULSE_DEV_API_PORT}PORT=${PULSE_DEV_API_PORT}