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(rbac): implement RBAC UI, OIDC group mapping, and API standard auth
rcourtman6ed1fdf80644
diff --git a/frontend-modern/src/api/rbac.ts b/frontend-modern/src/api/rbac.tsnew file mode 100644index 0000000000..793e8edad2--- /dev/null+++ b/frontend-modern/src/api/rbac.ts@@ -0,0 +1,29 @@+import { apiFetchJSON } from '@/utils/apiClient';+import type { Role, UserRoleAssignment, Permission } from '@/types/rbac';++export const RBACAPI = {+ // Roles+ getRoles: () => apiFetchJSON<Role[]>('/api/admin/roles'),+ getRole: (id: string) => apiFetchJSON<Role>(`/api/admin/roles/${id}`),+ saveRole: (role: Role) => {+ const method = role.createdAt ? 'PUT' : 'POST';+ const url = method === 'PUT' ? `/api/admin/roles/${role.id}` : '/api/admin/roles';+ return apiFetchJSON<Role>(url, {+ method,+ body: JSON.stringify(role),+ });+ },+ deleteRole: (id: string) => apiFetchJSON(`/api/admin/roles/${id}`, { method: 'DELETE' }),++ // User Assignments+ getUsers: () => apiFetchJSON<UserRoleAssignment[]>('/api/admin/users'),+ getUserAssignment: (username: string) => apiFetchJSON<UserRoleAssignment>(`/api/admin/users/${username}/roles`),+ updateUserRoles: (username: string, roleIds: string[]) =>+ apiFetchJSON(`/api/admin/users/${username}/roles`, {+ method: 'PUT',+ body: JSON.stringify({ roleIds }),+ }),++ getUserPermissions: (username: string) =>+ apiFetchJSON<Permission[]>(`/api/admin/users/${username}/permissions`),+};diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsxindex 0b861055c6..ea150dea6e 100644--- a/frontend-modern/src/components/Settings/AISettings.tsx+++ b/frontend-modern/src/components/Settings/AISettings.tsx@@ -8,7 +8,6 @@ import { formField, labelClass, controlClass } from '@/components/shared/Form';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import { AIAPI } from '@/api/ai';-import Sparkles from 'lucide-solid/icons/sparkles';import { isEnterprise, loadLicenseStatus } from '@/stores/license';import type { AISettings as AISettingsType, AIProvider, AuthMethod } from '@/types/ai';diff --git a/frontend-modern/src/components/Settings/AuditLogPanel.tsx b/frontend-modern/src/components/Settings/AuditLogPanel.tsxindex 681f09ed66..72806e3855 100644--- a/frontend-modern/src/components/Settings/AuditLogPanel.tsx+++ b/frontend-modern/src/components/Settings/AuditLogPanel.tsx@@ -17,8 +17,6 @@ import {} from '@/utils/localStorage';import { showSuccess, showWarning, showToast } from '@/utils/toast';import { isEnterprise, loadLicenseStatus } from '@/stores/license';-import Sparkles from 'lucide-solid/icons/sparkles';-import ExternalLink from 'lucide-solid/icons/external-link';interface AuditEvent {id: string;diff --git a/frontend-modern/src/components/Settings/OIDCPanel.tsx b/frontend-modern/src/components/Settings/OIDCPanel.tsxindex 3c9c3d8595..8dc1abc9d9 100644--- a/frontend-modern/src/components/Settings/OIDCPanel.tsx+++ b/frontend-modern/src/components/Settings/OIDCPanel.tsx@@ -7,8 +7,6 @@ import { formField, labelClass, controlClass, formHelpText } from '@/components/import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import { isEnterprise, loadLicenseStatus } from '@/stores/license';-import Sparkles from 'lucide-solid/icons/sparkles';-import ExternalLink from 'lucide-solid/icons/external-link';interface OIDCConfigResponse {enabled: boolean;@@ -24,6 +22,7 @@ interface OIDCConfigResponse {allowedDomains: string[];allowedEmails: string[];caBundle?: string;+ groupRoleMappings?: Record<string, string>;clientSecretSet: boolean;envOverrides?: Record<string, boolean>;defaultRedirect: string;@@ -36,6 +35,18 @@ const splitList = (input: string) =>.map((v) => v.trim()).filter(Boolean);+const mappingsToString = (mappings?: Record<string, string>) =>+ mappings ? Object.entries(mappings).map(([k, v]) => `${k}=${v}`).join(', ') : '';++const stringToMappings = (input: string) => {+ const result: Record<string, string> = {};+ splitList(input).forEach(pair => {+ const [k, v] = pair.split('=').map(s => s.trim());+ if (k && v) result[k] = v;+ });+ return result;+};+interface Props {onConfigUpdated?: (config: OIDCConfigResponse) => void;}@@ -59,6 +70,7 @@ export const OIDCPanel: Component<Props> = (props) => {allowedGroups: '',allowedDomains: '',allowedEmails: '',+ groupRoleMappings: '',caBundle: '',clientSecret: '',clearSecret: false,@@ -84,6 +96,7 @@ export const OIDCPanel: Component<Props> = (props) => {allowedGroups: '',allowedDomains: '',allowedEmails: '',+ groupRoleMappings: '',caBundle: '',clientSecret: '',clearSecret: false,@@ -104,6 +117,7 @@ export const OIDCPanel: Component<Props> = (props) => {allowedGroups: listToString(data.allowedGroups),allowedDomains: listToString(data.allowedDomains),allowedEmails: listToString(data.allowedEmails),+ groupRoleMappings: mappingsToString(data.groupRoleMappings),caBundle: data.caBundle || '',clientSecret: '',clearSecret: false,@@ -158,6 +172,7 @@ export const OIDCPanel: Component<Props> = (props) => {allowedGroups: splitList(form.allowedGroups),allowedDomains: splitList(form.allowedDomains),allowedEmails: splitList(form.allowedEmails),+ groupRoleMappings: stringToMappings(form.groupRoleMappings),caBundle: form.caBundle.trim(),};@@ -520,6 +535,20 @@ export const OIDCPanel: Component<Props> = (props) => {/><p class={formHelpText}>Optional allowlist of specific emails.</p></div>+ <div class={formField}>+ <label class={labelClass()}>Group role mappings</label>+ <textarea+ rows={2}+ value={form.groupRoleMappings}+ onInput={(event) => setForm('groupRoleMappings', event.currentTarget.value)}+ placeholder="admins=admin, operators=operator"+ class={controlClass('min-h-[70px]')}+ disabled={isEnvLocked() || saving()}+ />+ <p class={formHelpText}>+ Comma or space separated <code>group=roleId</code> pairs.+ </p>+ </div></div></Show></div>diff --git a/frontend-modern/src/components/Settings/RolesPanel.tsx b/frontend-modern/src/components/Settings/RolesPanel.tsxnew file mode 100644index 0000000000..375351d0ff--- /dev/null+++ b/frontend-modern/src/components/Settings/RolesPanel.tsx@@ -0,0 +1,381 @@+import { Component, createSignal, onMount, Show, For } from 'solid-js';+import { Card } from '@/components/shared/Card';+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 Plus from 'lucide-solid/icons/plus';+import Pencil from 'lucide-solid/icons/pencil';+import Trash2 from 'lucide-solid/icons/trash-2';+import Shield from 'lucide-solid/icons/shield';+import BadgeCheck from 'lucide-solid/icons/badge-check';+import X from 'lucide-solid/icons/x';++const ACTIONS = ['read', 'write', 'delete', 'admin', '*'];+const RESOURCES = ['settings', 'audit_logs', 'nodes', 'users', 'license', '*'];++export const RolesPanel: Component = () => {+ const [roles, setRoles] = createSignal<Role[]>([]);+ const [loading, setLoading] = createSignal(true);+ const [showModal, setShowModal] = createSignal(false);+ const [editingRole, setEditingRole] = createSignal<Role | null>(null);+ const [saving, setSaving] = createSignal(false);++ // Form state+ const [formId, setFormId] = createSignal('');+ const [formName, setFormName] = createSignal('');+ const [formDescription, setFormDescription] = createSignal('');+ const [formPermissions, setFormPermissions] = createSignal<Permission[]>([]);++ const loadRoles = async () => {+ setLoading(true);+ try {+ const data = await RBACAPI.getRoles();+ setRoles(data || []);+ } catch (err) {+ logger.error('Failed to load roles', err);+ notificationStore.error('Failed to load roles');+ } finally {+ setLoading(false);+ }+ };++ onMount(() => {+ loadLicenseStatus();+ loadRoles();+ });++ const handleCreate = () => {+ setEditingRole(null);+ setFormId('');+ setFormName('');+ setFormDescription('');+ setFormPermissions([{ action: 'read', resource: 'nodes' }]);+ setShowModal(true);+ };++ const handleEdit = (role: Role) => {+ if (role.isBuiltIn) return;+ setEditingRole(role);+ setFormId(role.id);+ setFormName(role.name);+ setFormDescription(role.description);+ setFormPermissions([...role.permissions]);+ setShowModal(true);+ };++ const handleDelete = async (role: Role) => {+ if (role.isBuiltIn) return;+ if (!confirm(`Are you sure you want to delete the role "${role.name}"?`)) return;++ try {+ await RBACAPI.deleteRole(role.id);+ notificationStore.success(`Role "${role.name}" deleted`);+ await loadRoles();+ } catch (err) {+ logger.error('Failed to delete role', err);+ notificationStore.error('Failed to delete role');+ }+ };++ const handleSave = async () => {+ const id = formId().trim().toLowerCase().replace(/\s+/g, '-');+ const name = formName().trim();+ if (!id || !name) {+ notificationStore.error('ID and Name are required');+ return;+ }++ setSaving(true);+ try {+ const role: Role = {+ id,+ name,+ description: formDescription(),+ permissions: formPermissions(),+ createdAt: editingRole()?.createdAt,+ };+ await RBACAPI.saveRole(role);+ notificationStore.success(`Role "${name}" saved`);+ setShowModal(false);+ await loadRoles();+ } catch (err) {+ logger.error('Failed to save role', err);+ notificationStore.error('Failed to save role');+ } finally {+ setSaving(false);+ }+ };++ const addPermission = () => {+ setFormPermissions([...formPermissions(), { action: 'read', resource: 'nodes' }]);+ };++ const removePermission = (index: number) => {+ const perms = [...formPermissions()];+ perms.splice(index, 1);+ setFormPermissions(perms);+ };++ const updatePermission = (index: number, field: keyof Permission, value: string) => {+ const perms = [...formPermissions()];+ perms[index] = { ...perms[index], [field]: value };+ setFormPermissions(perms);+ };++ return (+ <div class="space-y-6">+ <Card padding="lg" class="space-y-4">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-3">+ <div class="flex items-center justify-center w-10 h-10 rounded-lg bg-indigo-100 dark:bg-indigo-900/30">+ <Shield class="w-5 h-5 text-indigo-600 dark:text-indigo-400" />+ </div>+ <div>+ <h3 class="text-base font-semibold text-gray-900 dark:text-gray-100">Roles</h3>+ <p class="text-sm text-gray-600 dark:text-gray-400">Manage custom roles and view built-in roles</p>+ </div>+ </div>+ <button+ type="button"+ onClick={handleCreate}+ class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-700"+ >+ <Plus class="w-4 h-4" />+ New Role+ </button>+ </div>++ <Show when={!isEnterprise() && !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">+ <h4 class="text-base font-semibold text-gray-900 dark:text-white">Custom Roles (Pro)</h4>+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">+ Define granular permissions and custom access tiers for your team.+ </p>+ </div>+ <a+ href="https://pulse.sh/pro"+ target="_blank"+ rel="noopener noreferrer"+ class="px-5 py-2.5 text-sm font-semibold bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"+ >+ Upgrade to Pro+ </a>+ </div>+ </div>+ </Show>++ <Show when={loading()}>+ <div class="flex items-center justify-center py-8">+ <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-indigo-500" />+ </div>+ </Show>++ <Show when={!loading()}>+ <div class="overflow-x-auto">+ <table class="w-full text-sm">+ <thead>+ <tr class="border-b border-gray-200 dark:border-gray-700">+ <th class="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400">Role</th>+ <th class="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400">Permissions</th>+ <th class="text-right py-2 px-3 font-medium text-gray-600 dark:text-gray-400">Actions</th>+ </tr>+ </thead>+ <tbody>+ <For each={roles()}>+ {(role) => (+ <tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50">+ <td class="py-3 px-3">+ <div class="flex flex-col">+ <span class="font-medium text-gray-900 dark:text-gray-100 flex items-center gap-1">+ {role.name}+ <Show when={role.isBuiltIn}>+ <BadgeCheck class="w-4 h-4 text-blue-500" />+ </Show>+ </span>+ <span class="text-xs text-gray-500 dark:text-gray-400">{role.description}</span>+ </div>+ </td>+ <td class="py-3 px-3">+ <div class="flex flex-wrap gap-1">+ <For each={role.permissions}>+ {(perm) => (+ <span class="inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600 dark:bg-gray-800 dark:text-gray-400 border border-gray-200 dark:border-gray-700">+ {perm.action}:{perm.resource}+ </span>+ )}+ </For>+ </div>+ </td>+ <td class="py-3 px-3 text-right">+ <Show when={!role.isBuiltIn}>+ <div class="inline-flex items-center gap-1">+ <button+ type="button"+ onClick={() => handleEdit(role)}+ class="p-1.5 rounded-md text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 dark:hover:text-indigo-400 dark:hover:bg-indigo-900/30"+ title="Edit role"+ >+ <Pencil class="w-4 h-4" />+ </button>+ <button+ type="button"+ onClick={() => handleDelete(role)}+ class="p-1.5 rounded-md text-gray-500 hover:text-red-600 hover:bg-red-50 dark:hover:text-red-400 dark:hover:bg-red-900/30"+ title="Delete role"+ >+ <Trash2 class="w-4 h-4" />+ </button>+ </div>+ </Show>+ <Show when={role.isBuiltIn}>+ <span class="text-xs text-gray-400 italic">Read-only</span>+ </Show>+ </td>+ </tr>+ )}+ </For>+ </tbody>+ </table>+ </div>+ </Show>+ </Card>++ {/* Role Modal */}+ <Show when={showModal()}>+ <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">+ <div class="w-full max-w-2xl bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 mx-4">+ <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">+ <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">+ {editingRole() ? 'Edit Role' : 'New Role'}+ </h3>+ <button+ type="button"+ onClick={() => setShowModal(false)}+ class="p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:hover:text-gray-300 dark:hover:bg-gray-800"+ >+ <X class="w-5 h-5" />+ </button>+ </div>++ <div class="px-6 py-4 space-y-4 max-h-[70vh] overflow-y-auto">+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <div class="space-y-1">+ <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">+ Role ID+ </label>+ <input+ type="text"+ value={formId()}+ onInput={(e) => setFormId(e.currentTarget.value)}+ placeholder="e.g., custom-auditor"+ disabled={!!editingRole()}+ class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:focus:border-indigo-400 dark:focus:ring-indigo-800/60 disabled:opacity-50"+ />+ </div>+ <div class="space-y-1">+ <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">+ Role Name+ </label>+ <input+ type="text"+ value={formName()}+ onInput={(e) => setFormName(e.currentTarget.value)}+ placeholder="e.g., Custom Auditor"+ class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:focus:border-indigo-400 dark:focus:ring-indigo-800/60"+ />+ </div>+ </div>+ <div class="space-y-1">+ <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">+ Description+ </label>+ <input+ type="text"+ value={formDescription()}+ onInput={(e) => setFormDescription(e.currentTarget.value)}+ placeholder="Brief description of this role's purpose"+ class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:focus:border-indigo-400 dark:focus:ring-indigo-800/60"+ />+ </div>++ <div class="space-y-3 pt-2">+ <div class="flex items-center justify-between">+ <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">+ Permissions+ </label>+ <button+ type="button"+ onClick={addPermission}+ class="text-xs font-medium text-indigo-600 hover:text-indigo-700 dark:text-indigo-400 flex items-center gap-1"+ >+ <Plus class="w-3 h-3" /> Add Permission+ </button>+ </div>++ <div class="space-y-2">+ <For each={formPermissions()}>+ {(perm, index) => (+ <div class="flex items-center gap-2">+ <select+ value={perm.action}+ onChange={(e) => updatePermission(index(), 'action', e.currentTarget.value)}+ class="flex-1 rounded-lg border border-gray-300 bg-white px-2 py-1.5 text-sm text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"+ >+ <For each={ACTIONS}>+ {(action) => <option value={action}>{action}</option>}+ </For>+ </select>+ <span class="text-gray-400 text-sm">:</span>+ <select+ value={perm.resource}+ onChange={(e) => updatePermission(index(), 'resource', e.currentTarget.value)}+ class="flex-1 rounded-lg border border-gray-300 bg-white px-2 py-1.5 text-sm text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"+ >+ <For each={RESOURCES}>+ {(resource) => <option value={resource}>{resource}</option>}+ </For>+ </select>+ <button+ type="button"+ onClick={() => removePermission(index())}+ disabled={formPermissions().length <= 1}+ class="p-1.5 text-gray-400 hover:text-red-500 disabled:opacity-30"+ >+ <Trash2 class="w-4 h-4" />+ </button>+ </div>+ )}+ </For>+ </div>+ </div>+ </div>++ <div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">+ <button+ type="button"+ onClick={() => setShowModal(false)}+ class="rounded-lg px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={handleSave}+ disabled={saving() || !formName().trim()}+ class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {saving() ? 'Saving...' : editingRole() ? 'Update Role' : 'Create Role'}+ </button>+ </div>+ </div>+ </div>+ </Show>+ </div>+ );+};++export default RolesPanel;diff --git a/frontend-modern/src/components/Settings/Settings.tsx b/frontend-modern/src/components/Settings/Settings.tsxindex b68757cd5a..50025f49b0 100644--- a/frontend-modern/src/components/Settings/Settings.tsx+++ b/frontend-modern/src/components/Settings/Settings.tsx@@ -37,6 +37,8 @@ import { SecurityAuthPanel } from './SecurityAuthPanel';import { APIAccessPanel } from './APIAccessPanel';import { SecurityOverviewPanel } from './SecurityOverviewPanel';import AuditLogPanel from './AuditLogPanel';+import RolesPanel from './RolesPanel';+import UserAssignmentsPanel from './UserAssignmentsPanel';import {PveNodesTable,PbsNodesTable,@@ -62,6 +64,7 @@ import Activity from 'lucide-solid/icons/activity';import Loader from 'lucide-solid/icons/loader';import Network from 'lucide-solid/icons/network';import Monitor from 'lucide-solid/icons/monitor';+import Users from 'lucide-solid/icons/users';import Sliders from 'lucide-solid/icons/sliders-horizontal';import RefreshCw from 'lucide-solid/icons/refresh-cw';import Clock from 'lucide-solid/icons/clock';@@ -301,6 +304,8 @@ type SettingsTab =| 'security-overview'| 'security-auth'| 'security-sso'+ | 'security-roles'+ | 'security-users'| 'security-audit'| 'diagnostics'| 'updates';@@ -368,6 +373,14 @@ const SETTINGS_HEADER_META: Record<SettingsTab, { title: string; description: sttitle: 'Single Sign-On',description: 'Configure OIDC providers for enterprise authentication.',},+ 'security-roles': {+ title: 'Roles',+ description: 'Define custom roles and manage granular permissions for users and tokens.',+ },+ 'security-users': {+ title: 'User Access',+ description: 'Assign roles to users and view effective permissions across your infrastructure.',+ },'security-audit': {title: 'Audit Log',description: 'View security events, login attempts, and configuration changes.',@@ -447,6 +460,8 @@ const Settings: Component<SettingsProps> = (props) => {if (path.includes('/settings/security-overview')) return 'security-overview';if (path.includes('/settings/security-auth')) return 'security-auth';if (path.includes('/settings/security-sso')) return 'security-sso';+ if (path.includes('/settings/security-roles')) return 'security-roles';+ if (path.includes('/settings/security-users')) return 'security-users';if (path.includes('/settings/security-audit')) return 'security-audit';if (path.includes('/settings/security')) return 'security-overview';if (path.includes('/settings/diagnostics')) return 'diagnostics';@@ -1124,6 +1139,18 @@ const Settings: Component<SettingsProps> = (props) => {icon: Key,iconProps: { strokeWidth: 2 },},+ {+ id: 'security-roles',+ label: 'Roles',+ icon: Shield,+ iconProps: { strokeWidth: 2 },+ },+ {+ id: 'security-users',+ label: 'Users',+ icon: Users,+ iconProps: { strokeWidth: 2 },+ },{id: 'security-audit',label: 'Audit Log',@@ -3646,6 +3673,16 @@ const Settings: Component<SettingsProps> = (props) => {</div></Show>+ {/* Security Roles Tab */}+ <Show when={activeTab() === 'security-roles'}>+ <RolesPanel />+ </Show>++ {/* Security User Assignments Tab */}+ <Show when={activeTab() === 'security-users'}>+ <UserAssignmentsPanel />+ </Show>+{/* Security Audit Log Tab */}<Show when={activeTab() === 'security-audit'}><AuditLogPanel />diff --git a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsxnew file mode 100644index 0000000000..b6bb49fd77--- /dev/null+++ b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx@@ -0,0 +1,328 @@+import { Component, createSignal, createMemo, onMount, Show, For } from 'solid-js';+import { Card } from '@/components/shared/Card';+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 Users from 'lucide-solid/icons/users';+import Shield from 'lucide-solid/icons/shield';+import BadgeCheck from 'lucide-solid/icons/badge-check';+import X from 'lucide-solid/icons/x';+import Pencil from 'lucide-solid/icons/pencil';+import Search from 'lucide-solid/icons/search';++export const UserAssignmentsPanel: Component = () => {+ const [assignments, setAssignments] = createSignal<UserRoleAssignment[]>([]);+ const [roles, setRoles] = createSignal<Role[]>([]);+ const [loading, setLoading] = createSignal(true);+ const [searchQuery, setSearchQuery] = createSignal('');+ const [showModal, setShowModal] = createSignal(false);+ const [editingUser, setEditingUser] = createSignal<UserRoleAssignment | null>(null);+ const [saving, setSaving] = createSignal(false);+ const [userPermissions, setUserPermissions] = createSignal<Permission[]>([]);+ const [loadingPermissions, setLoadingPermissions] = createSignal(false);++ // Form state+ const [formRoleIds, setFormRoleIds] = createSignal<string[]>([]);++ const loadData = async () => {+ setLoading(true);+ try {+ const [usersData, rolesData] = await Promise.all([+ RBACAPI.getUsers(),+ RBACAPI.getRoles()+ ]);+ setAssignments(usersData || []);+ setRoles(rolesData || []);+ } catch (err) {+ logger.error('Failed to load user assignments', err);+ notificationStore.error('Failed to load user assignments');+ } finally {+ setLoading(false);+ }+ };++ onMount(() => {+ loadLicenseStatus();+ loadData();+ });++ const filteredAssignments = createMemo(() => {+ const query = searchQuery().toLowerCase();+ if (!query) return assignments();+ return assignments().filter(a => a.username.toLowerCase().includes(query));+ });++ const handleEditRoles = async (assignment: UserRoleAssignment) => {+ setEditingUser(assignment);+ setFormRoleIds([...assignment.roleIds]);+ setShowModal(true);+ await loadUserPermissions(assignment.username);+ };++ const loadUserPermissions = async (username: string) => {+ setLoadingPermissions(true);+ try {+ const perms = await RBACAPI.getUserPermissions(username);+ setUserPermissions(perms || []);+ } catch (err) {+ logger.error('Failed to load user permissions', err);+ } finally {+ setLoadingPermissions(false);+ }+ };++ const handleSave = async () => {+ const user = editingUser();+ if (!user) return;++ setSaving(true);+ try {+ await RBACAPI.updateUserRoles(user.username, formRoleIds());+ notificationStore.success(`Roles updated for ${user.username}`);+ setShowModal(false);+ await loadData();+ } catch (err) {+ logger.error('Failed to update user roles', err);+ notificationStore.error('Failed to update user roles');+ } finally {+ setSaving(false);+ }+ };++ const toggleRole = (roleId: string) => {+ const current = formRoleIds();+ if (current.includes(roleId)) {+ setFormRoleIds(current.filter(id => id !== roleId));+ } else {+ setFormRoleIds([...current, roleId]);+ }+ };++ const getRoleName = (id: string) => {+ return roles().find(r => r.id === id)?.name || id;+ };++ return (+ <div class="space-y-6">+ <Card padding="lg" class="space-y-4">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-3">+ <div class="flex items-center justify-center w-10 h-10 rounded-lg bg-teal-100 dark:bg-teal-900/30">+ <Users class="w-5 h-5 text-teal-600 dark:text-teal-400" />+ </div>+ <div>+ <h3 class="text-base font-semibold text-gray-900 dark:text-gray-100">User Access</h3>+ <p class="text-sm text-gray-600 dark:text-gray-400">Manage user role assignments and view effective permissions</p>+ </div>+ </div>+ <div class="relative">+ <Search class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />+ <input+ type="text"+ placeholder="Search users..."+ value={searchQuery()}+ onInput={(e) => setSearchQuery(e.currentTarget.value)}+ class="pl-9 pr-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-teal-200 dark:focus:ring-teal-800/60"+ />+ </div>+ </div>++ <Show when={!isEnterprise() && !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">+ <h4 class="text-base font-semibold text-gray-900 dark:text-white">Centralized Access Control (Pro)</h4>+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">+ Assign multi-tier roles to users and manage infrastructure-wide security policies.+ </p>+ </div>+ <a+ href="https://pulse.sh/pro"+ target="_blank"+ rel="noopener noreferrer"+ class="px-5 py-2.5 text-sm font-semibold bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors"+ >+ Upgrade to Pro+ </a>+ </div>+ </div>+ </Show>++ <Show when={loading()}>+ <div class="flex items-center justify-center py-8">+ <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-teal-500" />+ </div>+ </Show>++ <Show when={!loading()}>+ <div class="overflow-x-auto">+ <table class="w-full text-sm">+ <thead>+ <tr class="border-b border-gray-200 dark:border-gray-700">+ <th class="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400">Username</th>+ <th class="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400">Assigned Roles</th>+ <th class="text-right py-2 px-3 font-medium text-gray-600 dark:text-gray-400">Actions</th>+ </tr>+ </thead>+ <tbody>+ <For each={filteredAssignments()}>+ {(assignment) => (+ <tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50">+ <td class="py-3 px-3">+ <span class="font-medium text-gray-900 dark:text-gray-100">{assignment.username}</span>+ </td>+ <td class="py-3 px-3">+ <div class="flex flex-wrap gap-1">+ <Show when={assignment.roleIds.length === 0}>+ <span class="text-xs text-gray-400 italic">No roles assigned</span>+ </Show>+ <For each={assignment.roleIds}>+ {(roleId) => (+ <span class="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300 border border-indigo-100 dark:border-indigo-800">+ <Shield class="w-3 h-3" />+ {getRoleName(roleId)}+ </span>+ )}+ </For>+ </div>+ </td>+ <td class="py-3 px-3 text-right">+ <button+ type="button"+ onClick={() => handleEditRoles(assignment)}+ class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"+ >+ <Pencil class="w-4 h-4" />+ Manage Access+ </button>+ </td>+ </tr>+ )}+ </For>+ </tbody>+ </table>+ </div>+ </Show>+ </Card>++ {/* Assignments Modal */}+ <Show when={showModal()}>+ <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">+ <div class="w-full max-w-2xl bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 mx-4">+ <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">+ <div>+ <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">+ Manage Access: {editingUser()?.username}+ </h3>+ <p class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider font-semibold mt-0.5">Role Assignments</p>+ </div>+ <button+ type="button"+ onClick={() => setShowModal(false)}+ class="p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:hover:text-gray-300 dark:hover:bg-gray-800"+ >+ <X class="w-5 h-5" />+ </button>+ </div>++ <div class="px-6 py-6 space-y-8 max-h-[70vh] overflow-y-auto">+ {/* Role Selection */}+ <div class="space-y-4">+ <h4 class="text-sm font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2">+ <Shield class="w-4 h-4 text-indigo-500" />+ Select Roles+ </h4>+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <For each={roles()}>+ {(role) => (+ <label class={`flex flex-col p-3 rounded-xl border transition-all cursor-pointer ${formRoleIds().includes(role.id)+ ? 'bg-indigo-50 border-indigo-200 dark:bg-indigo-900/20 dark:border-indigo-800'+ : 'bg-white border-gray-200 hover:border-indigo-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:border-indigo-900'+ }`}>+ <div class="flex items-center justify-between mb-1">+ <div class="flex items-center gap-2 shadow-sm">+ <input+ type="checkbox"+ checked={formRoleIds().includes(role.id)}+ onChange={() => toggleRole(role.id)}+ class="w-4 h-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500 dark:border-gray-600"+ />+ <span class="text-sm font-semibold text-gray-900 dark:text-gray-100">+ {role.name}+ </span>+ </div>+ <Show when={role.isBuiltIn}>+ <BadgeCheck class="w-4 h-4 text-blue-500" />+ </Show>+ </div>+ <p class="text-xs text-gray-500 dark:text-gray-400 line-clamp-2 leading-relaxed pl-6">+ {role.description}+ </p>+ </label>+ )}+ </For>+ </div>+ </div>++ {/* Effective Permissions Preview */}+ <div class="space-y-4 pt-4 border-t border-gray-100 dark:border-gray-800">+ <div class="flex items-center justify-between">+ <h4 class="text-sm font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2">+ <BadgeCheck class="w-4 h-4 text-teal-500" />+ Effective Permissions Preview+ </h4>+ <Show when={loadingPermissions()}>+ <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-teal-500" />+ </Show>+ </div>+ <div class="bg-gray-50 dark:bg-gray-950 rounded-xl p-4 border border-gray-100 dark:border-gray-800">+ <Show when={!loadingPermissions() && userPermissions().length === 0}>+ <p class="text-xs text-gray-500 dark:text-gray-400 italic text-center py-2">+ No effective permissions. This user will have no access.+ </p>+ </Show>+ <div class="flex flex-wrap gap-2">+ <For each={userPermissions()}>+ {(perm) => (+ <span class="inline-flex items-center rounded-md bg-white px-2.5 py-1 text-xs font-semibold text-gray-700 dark:bg-gray-900 dark:text-gray-300 border border-gray-200 dark:border-gray-700 shadow-sm">+ <span class="text-indigo-600 dark:text-indigo-400">{perm.action}</span>+ <span class="mx-1 text-gray-400">:</span>+ <span class="text-teal-600 dark:text-teal-400">{perm.resource}</span>+ </span>+ )}+ </For>+ </div>+ <p class="mt-4 text-[10px] text-gray-400 dark:text-gray-500 uppercase tracking-widest font-bold">+ Note: Permissions are recalculated on save. This preview shows current server-side state.+ </p>+ </div>+ </div>+ </div>++ <div class="flex items-center justify-end gap-3 px-6 py-5 border-t border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-900/50 rounded-b-xl">+ <button+ type="button"+ onClick={() => setShowModal(false)}+ class="rounded-lg px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800 transition-colors"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={handleSave}+ disabled={saving()}+ class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-6 py-2 text-sm font-bold text-white shadow-lg shadow-indigo-200 dark:shadow-none transition-all hover:bg-indigo-700 hover:-translate-y-0.5 active:translate-y-0 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:translate-y-0"+ >+ {saving() ? 'Applying...' : 'Save Changes'}+ </button>+ </div>+ </div>+ </div>+ </Show>+ </div>+ );+};++export default UserAssignmentsPanel;diff --git a/frontend-modern/src/types/rbac.ts b/frontend-modern/src/types/rbac.tsnew file mode 100644index 0000000000..587290c7a3--- /dev/null+++ b/frontend-modern/src/types/rbac.ts@@ -0,0 +1,20 @@+export interface Permission {+ action: string;+ resource: string;+}++export interface Role {+ id: string;+ name: string;+ description: string;+ permissions: Permission[];+ isBuiltIn?: boolean;+ createdAt?: string;+ updatedAt?: string;+}++export interface UserRoleAssignment {+ username: string;+ roleIds: string[];+ updatedAt?: string;+}diff --git a/internal/api/auth.go b/internal/api/auth.goindex 1b495247b7..08d06a31d6 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -18,12 +18,6 @@ import ("github.com/rs/zerolog/log")-type contextKey string--const (- contextKeyAPIToken contextKey = "apiTokenRecord"-)-// Global session store instancevar (sessionStore *SessionStore@@ -752,16 +746,16 @@ func attachAPITokenRecord(r *http.Request, record *config.APITokenRecord) {return}clone := record.Clone()- ctx := context.WithValue(r.Context(), contextKeyAPIToken, clone)+ ctx := internalauth.WithAPIToken(r.Context(), &clone)*r = *r.WithContext(ctx)}func getAPITokenRecordFromRequest(r *http.Request) *config.APITokenRecord {- value := r.Context().Value(contextKeyAPIToken)- if value == nil {+ val := internalauth.GetAPIToken(r.Context())+ if val == nil {return nil}- record, ok := value.(config.APITokenRecord)+ record, ok := val.(*config.APITokenRecord)if !ok {return nil}diff --git a/internal/api/oidc_handlers.go b/internal/api/oidc_handlers.goindex d2f7d98653..aae996c445 100644--- a/internal/api/oidc_handlers.go+++ b/internal/api/oidc_handlers.go@@ -12,6 +12,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/config"+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log")@@ -246,6 +247,33 @@ func (r *Router) handleOIDCCallback(w http.ResponseWriter, req *http.Request) {log.Debug().Msg("User group membership verified")}+ // RBAC Integration: Map OIDC groups to Pulse roles+ if authManager := internalauth.GetManager(); authManager != nil {+ groups := extractStringSliceClaim(claims, cfg.GroupsClaim)+ var rolesToAssign []string+ seenRoles := make(map[string]bool)++ for _, group := range groups {+ if roleID, ok := cfg.GroupRoleMappings[group]; ok {+ if !seenRoles[roleID] {+ rolesToAssign = append(rolesToAssign, roleID)+ seenRoles[roleID] = true+ }+ }+ }++ if len(rolesToAssign) > 0 {+ log.Info().+ Str("user", username).+ Strs("mapped_roles", rolesToAssign).+ 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")+ // We don't fail the login here, but log the error+ }+ }+ }+// Prepare OIDC token info for session storage (enables refresh token support)var oidcTokens *OIDCTokenInfoif token.RefreshToken != "" {diff --git a/internal/api/rbac_handlers.go b/internal/api/rbac_handlers.gonew file mode 100644index 0000000000..cf0ed56f72--- /dev/null+++ b/internal/api/rbac_handlers.go@@ -0,0 +1,181 @@+package api++import (+ "encoding/json"+ "net/http"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++// RBACHandlers provides HTTP handlers for RBAC management.+type RBACHandlers struct {+ config *config.Config+}++// NewRBACHandlers creates a new RBACHandlers instance.+func NewRBACHandlers(cfg *config.Config) *RBACHandlers {+ return &RBACHandlers{config: cfg}+}++// HandleRoles handles list, create, update, and delete actions for roles.+func (h *RBACHandlers) HandleRoles(w http.ResponseWriter, r *http.Request) {+ manager := auth.GetManager()+ if manager == nil {+ writeErrorResponse(w, http.StatusNotImplemented, "rbac_unavailable", "RBAC management is not available", nil)+ return+ }++ id := strings.TrimPrefix(r.URL.Path, "/api/admin/roles")+ id = strings.TrimPrefix(id, "/")+ id = strings.TrimSuffix(id, "/")++ switch r.Method {+ case http.MethodGet:+ if id == "" {+ // List all roles+ roles := manager.GetRoles()+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(roles)+ } else {+ // Get specific role+ role, ok := manager.GetRole(id)+ if !ok {+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Role not found", nil)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(role)+ }++ case http.MethodPost:+ if id != "" {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "POST is for creating roles; do not include an ID in the path", nil)+ return+ }+ var role auth.Role+ if err := json.NewDecoder(r.Body).Decode(&role); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid role data", nil)+ return+ }++ if err := manager.SaveRole(role); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "save_failed", err.Error(), nil)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(role)++ case http.MethodPut:+ var role auth.Role+ if err := json.NewDecoder(r.Body).Decode(&role); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid role data", nil)+ return+ }++ if id != "" {+ role.ID = id+ }++ if err := manager.SaveRole(role); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "save_failed", err.Error(), nil)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(role)++ case http.MethodDelete:+ if id == "" {+ writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Role ID is required", nil)+ return+ }++ if err := manager.DeleteRole(id); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "delete_failed", err.Error(), nil)+ return+ }++ w.WriteHeader(http.StatusNoContent)++ default:+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+}++// HandleGetUsers lists users with their assigned roles.+func (h *RBACHandlers) HandleGetUsers(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ manager := auth.GetManager()+ if manager == nil {+ writeErrorResponse(w, http.StatusNotImplemented, "rbac_unavailable", "RBAC management is not available", nil)+ return+ }++ assignments := manager.GetUserAssignments()+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(assignments)+}++// HandleUserRoleActions handles assigning/updating roles for a user.+func (h *RBACHandlers) HandleUserRoleActions(w http.ResponseWriter, r *http.Request) {+ manager := auth.GetManager()+ if manager == nil {+ writeErrorResponse(w, http.StatusNotImplemented, "rbac_unavailable", "RBAC management is not available", nil)+ return+ }++ // Extract username from path: /api/admin/users/{username}/roles+ path := strings.TrimPrefix(r.URL.Path, "/api/admin/users/")+ parts := strings.Split(strings.Trim(path, "/"), "/")+ if len(parts) < 1 || parts[0] == "" {+ writeErrorResponse(w, http.StatusBadRequest, "missing_username", "Username is required", nil)+ return+ }+ username := parts[0]++ switch r.Method {+ case http.MethodPut, http.MethodPost:+ var req struct {+ RoleIDs []string `json:"roleIds"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid request body", nil)+ return+ }++ if err := manager.UpdateUserRoles(username, req.RoleIDs); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "update_failed", err.Error(), nil)+ return+ }++ w.WriteHeader(http.StatusNoContent)++ case http.MethodGet:+ // Get effective permissions+ if len(parts) > 1 && parts[1] == "permissions" {+ perms := manager.GetUserPermissions(username)+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(perms)+ return+ }++ // Get specific assignment+ assignment, ok := manager.GetUserAssignment(username)+ if !ok {+ writeErrorResponse(w, http.StatusNotFound, "not_found", "User assignment not found", nil)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(assignment)++ default:+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+}diff --git a/internal/api/rbac_handlers_test.go b/internal/api/rbac_handlers_test.gonew file mode 100644index 0000000000..28bd9d6f3d--- /dev/null+++ b/internal/api/rbac_handlers_test.go@@ -0,0 +1,179 @@+package api++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++type mockRBACManager struct {+ roles []auth.Role+ assignments []auth.UserRoleAssignment+}++func (m *mockRBACManager) GetRoles() []auth.Role { return m.roles }+func (m *mockRBACManager) GetRole(id string) (auth.Role, bool) {+ for _, r := range m.roles {+ if r.ID == id {+ return r, true+ }+ }+ return auth.Role{}, false+}+func (m *mockRBACManager) SaveRole(role auth.Role) error {+ m.roles = append(m.roles, role)+ return nil+}+func (m *mockRBACManager) DeleteRole(id string) error {+ for i, r := range m.roles {+ if r.ID == id {+ m.roles = append(m.roles[:i], m.roles[i+1:]...)+ return nil+ }+ }+ return nil+}+func (m *mockRBACManager) GetUserAssignments() []auth.UserRoleAssignment { return m.assignments }+func (m *mockRBACManager) GetUserAssignment(username string) (auth.UserRoleAssignment, bool) {+ for _, a := range m.assignments {+ if a.Username == username {+ return a, true+ }+ }+ return auth.UserRoleAssignment{}, false+}+func (m *mockRBACManager) AssignRole(username string, roleID string) error { return nil }+func (m *mockRBACManager) UpdateUserRoles(username string, roleIDs []string) error {+ m.assignments = append(m.assignments, auth.UserRoleAssignment{Username: username, RoleIDs: roleIDs})+ return nil+}+func (m *mockRBACManager) RemoveRole(username string, roleID string) error { return nil }+func (m *mockRBACManager) GetUserPermissions(username string) []auth.Permission {+ return []auth.Permission{{Action: "read", Resource: "nodes"}}+}++func TestHandleRoles(t *testing.T) {+ cfg := &config.Config{}+ h := NewRBACHandlers(cfg)++ mock := &mockRBACManager{+ roles: []auth.Role{{ID: "admin", Name: "Admin"}},+ }+ auth.SetManager(mock)++ t.Run("List roles", func(t *testing.T) {+ req := httptest.NewRequest("GET", "/api/admin/roles", nil)+ rr := httptest.NewRecorder()+ h.HandleRoles(rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("Expected status OK, got %d", rr.Code)+ }+ var roles []auth.Role+ json.Unmarshal(rr.Body.Bytes(), &roles)+ if len(roles) != 1 || roles[0].ID != "admin" {+ t.Errorf("Unexpected roles: %+v", roles)+ }+ })++ t.Run("Create role", func(t *testing.T) {+ role := auth.Role{ID: "custom", Name: "Custom"}+ body, _ := json.Marshal(role)+ req := httptest.NewRequest("POST", "/api/admin/roles", bytes.NewReader(body))+ rr := httptest.NewRecorder()++ h.HandleRoles(rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("Expected status OK, got %d", rr.Code)+ }+ if len(mock.roles) != 2 || mock.roles[1].ID != "custom" {+ t.Errorf("Role not saved correctly")+ }+ })++ t.Run("POST with path ID (rejected)", func(t *testing.T) {+ req := httptest.NewRequest("POST", "/api/admin/roles/new-role", nil)+ rr := httptest.NewRecorder()+ h.HandleRoles(rr, req)++ if rr.Code != http.StatusBadRequest {+ t.Errorf("Expected status Bad Request, got %d", rr.Code)+ }+ })++ t.Run("Get role", func(t *testing.T) {+ req := httptest.NewRequest("GET", "/api/admin/roles/admin", nil)+ rr := httptest.NewRecorder()+ h.HandleRoles(rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("Expected status OK, got %d", rr.Code)+ }+ var role auth.Role+ json.Unmarshal(rr.Body.Bytes(), &role)+ if role.ID != "admin" {+ t.Errorf("Expected admin role, got %s", role.ID)+ }+ })++ t.Run("Delete role", func(t *testing.T) {+ req := httptest.NewRequest("DELETE", "/api/admin/roles/custom", nil)+ rr := httptest.NewRecorder()++ h.HandleRoles(rr, req)++ if rr.Code != http.StatusNoContent {+ t.Errorf("Expected status No Content, got %d", rr.Code)+ }+ if len(mock.roles) != 1 {+ t.Errorf("Role not deleted")+ }+ })+}++func TestHandleUserRoleActions(t *testing.T) {+ cfg := &config.Config{}+ h := NewRBACHandlers(cfg)+ mock := &mockRBACManager{}+ auth.SetManager(mock)++ t.Run("Update user roles", func(t *testing.T) {+ reqData := struct {+ RoleIDs []string `json:"roleIds"`+ }{RoleIDs: []string{"admin", "viewer"}}+ body, _ := json.Marshal(reqData)+ req := httptest.NewRequest("PUT", "/api/admin/users/testuser/roles", bytes.NewReader(body))+ rr := httptest.NewRecorder()++ h.HandleUserRoleActions(rr, req)++ if rr.Code != http.StatusNoContent {+ t.Errorf("Expected status No Content, got %d", rr.Code)+ }+ if len(mock.assignments) != 1 || mock.assignments[0].Username != "testuser" {+ t.Errorf("Assignment not saved correctly")+ }+ })++ t.Run("Get effective permissions", func(t *testing.T) {+ req := httptest.NewRequest("GET", "/api/admin/users/testuser/permissions", nil)+ rr := httptest.NewRecorder()++ h.HandleUserRoleActions(rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("Expected status OK, got %d", rr.Code)+ }+ var perms []auth.Permission+ json.Unmarshal(rr.Body.Bytes(), &perms)+ if len(perms) != 1 || perms[0].Action != "read" {+ t.Errorf("Unexpected permissions: %+v", perms)+ }+ })+}diff --git a/internal/api/router.go b/internal/api/router.goindex f9bf9891b8..dc2b6be3f3 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -38,6 +38,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/updates""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")@@ -205,6 +206,7 @@ func (r *Router) setupRoutes() {r.resourceHandlers = NewResourceHandlers()r.configProfileHandler = NewConfigProfileHandler(r.persistence)r.licenseHandlers = NewLicenseHandlers(r.config.DataPath)+ rbacHandlers := NewRBACHandlers(r.config)// API routesr.mux.HandleFunc("/api/health", r.handleHealth)@@ -503,7 +505,13 @@ 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, internalauth.ActionRead, internalauth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureAuditLogging, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleVerifyAuditEvent))))+ 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))))++ // 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)))+ r.mux.HandleFunc("/api/admin/roles/", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureRBAC, rbacHandlers.HandleRoles)))+ r.mux.HandleFunc("/api/admin/users", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureRBAC, rbacHandlers.HandleGetUsers)))+ r.mux.HandleFunc("/api/admin/users/", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, RequireLicenseFeature(r.licenseHandlers.Service(), license.FeatureRBAC, rbacHandlers.HandleUserRoleActions)))// Security routesr.mux.HandleFunc("/api/security/change-password", r.handleChangePassword)diff --git a/internal/config/oidc.go b/internal/config/oidc.goindex 7f626d1bec..c653dc2704 100644--- a/internal/config/oidc.go+++ b/internal/config/oidc.go@@ -14,21 +14,22 @@ const DefaultOIDCCallbackPath = "/api/oidc/callback"// OIDCConfig captures configuration required to integrate with an OpenID Connect provider.type OIDCConfig struct {- Enabled bool `json:"enabled"`- IssuerURL string `json:"issuerUrl"`- ClientID string `json:"clientId"`- ClientSecret string `json:"clientSecret,omitempty"`- RedirectURL string `json:"redirectUrl"`- LogoutURL string `json:"logoutUrl,omitempty"`- Scopes []string `json:"scopes,omitempty"`- UsernameClaim string `json:"usernameClaim,omitempty"`- EmailClaim string `json:"emailClaim,omitempty"`- GroupsClaim string `json:"groupsClaim,omitempty"`- AllowedGroups []string `json:"allowedGroups,omitempty"`- AllowedDomains []string `json:"allowedDomains,omitempty"`- AllowedEmails []string `json:"allowedEmails,omitempty"`- CABundle string `json:"caBundle,omitempty"`- EnvOverrides map[string]bool `json:"-"`+ Enabled bool `json:"enabled"`+ IssuerURL string `json:"issuerUrl"`+ ClientID string `json:"clientId"`+ ClientSecret string `json:"clientSecret,omitempty"`+ RedirectURL string `json:"redirectUrl"`+ LogoutURL string `json:"logoutUrl,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+ UsernameClaim string `json:"usernameClaim,omitempty"`+ EmailClaim string `json:"emailClaim,omitempty"`+ GroupsClaim string `json:"groupsClaim,omitempty"`+ AllowedGroups []string `json:"allowedGroups,omitempty"`+ AllowedDomains []string `json:"allowedDomains,omitempty"`+ AllowedEmails []string `json:"allowedEmails,omitempty"`+ GroupRoleMappings map[string]string `json:"groupRoleMappings,omitempty"`+ CABundle string `json:"caBundle,omitempty"`+ EnvOverrides map[string]bool `json:"-"`}// NewOIDCConfig returns an instance populated with sensible defaults.@@ -50,6 +51,12 @@ func (c *OIDCConfig) Clone() *OIDCConfig {clone.AllowedDomains = append([]string{}, c.AllowedDomains...)clone.AllowedEmails = append([]string{}, c.AllowedEmails...)clone.CABundle = c.CABundle+ if c.GroupRoleMappings != nil {+ clone.GroupRoleMappings = make(map[string]string, len(c.GroupRoleMappings))+ for k, v := range c.GroupRoleMappings {+ clone.GroupRoleMappings[k] = v+ }+ }if c.EnvOverrides != nil {clone.EnvOverrides = make(map[string]bool, len(c.EnvOverrides))for k, v := range c.EnvOverrides {@@ -85,6 +92,10 @@ func (c *OIDCConfig) ApplyDefaults(publicURL string) {c.AllowedDomains = normaliseList(c.AllowedDomains)c.AllowedEmails = normaliseList(c.AllowedEmails)+ if c.GroupRoleMappings == nil {+ c.GroupRoleMappings = make(map[string]string)+ }+if c.EnvOverrides == nil {c.EnvOverrides = make(map[string]bool)}@@ -169,6 +180,27 @@ func parseDelimited(input string) []string {return normaliseList(parts)}+// parseMappings converts a delimiter-separated string of key=value pairs into a map.+// Format: group1=role1,group2=role2+func parseMappings(input string) map[string]string {+ if strings.TrimSpace(input) == "" {+ return nil+ }++ result := make(map[string]string)+ pairs := parseDelimited(input)+ for _, pair := range pairs {+ if idx := strings.IndexByte(pair, '='); idx != -1 {+ key := strings.TrimSpace(pair[:idx])+ val := strings.TrimSpace(pair[idx+1:])+ if key != "" && val != "" {+ result[key] = val+ }+ }+ }+ return result+}+// MergeFromEnv overrides config values with environment provided pairs.func (c *OIDCConfig) MergeFromEnv(env map[string]string) {if c == nil {@@ -231,6 +263,10 @@ func (c *OIDCConfig) MergeFromEnv(env map[string]string) {c.AllowedEmails = parseDelimited(val)c.EnvOverrides["allowedEmails"] = true}+ if val, ok := env["OIDC_GROUP_ROLE_MAPPINGS"]; ok {+ c.GroupRoleMappings = parseMappings(val)+ c.EnvOverrides["groupRoleMappings"] = true+ }if val, ok := env["OIDC_CA_BUNDLE"]; ok {c.CABundle = valc.EnvOverrides["caBundle"] = truediff --git a/internal/hostagent/proxmox_setup.go b/internal/hostagent/proxmox_setup.goindex b2f5064de7..3f7863eac9 100644--- a/internal/hostagent/proxmox_setup.go+++ b/internal/hostagent/proxmox_setup.go@@ -413,28 +413,35 @@ func (p *ProxmoxSetup) getIPThatReachesPulse() string {host := u.Hostif !strings.Contains(host, ":") {- // Add default port if not specified+ // If port is missing, try to infer it from schemeif u.Scheme == "https" {host += ":443"- } else {+ } else if u.Scheme == "http" {host += ":80"+ } else {+ // Pulse default if scheme is missing or weird+ host += ":7655"}}// Create a UDP "connection" to determine local address (doesn't actually send data)- conn, err := net.DialTimeout("udp", host, 2*time.Second)+ // We use a short timeout as this is just a routing table lookup.+ conn, err := net.DialTimeout("udp", host, 500*time.Millisecond)if err != nil {- p.logger.Debug().Err(err).Msg("Could not determine local IP for Pulse connection")+ p.logger.Debug().Err(err).Str("target", host).Msg("Could not determine local IP for Pulse connection (routing check failed)")return ""}defer conn.Close()- localAddr := conn.LocalAddr().(*net.UDPAddr)+ localAddr, ok := conn.LocalAddr().(*net.UDPAddr)+ if !ok || localAddr == nil {+ return ""+ }ip := localAddr.IP.String()// If we found an IP that can reach Pulse, it's the most reliable one to report.// We only skip loopback/link-local which net.Dial UDP shouldn't return anyway.- if ip != "" && ip != "127.0.0.1" && !strings.HasPrefix(ip, "fe80:") {+ if ip != "" && ip != "127.0.0.1" && ip != "::1" && !strings.HasPrefix(ip, "fe80:") {return ip}return ""@@ -464,29 +471,6 @@ func (p *ProxmoxSetup) getIPForHostname() string {return ""}-// isPrivateIP checks if an IP address is in a private range (RFC 1918).-func isPrivateIP(ip string) bool {- parsed := net.ParseIP(ip)- if parsed == nil {- return false- }- // Check common private ranges- private := []string{- "10.0.0.0/8", // RFC 1918- "172.16.0.0/12", // RFC 1918- "192.168.0.0/16", // RFC 1918- "100.64.0.0/10", // CGNAT / Tailscale- "169.254.0.0/16", // Link-local- }- for _, cidr := range private {- _, network, _ := net.ParseCIDR(cidr)- if network.Contains(parsed) {- return true- }- }- return false-}-// selectBestIP picks the most likely externally-reachable IP from a list.// Prefers common LAN subnets (192.168.x.x, 10.x.x.x) and avoids internal// cluster networks (like corosync's 172.20.x.x) and link-local addresses.@@ -560,8 +544,9 @@ func scoreIPv4(ip string) int {fmt.Sscanf(parts[1], "%d", &second)// Scoring logic:- // - 192.168.x.x: Very common home/office LAN, high priority (score 100)+ // - 192.168.x.x: Very common home/office LAN, highest priority (score 100)// - 10.0.x.x - 10.31.x.x: Common corporate LAN ranges (score 90)+ // - 100.64.x.x: Tailscale / CGNAT (score 85)// - 10.x.x.x (other): Less common, but still likely LAN (score 70)// - 172.16-31.x.x: Private range, often used for internal clusters (score 50)// Corosync often uses 172.20.x.x or similar for ring0/ring1@@ -573,6 +558,8 @@ func scoreIPv4(ip string) int {return 100 // Most common home/office LANcase first == 10 && second <= 31:return 90 // Common corporate LAN+ case first == 100 && (second >= 64 && second <= 127):+ return 85 // Tailscale / CGNATcase first == 10:return 70 // Other 10.x.x.xcase first == 172 && second >= 16 && second <= 31:diff --git a/internal/hostagent/proxmox_setup_test.go b/internal/hostagent/proxmox_setup_test.goindex a9ffcdf38e..c1b9065c03 100644--- a/internal/hostagent/proxmox_setup_test.go+++ b/internal/hostagent/proxmox_setup_test.go@@ -115,6 +115,17 @@ func TestSelectBestIP(t *testing.T) {hostnameIP: "",expected: "10.0.0.1",},+ {+ name: "prefers LAN over Tailscale if hostname matches both",+ ips: []string{"192.168.1.5", "100.64.0.1"},+ hostnameIP: "192.168.1.5",+ expected: "192.168.1.5",+ },+ {+ name: "prefers Tailscale over cluster network",+ ips: []string{"172.20.0.1", "100.64.0.1"},+ expected: "100.64.0.1",+ },}for _, tt := range tests {@@ -152,6 +163,13 @@ func TestScoreIPv4(t *testing.T) {{"172.20.0.80", 50}, // Corosync typical{"172.31.255.255", 50},+ // 100.64.x.x - Tailscale / CGNAT (85)+ {"100.64.0.1", 85},+ {"100.100.100.100", 85},+ {"100.127.255.255", 85},+ {"100.63.255.255", 30}, // Just outside range (below)+ {"100.128.0.1", 30}, // Just outside range (above)+// 169.254.x.x - link-local (0){"169.254.1.1", 0},diff --git a/internal/license/features.go b/internal/license/features.goindex f9521cee28..9bbc06c406 100644--- a/internal/license/features.go+++ b/internal/license/features.go@@ -17,7 +17,8 @@ const (FeatureUpdateAlerts = "update_alerts" // Alerts for pending container/package updates (free feature)// MSP tier features (FUTURE - not in v1 launch)- FeatureMultiUser = "multi_user" // RBAC - NOT IMPLEMENTED YET+ FeatureRBAC = "rbac" // Role-Based Access Control+ FeatureMultiUser = "multi_user" // Multi-user (likely merged with RBAC)FeatureWhiteLabel = "white_label" // Custom branding - NOT IMPLEMENTED YETFeatureMultiTenant = "multi_tenant" // Multi-tenant - NOT IMPLEMENTED YETFeatureUnlimited = "unlimited" // Unlimited instances (explicit for contracts)@@ -55,6 +56,7 @@ var TierFeatures = map[Tier][]string{FeatureAgentProfiles,FeatureUpdateAlerts,FeatureSSO,+ FeatureRBAC,},TierProAnnual: {FeatureAIPatrol,@@ -64,6 +66,7 @@ var TierFeatures = map[Tier][]string{FeatureAgentProfiles,FeatureUpdateAlerts,FeatureSSO,+ FeatureRBAC,},TierLifetime: {FeatureAIPatrol,@@ -73,6 +76,7 @@ var TierFeatures = map[Tier][]string{FeatureAgentProfiles,FeatureUpdateAlerts,FeatureSSO,+ FeatureRBAC,},TierMSP: {FeatureAIPatrol,@@ -100,6 +104,7 @@ var TierFeatures = map[Tier][]string{FeatureAuditLogging,FeatureSSO,FeatureAdvancedSSO,+ FeatureRBAC,},}@@ -150,8 +155,10 @@ func GetFeatureDisplayName(feature string) string {return "Kubernetes AI Analysis"case FeatureUpdateAlerts:return "Update Alerts (Container/Package Updates)"+ case FeatureRBAC:+ return "Role-Based Access Control (RBAC)"case FeatureMultiUser:- return "Multi-User / RBAC"+ return "Multi-User Mode"case FeatureWhiteLabel:return "White-Label Branding"case FeatureMultiTenant:diff --git a/pkg/auth/authorizer.go b/pkg/auth/authorizer.goindex 98360f01c0..8c88c7cbef 100644--- a/pkg/auth/authorizer.go+++ b/pkg/auth/authorizer.go@@ -12,9 +12,15 @@ type Authorizer interface {type contextKey stringconst (- contextKeyUser contextKey = "user"+ contextKeyUser contextKey = "user"+ contextKeyAPIToken contextKey = "apiToken")+// APITokenInfo is a minimal interface for checking token scopes without circular dependencies.+type APITokenInfo interface {+ HasScope(scope string) bool+}+// WithUser adds a username to the contextfunc WithUser(ctx context.Context, username string) context.Context {return context.WithValue(ctx, contextKeyUser, username)@@ -28,6 +34,19 @@ func GetUser(ctx context.Context) string {return ""}+// WithAPIToken adds an API token record to the context+func WithAPIToken(ctx context.Context, token APITokenInfo) context.Context {+ return context.WithValue(ctx, contextKeyAPIToken, token)+}++// GetAPIToken extracts the API token record from the context+func GetAPIToken(ctx context.Context) APITokenInfo {+ if token, ok := ctx.Value(contextKeyAPIToken).(APITokenInfo); ok {+ return token+ }+ return nil+}+// DefaultAuthorizer is a pass-through implementation that allows everything.// Used in OSS version and when enterprise features are disabled.type DefaultAuthorizer struct{}diff --git a/pkg/auth/rbac.go b/pkg/auth/rbac.gonew file mode 100644index 0000000000..86c331cdb2--- /dev/null+++ b/pkg/auth/rbac.go@@ -0,0 +1,78 @@+package auth++import (+ "context"+ "time"+)++// Permission defines a single allowed action on a resource.+type Permission struct {+ Action string `json:"action"` // read, write, delete, admin+ Resource string `json:"resource"` // nodes, settings, users, audit_logs, etc.+}++// Role represents a collection of permissions.+type Role struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Permissions []Permission `json:"permissions"`+ IsBuiltIn bool `json:"isBuiltIn"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+}++// UserRoleAssignment maps a user to one or more roles.+type UserRoleAssignment struct {+ Username string `json:"username"`+ RoleIDs []string `json:"roleIds"`+ UpdatedAt time.Time `json:"updatedAt"`+}++// Built-in Role IDs+const (+ RoleAdmin = "admin"+ RoleOperator = "operator"+ RoleViewer = "viewer"+ RoleAuditor = "auditor"+ RoleCompliance = "compliance" // Alias for Auditor+)++// Manager defines the interface for managing RBAC data.+// This is typically implemented by the enterprise RBAC store.+type Manager interface {+ // Role management+ GetRoles() []Role+ GetRole(id string) (Role, bool)+ SaveRole(role Role) error+ DeleteRole(id string) error++ // Assignment management+ GetUserAssignments() []UserRoleAssignment+ GetUserAssignment(username string) (UserRoleAssignment, bool)+ AssignRole(username string, roleID string) error+ UpdateUserRoles(username string, roleIDs []string) error+ RemoveRole(username string, roleID string) error++ // Effective permissions+ GetUserPermissions(username string) []Permission+}++var globalManager Manager++// SetManager sets the global RBAC manager instance.+func SetManager(m Manager) {+ globalManager = m+}++// GetManager returns the global RBAC manager instance.+func GetManager() Manager {+ return globalManager+}++// Requirement helpers+func HasPermission(ctx context.Context, action, resource string) bool {+ authorizer := GetAuthorizer()+ allowed, _ := authorizer.Authorize(ctx, action, resource)+ return allowed+}