Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Users administration, editable RBAC, and SSO login hardening (lands #1179's reviewed scope) (#1183)
Beenu Arora90ea2fdabbbc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12242f64d..ee8491374 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Admin Users administration: a console-only **Settings → Users** screen+ (admin nav, hidden entirely for viewer/infosec) with server-side+ pagination/search/filter/sort over `GET /api/v1/admin/users`, multi-role+ assignment via checkbox modal with a live effective-permissions preview,+ enable/disable with session revocation, and permanent delete+ (`DELETE /api/v1/admin/users/{id}?reason=…`) guarded against+ self-deletion and last-admin lockout. Delete is audit-safe: migration+ `094` rewrites the one RESTRICT FK to `ON DELETE SET NULL` and the+ audit row snapshots the full identity, so attribution survives the row.- Enterprise SSO wave: a feature-flagged (`SSO_ENABLED=false` by default)single-sign-on surface with a login-screen button served by`GET /api/v1/auth/sso/status`, `infosec` as a first-class assignable rolediff --git a/apps/web/src/app/(app)/settings/users/page.tsx b/apps/web/src/app/(app)/settings/users/page.tsxnew file mode 100644index 000000000..9d38e24f8--- /dev/null+++ b/apps/web/src/app/(app)/settings/users/page.tsx@@ -0,0 +1,19 @@+import { UsersView } from '@/components/settings/UsersView';++export const metadata = {+ title: 'Users',+};++export default function UsersPage() {+ return (+ <div className="p-6">+ <div className="mb-4">+ <h2 className="text-xl font-bold text-gray-100">Users</h2>+ <p className="mt-0.5 text-sm text-gray-500">+ Manage members and their roles. Role changes revoke the member's active sessions and are audited.+ </p>+ </div>+ <UsersView />+ </div>+ );+}diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsxindex 6000b9dab..a2f375d26 100644--- a/apps/web/src/components/layout/Sidebar.tsx+++ b/apps/web/src/components/layout/Sidebar.tsx@@ -1,12 +1,13 @@'use client';-import { useState } from 'react';+import { useEffect, useState } from 'react';import Link from 'next/link';import { usePathname } from 'next/navigation';import { clsx } from 'clsx';import packageJson from '../../../package.json';import { LiveQueueBadge } from './LiveQueueBadge';import { useBranding } from '@/hooks/useBranding';+import { authApi } from '@/lib/api';const APP_VERSION = packageJson.version;@@ -14,6 +15,8 @@ interface NavItem {label: string;href: string;icon: React.ReactNode;+ /** Hidden entirely for non-admin operators (server gates the API anyway). */+ adminOnly?: boolean;badge?: number;badgeColor?: string;/**@@ -143,6 +146,12 @@ const CurrencyIcon = () => (</svg>);+const UsersIcon = () => (+ <svg className="w-5 h-5" aria-hidden="true" fill="none" viewBox="0 0 24 24" stroke="currentColor">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a4 4 0 00-3-3.87M9 20H4v-2a4 4 0 013-3.87m6-1.13a4 4 0 10-4-4 4 4 0 004 4zm6-4a3 3 0 11-3-3" />+ </svg>+);+const navSections: NavSection[] = [{items: [@@ -304,6 +313,12 @@ const navSections: NavSection[] = [href: '/connectors',icon: <PuzzleIcon />,},+ {+ label: 'Users',+ href: '/settings/users',+ icon: <UsersIcon />,+ adminOnly: true,+ },{label: 'Roles & Permissions',href: '/settings/rbac',@@ -361,6 +376,16 @@ export function Sidebar() {const pathname = usePathname();const [mobileOpen, setMobileOpen] = useState(false);+ // Users management is admin-only. The nav item is hidden entirely for+ // viewer/infosec — the server refuses the page's API calls anyway, but+ // showing a door that only opens for someone else is a lie in chrome.+ // Client-side gate is a courtesy; `/api/v1/admin/users` is the real gate.+ const [meRole, setMeRole] = useState<string | null>(null);+ useEffect(() => {+ setMeRole(authApi.currentUser()?.role ?? null);+ }, []);+ const isAdmin = meRole === 'admin';+const isActive = (href: string) => {if (href === '/dashboard') return pathname === '/dashboard';return pathname.startsWith(href);@@ -438,7 +463,7 @@ export function Sidebar() {</p>)}<ul className="space-y-0.5">- {section.items.map((item) => {+ {section.items.filter((item) => !item.adminOnly || isAdmin).map((item) => {const active = isActive(item.href);return (<li key={item.href}>diff --git a/apps/web/src/components/layout/TopBar.tsx b/apps/web/src/components/layout/TopBar.tsxindex e68b71e59..5e2f613b3 100644--- a/apps/web/src/components/layout/TopBar.tsx+++ b/apps/web/src/components/layout/TopBar.tsx@@ -15,6 +15,7 @@ import { useTenant } from './TenantProvider';const routeLabels: Record<string, { title: string; description: string }> = {'/detection/catalog': { title: 'Detection Catalog', description: 'Curated rule packs and templates' },'/settings/rbac': { title: 'Roles & Permissions', description: 'Access control and team management' },+ '/settings/users': { title: 'Users', description: 'Member and role management' },'/dashboard': { title: 'Dashboard', description: 'SOC overview and metrics' },'/alerts': { title: 'Alerts', description: 'Security alerts and incidents' },'/cases': { title: 'Cases', description: 'Incident case management' },diff --git a/apps/web/src/components/settings/AssignRoleModal.tsx b/apps/web/src/components/settings/AssignRoleModal.tsxnew file mode 100644index 000000000..444881c22--- /dev/null+++ b/apps/web/src/components/settings/AssignRoleModal.tsx@@ -0,0 +1,141 @@+'use client';++import { useState } from 'react';+import toast from 'react-hot-toast';+import { rbacApi, type RbacRole, type TenantUser } from '@/lib/api';++interface AssignRoleModalProps {+ user: TenantUser;+ roles: RbacRole[];+ isSelf: boolean;+ adminCount: number;+ onClose: () => void;+ onAssigned: () => void;+}++/**+ * Assign-role modal for one member.+ *+ * Product stance: single primary role. Storage is multi-role capable+ * (`user_roles`), and `POST /api/v1/rbac/users/{id}/roles` exists for it,+ * but the console deliberately assigns exactly one — half-supporting both+ * shapes is how two role columns start disagreeing about who someone is.+ * The chosen role replaces the previous assignment and takes effect on the+ * target's next request; no re-login is required.+ */+export function AssignRoleModal({ user, roles, isSelf, adminCount, onClose, onAssigned }: AssignRoleModalProps) {+ const [selected, setSelected] = useState<string>(user.role);+ const [reason, setReason] = useState('');+ const [confirmAdmin, setConfirmAdmin] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const grantingAdmin = selected === 'admin' && user.role !== 'admin';+ const demotingLastAdmin = isSelf && user.role === 'admin' && selected !== 'admin' && adminCount <= 1;+ const reasonMissing = reason.trim().length === 0;+ const canSave = !saving && !reasonMissing && !demotingLastAdmin && (!grantingAdmin || confirmAdmin) && selected !== user.role;++ const save = async () => {+ setSaving(true);+ setError(null);+ try {+ const res = await rbacApi.setPrimaryRole(user.id, selected, reason.trim());+ toast.success(`${user.email} is now ${res.role_name} — effective on their next request.`);+ onAssigned();+ } catch (e) {+ const msg = (e as Error).message || 'Role assignment failed';+ setError(msg);+ toast.error(msg);+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>+ <div+ className="w-full max-w-md rounded-2xl border border-gray-800 bg-gray-900 p-6 shadow-2xl"+ onClick={(e) => e.stopPropagation()}+ >+ <h3 className="text-base font-semibold text-gray-100">Assign role</h3>+ <p className="mt-1 text-sm text-gray-400">+ {user.username} · {user.email}+ {!user.is_active && <span className="ml-2 rounded bg-amber-500/20 px-1.5 py-0.5 text-[10px] uppercase text-amber-300">disabled — assignments refused</span>}+ </p>++ {error && (+ <p className="mt-3 rounded-lg border border-red-900/60 bg-red-950/40 px-3 py-2 text-sm text-red-300" role="alert">+ {error}+ </p>+ )}++ <label className="mt-4 block text-xs font-semibold uppercase tracking-wide text-gray-500" htmlFor="assign-role-select">+ Role+ </label>+ <select+ id="assign-role-select"+ value={selected}+ onChange={(e) => {+ setSelected(e.target.value);+ setConfirmAdmin(false);+ }}+ disabled={!user.is_active}+ className="mt-1 w-full rounded-lg border border-gray-700 bg-gray-950 px-3 py-2 text-sm text-gray-100 focus:border-indigo-500 focus:outline-none"+ >+ {roles.map((r) => (+ <option key={r.id} value={r.name}>+ {r.name}+ {r.is_sso_default ? ' — SSO default' : ''}+ </option>+ ))}+ </select>+ {roles.find((r) => r.name === selected)?.description && (+ <p className="mt-1.5 text-xs text-gray-500">{roles.find((r) => r.name === selected)?.description}</p>+ )}++ <label className="mt-4 block text-xs font-semibold uppercase tracking-wide text-gray-500" htmlFor="assign-role-reason">+ Reason (required, audited)+ </label>+ <textarea+ id="assign-role-reason"+ value={reason}+ onChange={(e) => setReason(e.target.value)}+ rows={2}+ maxLength={500}+ placeholder="Why is this role changing? Stored in the audit log with actor, target, old and new role."+ className="mt-1 w-full rounded-lg border border-gray-700 bg-gray-950 px-3 py-2 text-sm text-gray-100 placeholder-gray-600 focus:border-indigo-500 focus:outline-none"+ />++ {grantingAdmin && (+ <label className="mt-3 flex items-start gap-2 rounded-lg border border-amber-800/60 bg-amber-950/30 px-3 py-2 text-sm text-amber-200">+ <input type="checkbox" checked={confirmAdmin} onChange={(e) => setConfirmAdmin(e.target.checked)} className="mt-0.5" />+ <span>+ Granting <strong>admin</strong> confers full control of this workspace, including user, role, SSO and+ audit management. Confirm you intend this.+ </span>+ </label>+ )}+ {demotingLastAdmin && (+ <p className="mt-3 rounded-lg border border-red-900/60 bg-red-950/40 px-3 py-2 text-sm text-red-300" role="alert">+ You are the only active admin. Promote another admin before changing your own role — the server refuses+ this request (409) and the break-glass account is the last door.+ </p>+ )}++ <div className="mt-5 flex justify-end gap-3">+ <button type="button" onClick={onClose} className="rounded-lg px-4 py-2 text-sm text-gray-400 hover:bg-gray-800">+ Cancel+ </button>+ <button+ type="button"+ onClick={save}+ disabled={!canSave}+ className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50"+ >+ {saving ? 'Assigning…' : selected === user.role ? 'Role unchanged' : `Assign ${selected}`}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/settings/RBACView.tsx b/apps/web/src/components/settings/RBACView.tsxindex 947eabd08..b3e6c2ecb 100644--- a/apps/web/src/components/settings/RBACView.tsx+++ b/apps/web/src/components/settings/RBACView.tsx@@ -6,7 +6,8 @@ import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { demoFallback } from '@/lib/demoFallback';import { FailureBanner } from '@/components/ui/FailureBanner';import { describeApiFailure } from '@/lib/failure';-import { apiFetch, authedFetcher } from '@/lib/api';+import { authedFetcher, rbacApi, type RbacRole } from '@/lib/api';+import toast from 'react-hot-toast';interface Permission {id: string;@@ -15,14 +16,8 @@ interface Permission {category: string | null;}-interface Role {- id: string;- tenant_id: string;- name: string;- description: string | null;- is_system: boolean;- permissions: Permission[];-}+type Role = RbacRole;+// Throws `ApiError`, so the banner below can tell a 403 (this operator cannot// read roles) from a 500 (the API is broken) from a 422 (the console is).@@ -54,7 +49,8 @@ function RoleCard({ role, onEdit, onDelete }: { role: Role; onEdit: (r: Role) =><div className="flex items-start justify-between gap-2"><div><div className="flex items-center gap-2">- <span className="text-base font-semibold text-gray-100">{role.name}</span>+ <span className="text-base font-semibold text-gray-100">{role.label || role.name}</span>+ {role.label && <span className="font-mono text-xs text-gray-500">{role.name}</span>}{role.is_system && (<span className="rounded bg-indigo-100 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-indigo-700">system@@ -80,13 +76,42 @@ function RoleCard({ role, onEdit, onDelete }: { role: Role; onEdit: (r: Role) =></div>)}</div>- <div className="mt-3 flex flex-wrap gap-1.5">- {role.permissions.length === 0 ? (- <span className="text-xs text-gray-600 italic">No permissions assigned</span>- ) : (- role.permissions.map((p) => <PermissionBadge key={p.id} perm={p} />)+ <div className="mt-3 flex items-center gap-3 text-xs text-gray-400">+ <span title="Users holding this role in this workspace">+ {role.user_count} user{role.user_count === 1 ? '' : 's'}+ </span>+ {role.is_sso_default && (+ <span className="rounded bg-sky-500/20 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-sky-300" title="New SSO sign-ins are provisioned with this role">+ SSO default · protected+ </span>+ )}+ {role.is_system && !role.is_sso_default && (+ <span className="rounded bg-gray-700/60 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-gray-300">+ protected · non-deletable+ </span>)}</div>+ {(() => {+ const byCat = new Map<string, Permission[]>();+ for (const p of role.permissions) {+ const cat = p.category ?? 'other';+ (byCat.get(cat) ?? byCat.set(cat, []).get(cat)!).push(p);+ }+ return role.permissions.length === 0 ? (+ <p className="mt-3 text-xs italic text-gray-600">No permissions assigned</p>+ ) : (+ <div className="mt-3 space-y-2">+ {[...byCat.entries()].sort().map(([cat, perms]) => (+ <div key={cat}>+ <p className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-gray-500">{cat}</p>+ <div className="flex flex-wrap gap-1.5">+ {perms.map((p) => <PermissionBadge key={p.id} perm={p} />)}+ </div>+ </div>+ ))}+ </div>+ );+ })()}</div>);}@@ -99,20 +124,21 @@ interface RoleFormProps {function RoleForm({ allPermissions, initial, onClose }: RoleFormProps) {const [name, setName] = useState(initial?.name ?? '');+ const [label, setLabel] = useState(initial?.label ?? initial?.name ?? '');const [description, setDescription] = useState(initial?.description ?? '');- const [selectedIds, setSelectedIds] = useState<Set<string>>(- new Set(initial?.permissions.map((p) => p.id) ?? [])+ const [selectedNames, setSelectedNames] = useState<Set<string>>(+ new Set(initial?.permissions.map((p) => p.name) ?? []));const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const categories = Array.from(new Set(allPermissions.map((p) => p.category ?? 'other'))).sort();- const toggle = (id: string) => {- setSelectedIds((prev) => {+ const toggle = (pname: string) => {+ setSelectedNames((prev) => {const next = new Set(prev);- if (next.has(id)) next.delete(id);- else next.add(id);+ if (next.has(pname)) next.delete(pname);+ else next.add(pname);return next;});};@@ -122,21 +148,28 @@ function RoleForm({ allPermissions, initial, onClose }: RoleFormProps) {setSaving(true);setError(null);try {- const url = initial ? `/api/v1/rbac/roles/${initial.id}` : '/api/v1/rbac/roles';- const method = initial ? 'PATCH' : 'POST';- const res = await fetch(url, {- method,- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ name, description: description || null, permission_ids: Array.from(selectedIds) }),- });- if (!res.ok) {- const data = await res.json();- throw new Error(data.detail ?? 'Save failed');+ // permission_names: every key is validated server-side against the+ // vocabulary; an unknown key returns a 400 that names it and lists+ // the valid set — never a silently dropped grant.+ if (initial) {+ await rbacApi.updateRole(initial.id, {+ label: label.trim() || initial.name,+ description: description || null,+ permission_names: [...selectedNames],+ });+ toast.success(`Role ${initial.name} updated — effective immediately for its ${initial.user_count} member(s).`);+ } else {+ await rbacApi.createRole({+ name: name.trim(),+ label: label.trim() || name.trim(),+ description: description || null,+ permission_names: [...selectedNames],+ });+ toast.success(`Role ${name.trim()} created.`);}- await mutate('/api/v1/rbac/roles');onClose();- } catch (e: any) {- setError(e.message);+ } catch (e) {+ setError((e as Error).message || 'Save failed');} finally {setSaving(false);}@@ -144,21 +177,36 @@ function RoleForm({ allPermissions, initial, onClose }: RoleFormProps) {return (<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">- <div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl">+ <div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl bg-white shadow-2xl"><div className="flex items-center justify-between border-b px-6 py-4">- <h2 className="text-lg font-semibold">{initial ? 'Edit Role' : 'Create Role'}</h2>+ <h2 className="text-lg font-semibold">{initial ? `Edit Role — ${initial.name}` : 'Create Role'}</h2><button onClick={onClose} className="text-gray-400 hover:text-gray-700">✕</button></div><div className="space-y-4 px-6 py-4">- {error && <p className="rounded bg-red-50 px-3 py-2 text-sm text-red-700">{error}</p>}+ {error && <p className="rounded bg-red-50 px-3 py-2 text-sm text-red-700" role="alert">{error}</p>}<div>- <label className="mb-1 block text-sm font-medium text-gray-700">Name</label>+ <label className="mb-1 block text-sm font-medium text-gray-700">Name (machine id, immutable)</label><inputvalue={name}onChange={(e) => setName(e.target.value)}- className="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"+ readOnly={Boolean(initial)}+ className="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 read-only:bg-gray-100 read-only:text-gray-500"placeholder="e.g. threat-hunter"/>+ <p className="mt-1 text-xs text-gray-500">+ {initial+ ? 'The machine name reaches tokens, audit records and URLs — it cannot be renamed. Edit the display label instead.'+ : 'Lowercase slug: letters, digits and dashes (e.g. threat-hunter). Reserved names (admin, viewer, infosec…) are refused.'}+ </p>+ </div>+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Display label</label>+ <input+ value={label}+ onChange={(e) => setLabel(e.target.value)}+ className="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"+ placeholder="e.g. Threat Hunter"+ /></div><div><label className="mb-1 block text-sm font-medium text-gray-700">Description</label>@@ -171,9 +219,9 @@ function RoleForm({ allPermissions, initial, onClose }: RoleFormProps) {</div><div><label className="mb-2 block text-sm font-medium text-gray-700">- Permissions ({selectedIds.size} selected)+ Permissions ({selectedNames.size} selected)</label>- <div className="max-h-64 overflow-y-auto space-y-3 rounded-lg border p-3">+ <div className="max-h-64 space-y-3 overflow-y-auto rounded-lg border p-3">{categories.map((cat) => (<div key={cat}><p className="mb-1 text-xs font-semibold uppercase tracking-wide text-gray-500">{cat}</p>@@ -181,11 +229,11 @@ function RoleForm({ allPermissions, initial, onClose }: RoleFormProps) {{allPermissions.filter((p) => (p.category ?? 'other') === cat).map((perm) => (- <label key={perm.id} className="flex cursor-pointer items-center gap-1.5">+ <label key={perm.name} className="flex cursor-pointer items-center gap-1.5" title={perm.description ?? ''}><inputtype="checkbox"- checked={selectedIds.has(perm.id)}- onChange={() => toggle(perm.id)}+ checked={selectedNames.has(perm.name)}+ onChange={() => toggle(perm.name)}className="rounded border-gray-300 text-indigo-600"/><span className="text-xs text-gray-700">{perm.name}</span>@@ -206,7 +254,7 @@ function RoleForm({ allPermissions, initial, onClose }: RoleFormProps) {disabled={saving}className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50">- {saving ? 'Saving…' : initial ? 'Update' : 'Create'}+ {saving ? 'Saving…' : initial ? 'Save changes' : 'Create role'}</button></div></div>@@ -233,21 +281,29 @@ const MOCK_ROLES: Role[] = [{id: 'role-1', tenant_id: 'default', name: 'SOC Analyst', description: 'Front-line analyst with read access to alerts, cases, and playbooks',is_system: true,+ user_count: 0,+ is_sso_default: false,permissions: MOCK_PERMISSIONS.filter((p) => ['p1', 'p3', 'p5', 'p7', 'p9', 'p12'].includes(p.id)),},{id: 'role-2', tenant_id: 'default', name: 'SOC Lead', description: 'Senior analyst with write access and playbook execution',is_system: true,+ user_count: 0,+ is_sso_default: false,permissions: MOCK_PERMISSIONS.filter((p) => ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p9', 'p12'].includes(p.id)),},{id: 'role-3', tenant_id: 'default', name: 'Admin', description: 'Full access to all features and settings',is_system: true,+ user_count: 0,+ is_sso_default: false,permissions: MOCK_PERMISSIONS,},{id: 'role-4', tenant_id: 'default', name: 'Detection Engineer', description: 'Manages detection rules and connector integrations',is_system: false,+ user_count: 0,+ is_sso_default: false,permissions: MOCK_PERMISSIONS.filter((p) => ['p1', 'p7', 'p8', 'p9', 'p10'].includes(p.id)),},];@@ -266,11 +322,40 @@ export function RBACView() {const [showCreate, setShowCreate] = useState(false);const [editingRole, setEditingRole] = useState<Role | null>(null);+ const [seeding, setSeeding] = useState(false);+ const [seedMsg, setSeedMsg] = useState<string | null>(null);++ // `roles:read` owns this screen server-side; a 403 means the operator is+ // not a platform admin. The management controls hide themselves rather+ // than rendering and failing — the server is the gate, the UI is just+ // honest about what the gate already answered.+ const rolesStatus = (rolesError as { status?: number } | undefined)?.status;+ const isAdmin = rolesStatus !== 403 && rolesStatus !== 401;++ const handleSeed = async () => {+ setSeeding(true);+ setSeedMsg(null);+ try {+ const res = await rbacApi.seedRoles();+ setSeedMsg(`Catalog seeded: ${res.roles} roles, ${res.permissions} permissions, ${res.user_roles} memberships.`);+ await reloadRoles();+ } catch (e) {+ setSeedMsg(`Seeding failed: ${(e as Error).message}`);+ } finally {+ setSeeding(false);+ }+ };const handleDelete = async (role: Role) => {- if (!confirm(`Delete role "${role.name}"?`)) return;- await apiFetch(`/api/v1/rbac/roles/${role.id}`, { method: 'DELETE' });- mutate('/api/v1/rbac/roles');+ if (!confirm(`Delete role "${role.label || role.name}"? This cannot be undone.`)) return;+ try {+ await rbacApi.deleteRole(role.id);+ toast.success(`Role ${role.name} deleted.`);+ await reloadRoles();+ } catch (e) {+ // 409 = still assigned (the server names the count); 403 = system role.+ toast.error((e as Error).message || 'Delete failed');+ }};return (@@ -280,12 +365,14 @@ export function RBACView() {<h2 className="text-xl font-bold text-gray-100">Roles & Permissions</h2><p className="mt-0.5 text-sm text-gray-500">Manage access control for your organization.</p></div>- <button- onClick={() => setShowCreate(true)}- className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700"- >- + New Role- </button>+ {isAdmin && (+ <button+ onClick={() => setShowCreate(true)}+ className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700"+ >+ + New Role+ </button>+ )}</div>{/* `roles` is `undefined` on failure outside the hosted demo, which@@ -319,33 +406,49 @@ export function RBACView() {<EmptyStateicon={EmptyStateIcons.shield}title="No roles defined yet"- description="Create your first role to start managing access control for your organization."+ description="Seed the standard catalog (viewer, infosec, admin) with its permissions, or create a custom role. Seeding is idempotent and backfills existing members' memberships so nobody loses access."action={- <button- type="button"- onClick={() => setShowCreate(true)}- className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors"- >- + New Role- </button>+ isAdmin ? (+ <div className="flex gap-3">+ <button+ type="button"+ onClick={handleSeed}+ disabled={seeding}+ className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors disabled:opacity-50"+ >+ {seeding ? 'Seeding…' : 'Seed roles'}+ </button>+ <button+ type="button"+ onClick={() => setShowCreate(true)}+ className="rounded-lg border border-gray-700 px-4 py-2 text-sm font-medium text-gray-200 hover:bg-gray-800 transition-colors"+ >+ + New Role+ </button>+ </div>+ ) : undefined}/>)}+ {seedMsg && (+ <p className="rounded-lg border border-indigo-800/60 bg-indigo-950/40 px-4 py-2 text-sm text-indigo-200">{seedMsg}</p>+ )}+{roles && roles.length > 0 && (<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">{roles.map((role) => (<RoleCardkey={role.id}role={role}- onEdit={(r) => setEditingRole(r)}- onDelete={handleDelete}+ onEdit={isAdmin ? (r) => setEditingRole(r) : () => undefined}+ onDelete={isAdmin ? handleDelete : () => undefined}/>))}</div>)}- {(showCreate || editingRole) && permissions && (+ {isAdmin && (showCreate || editingRole) && permissions && (<RoleFormallPermissions={permissions}initial={editingRole ?? undefined}diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsxindex 386db486b..92078163a 100644--- a/apps/web/src/components/settings/SettingsView.tsx+++ b/apps/web/src/components/settings/SettingsView.tsx@@ -46,9 +46,11 @@ import { Skeleton } from '@/components/ui/Skeleton';import { ErrorState } from '@/components/ui/ErrorState';import { EmptyState } from '@/components/ui/EmptyState';import { AutonomyPolicyPanel } from '@/components/settings/AutonomyPolicy';+import { AssignRoleModal } from '@/components/settings/AssignRoleModal';import { RetroHuntSettingsPanel } from './RetroHuntSettings';import { useTheme, type ThemePreference } from '@/components/theme/ThemeProvider';import { canUseDemoData } from '@/lib/demoFallback';+import { rbacApi, authApi } from '@/lib/api';// ─── Types ────────────────────────────────────────────────────────────────────@@ -655,6 +657,19 @@ function WorkspacePanel() {const activeCount = users?.filter((u) => u.is_active).length ?? 0;+ // Assignment is admin-only server-side (`roles:write`). The probe is the+ // same call the Roles screen makes: if it 403s, this operator is not a+ // platform admin and the per-member controls simply do not render. The+ // server remains the gate; this only stops offering a doomed button.+ const { data: rolesList, mutate: reprobeRoles } = useSWR('settings:rbac-roles-probe', () => rbacApi.listRoles(), {+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ });+ const canAssign = Array.isArray(rolesList);+ const [assignTarget, setAssignTarget] = useState<TenantUser | null>(null);+ const me = authApi.currentUser();+ const adminCount = users?.filter((u) => u.role === 'admin' && u.is_active).length ?? 0;+return (<div><PanelHeader@@ -728,13 +743,44 @@ function WorkspacePanel() {</p><p className="truncate text-xs text-gray-500">{u.email}</p></div>- <span className="rounded-full bg-gray-800 px-2.5 py-1 text-xs text-gray-300 ring-1 ring-gray-700">- {u.role}- </span>+ <div className="flex shrink-0 items-center gap-2">+ <span className="rounded-full bg-gray-800 px-2.5 py-1 text-xs text-gray-300 ring-1 ring-gray-700">+ {u.role}+ </span>+ {canAssign && (+ <button+ type="button"+ onClick={() => setAssignTarget(u)}+ disabled={u.id === me?.id && adminCount <= 1}+ title={+ u.id === me?.id && adminCount <= 1+ ? 'You are the only active admin — promote another admin before changing your own role'+ : `Change ${u.email}'s role`+ }+ className="rounded-md border border-gray-700 px-2 py-1 text-xs text-gray-300 hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-40"+ >+ Assign role+ </button>+ )}+ </div></li>))}</ul>)}+ {assignTarget && (+ <AssignRoleModal+ user={assignTarget}+ roles={rolesList ?? []}+ isSelf={assignTarget.id === me?.id}+ adminCount={adminCount}+ onClose={() => setAssignTarget(null)}+ onAssigned={() => {+ setAssignTarget(null);+ retryUsers();+ reprobeRoles();+ }}+ />+ )}</div></div>);diff --git a/apps/web/src/components/settings/UsersView.tsx b/apps/web/src/components/settings/UsersView.tsxnew file mode 100644index 000000000..b09c4c841--- /dev/null+++ b/apps/web/src/components/settings/UsersView.tsx@@ -0,0 +1,534 @@+'use client';++import { useCallback, useEffect, useMemo, useState } from 'react';+import useSWR from 'swr';+import toast from 'react-hot-toast';+import {+ adminUsersApi,+ authApi,+ rbacApi,+ type AdminUserRow,+ type RbacRole,+} from '@/lib/api';++/**+ * Users — admin-only member management with role assignment.+ *+ * Storage is multi-role (`user_roles`), so this screen is multi-select and+ * shows the effective merged permission set live in the edit modal. The+ * server (`/api/v1/admin/users/*`) is the authorization gate: every route+ * requires `roles:write`, refuses the last-admin demotion (409), requires a+ * reason, and revokes the target's sessions on any change.+ */++const PAGE_SIZE = 20;++function formatDate(iso: string | null): string {+ if (!iso) return '—';+ try {+ return new Date(iso).toLocaleString(undefined, {+ year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',+ });+ } catch {+ return iso;+ }+}++function RoleBadge({ name }: { name: string }) {+ const isAdmin = name === 'admin';+ return (+ <span+ className={+ isAdmin+ ? 'inline-block rounded bg-amber-500/20 px-2 py-0.5 text-xs font-bold uppercase tracking-wide text-amber-300 ring-1 ring-amber-500/40'+ : 'inline-block rounded bg-indigo-500/15 px-2 py-0.5 text-xs font-medium text-indigo-300 ring-1 ring-indigo-500/30'+ }+ >+ {name}+ </span>+ );+}++function StatusBadge({ active }: { active: boolean }) {+ return active ? (+ <span className="inline-flex items-center gap-1 text-xs text-emerald-300">+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" /> active+ </span>+ ) : (+ <span className="inline-flex items-center gap-1 text-xs text-amber-300">+ <span className="h-1.5 w-1.5 rounded-full bg-amber-400" /> disabled+ </span>+ );+}++interface EditRolesModalProps {+ user: AdminUserRow;+ roles: RbacRole[];+ isSelf: boolean;+ onClose: () => void;+ onSaved: () => void;+}++function EditRolesModal({ user, roles, isSelf, onClose, onSaved }: EditRolesModalProps) {+ const [selected, setSelected] = useState<Set<string>>(new Set(user.roles));+ const [reason, setReason] = useState('');+ const [confirmAdmin, setConfirmAdmin] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const grantingAdmin = !user.roles.includes('admin') && selected.has('admin');+ const unchanged =+ selected.size === user.roles.length && user.roles.every((r) => selected.has(r));+ const canSave =+ !saving && !unchanged && selected.size > 0 && reason.trim().length > 0 &&+ user.is_active && (!grantingAdmin || confirmAdmin);++ // Live merged permission preview: union over every selected role.+ const effective = useMemo(() => {+ const names = new Set<string>();+ for (const r of roles) {+ if (selected.has(r.name)) for (const p of r.permissions) names.add(p.name);+ }+ return [...names].sort();+ }, [roles, selected]);++ const toggle = (name: string) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(name)) next.delete(name);+ else next.add(name);+ return next;+ });+ setConfirmAdmin(false);+ };++ const save = async () => {+ setSaving(true);+ setError(null);+ try {+ await adminUsersApi.setRoles(user.id, [...selected], reason.trim());+ toast.success(+ `${user.email} → ${[...selected].join(', ')}. Their active sessions were revoked; the new permissions apply on their next sign-in.`,+ );+ onSaved();+ } catch (e) {+ // Safe, human-readable server detail only — never a stack trace.+ const msg = (e as Error).message || 'Role change failed';+ setError(msg);+ toast.error(msg);+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>+ <div+ className="max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-2xl border border-gray-800 bg-gray-900 p-6 shadow-2xl"+ onClick={(e) => e.stopPropagation()}+ >+ <h3 className="text-base font-semibold text-gray-100">Edit roles</h3>+ <p className="mt-1 text-sm text-gray-400">+ {user.username || user.email} · {user.email}+ {!user.is_active && (+ <span className="ml-2 rounded bg-amber-500/20 px-1.5 py-0.5 text-[10px] uppercase text-amber-300">+ disabled — assignments refused+ </span>+ )}+ </p>++ {error && (+ <p className="mt-3 rounded-lg border border-red-900/60 bg-red-950/40 px-3 py-2 text-sm text-red-300" role="alert">+ {error}+ </p>+ )}++ <p className="mt-4 text-xs font-semibold uppercase tracking-wide text-gray-500">+ Roles (multi-select — permissions merge)+ </p>+ <div className="mt-1 space-y-1.5">+ {roles.map((r) => (+ <label+ key={r.id}+ className="flex cursor-pointer items-start gap-2 rounded-lg border border-gray-800 bg-gray-950/60 px-3 py-2 hover:border-gray-700"+ >+ <input+ type="checkbox"+ checked={selected.has(r.name)}+ onChange={() => toggle(r.name)}+ disabled={!user.is_active}+ className="mt-0.5 rounded border-gray-600 text-indigo-600"+ />+ <span className="min-w-0">+ <span className="block text-sm text-gray-100">+ {r.label || r.name}+ <span className="ml-2 font-mono text-[11px] text-gray-500">{r.name}</span>+ {r.is_system && (+ <span className="ml-2 rounded bg-indigo-100/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-indigo-300">system</span>+ )}+ {r.is_sso_default && (+ <span className="ml-2 rounded bg-sky-500/20 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-sky-300">SSO default</span>+ )}+ </span>+ {r.description && <span className="block text-xs text-gray-500">{r.description}</span>}+ </span>+ </label>+ ))}+ </div>++ <p className="mt-4 text-xs font-semibold uppercase tracking-wide text-gray-500">+ Effective permissions — {effective.length} (read-only preview)+ </p>+ <div className="mt-1 max-h-32 overflow-y-auto rounded-lg border border-gray-800 bg-gray-950/80 p-2">+ {effective.length === 0 ? (+ <p className="text-xs italic text-gray-600">Select at least one role.</p>+ ) : (+ <div className="flex flex-wrap gap-1">+ {effective.map((p) => (+ <span key={p} className="rounded bg-gray-800 px-1.5 py-0.5 font-mono text-[10px] text-gray-300">{p}</span>+ ))}+ </div>+ )}+ </div>++ <label className="mt-4 block text-xs font-semibold uppercase tracking-wide text-gray-500" htmlFor="users-role-reason">+ Reason (required, audited)+ </label>+ <textarea+ id="users-role-reason"+ value={reason}+ onChange={(e) => setReason(e.target.value)}+ rows={2}+ maxLength={500}+ placeholder="Why are these roles changing? Stored in the audit log with actor, target, old and new roles."+ className="mt-1 w-full rounded-lg border border-gray-700 bg-gray-950 px-3 py-2 text-sm text-gray-100 placeholder-gray-600 focus:border-indigo-500 focus:outline-none"+ />++ {grantingAdmin && (+ <label className="mt-3 flex items-start gap-2 rounded-lg border border-amber-800/60 bg-amber-950/30 px-3 py-2 text-sm text-amber-200">+ <input type="checkbox" checked={confirmAdmin} onChange={(e) => setConfirmAdmin(e.target.checked)} className="mt-0.5" />+ <span>+ Granting <strong>admin</strong> confers full control of this workspace — users, roles, SSO and audit.+ Confirm you intend this.+ </span>+ </label>+ )}+ {isSelf && user.roles.includes('admin') && !selected.has('admin') && (+ <p className="mt-3 rounded-lg border border-red-900/60 bg-red-950/40 px-3 py-2 text-sm text-red-300" role="alert">+ You appear to be removing your own admin role. If you are the last active admin the server will refuse+ this with a 409 — promote another admin first.+ </p>+ )}++ <div className="mt-5 flex justify-end gap-3">+ <button type="button" onClick={onClose} className="rounded-lg px-4 py-2 text-sm text-gray-400 hover:bg-gray-800">+ Cancel+ </button>+ <button+ type="button"+ onClick={save}+ disabled={!canSave}+ className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50"+ >+ {saving ? 'Saving…' : unchanged ? 'No changes' : `Save ${selected.size} role${selected.size === 1 ? '' : 's'}`}+ </button>+ </div>+ </div>+ </div>+ );+}++export function UsersView() {+ const [search, setSearch] = useState('');+ const [appliedSearch, setAppliedSearch] = useState('');+ const [roleFilter, setRoleFilter] = useState('');+ const [statusFilter, setStatusFilter] = useState('');+ const [sort, setSort] = useState<'name' | 'email' | 'status' | 'created' | 'last_login'>('created');+ const [order, setOrder] = useState<'asc' | 'desc'>('desc');+ const [offset, setOffset] = useState(0);+ const [editing, setEditing] = useState<AdminUserRow | null>(null);+ const [busyId, setBusyId] = useState<string | null>(null);++ const qs = new URLSearchParams();+ if (appliedSearch) qs.set('search', appliedSearch);+ if (roleFilter) qs.set('role', roleFilter);+ if (statusFilter) qs.set('status', statusFilter);+ qs.set('sort', sort);+ qs.set('order', order);+ qs.set('limit', String(PAGE_SIZE));+ qs.set('offset', String(offset));++ const { data, error, mutate, isLoading } = useSWR(+ `admin-users:${qs.toString()}`,+ () => adminUsersApi.listUsers(Object.fromEntries(qs.entries()) as never),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ const { data: roles } = useSWR<RbacRole[]>('api/v1/rbac/roles', () => rbacApi.listRoles(), {+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ });++ const refresh = useCallback(() => { void mutate(); }, [mutate]);++ // Comparing against the signed-in operator's own id so the modal can warn+ // about self-demotion; storage is client-only, hence the effect.+ const [meId, setMeId] = useState<string | null>(null);+ useEffect(() => { setMeId(authApi.currentUser()?.id ?? null); }, []);++ const setStatus = async (u: AdminUserRow, active: boolean) => {+ const verb = active ? 'enable' : 'disable';+ const reason = window.prompt(`Reason to ${verb} ${u.email} (audited):`);+ if (reason === null) return;+ if (!reason.trim()) { toast.error('A reason is required.'); return; }+ setBusyId(u.id);+ try {+ await adminUsersApi.setStatus(u.id, active, reason.trim());+ toast.success(`${u.email} ${active ? 'enabled' : 'disabled'}${active ? '' : ' — cannot log in; role preserved, active sessions revoked.'}`);+ await mutate();+ } catch (e) {+ toast.error((e as Error).message || `Could not ${verb} this member.`);+ } finally {+ setBusyId(null);+ }+ };++ // Triple gate on a destructive, irreversible action: reason + typed+ // email confirmation + explicit final confirm. The server refuses+ // self-deletion and last-admin deletion regardless; the UI just makes+ // an accidental click hard.+ const deleteUser = async (u: AdminUserRow) => {+ if (meId && u.id === meId) {+ toast.error('You cannot delete your own account. Disable it instead.');+ return;+ }+ const reason = window.prompt(`Reason to PERMANENTLY DELETE ${u.email} (audited):`);+ if (reason === null || !reason.trim()) {+ if (reason !== null) toast.error('A reason is required.');+ return;+ }+ const typed = window.prompt(`This removes the account for good (audit history is kept). Type the email to confirm:`);+ if (typed === null) return;+ if (typed.trim().toLowerCase() !== u.email.toLowerCase()) {+ toast.error('Confirmation email did not match. Nothing was deleted.');+ return;+ }+ if (!window.confirm(`Delete ${u.email}? SSO users will be re-provisioned as viewer at next login.`)) return;+ setBusyId(u.id);+ try {+ await adminUsersApi.deleteUser(u.id, reason.trim());+ toast.success(`${u.email} deleted — sessions revoked, audit written.`);+ await mutate();+ } catch (e) {+ toast.error((e as Error).message || 'Could not delete this member.');+ } finally {+ setBusyId(null);+ }+ };++ const rows = data?.items ?? [];+ const total = data?.total ?? 0;+ const failed = Boolean(error) && !data;+ const empty = !failed && !isLoading && rows.length === 0;++ const headerSort = (col: 'name' | 'email' | 'status' | 'created' | 'last_login', label: string) => (+ <button+ type="button"+ className="inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300"+ onClick={() => {+ if (sort === col) setOrder(order === 'asc' ? 'desc' : 'asc');+ else { setSort(col); setOrder('asc'); }+ setOffset(0);+ }}+ >+ {label}+ {sort === col && <span className="text-indigo-400">{order === 'asc' ? '↑' : '↓'}</span>}+ </button>+ );++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center gap-3">+ <form+ className="flex flex-wrap items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ setAppliedSearch(search.trim());+ setOffset(0);+ }}+ >+ <input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search name or email…"+ className="w-56 rounded-lg border border-gray-700 bg-gray-950 px-3 py-1.5 text-sm text-gray-100 placeholder-gray-600 focus:border-indigo-500 focus:outline-none"+ />+ <select+ value={roleFilter}+ onChange={(e) => { setRoleFilter(e.target.value); setOffset(0); }}+ className="rounded-lg border border-gray-700 bg-gray-950 px-2 py-1.5 text-sm text-gray-200"+ >+ <option value="">All roles</option>+ {(roles ?? []).map((r) => (+ <option key={r.id} value={r.name}>{r.label || r.name}</option>+ ))}+ </select>+ <select+ value={statusFilter}+ onChange={(e) => { setStatusFilter(e.target.value); setOffset(0); }}+ className="rounded-lg border border-gray-700 bg-gray-950 px-2 py-1.5 text-sm text-gray-200"+ >+ <option value="">Any status</option>+ <option value="active">Active</option>+ <option value="disabled">Disabled</option>+ </select>+ <button type="submit" className="rounded-lg border border-gray-700 px-3 py-1.5 text-sm text-gray-200 hover:bg-gray-800">+ Search+ </button>+ </form>+ <span className="ml-auto text-xs text-gray-500">{failed ? '' : `${total} member${total === 1 ? '' : 's'}`}</span>+ </div>++ {failed && (+ <div className="rounded-xl border border-red-900/60 bg-red-950/30 px-4 py-6 text-center">+ <p className="text-sm text-red-300">The user list could not be loaded.</p>+ <p className="mt-1 text-[11px] text-gray-500">{(error as Error).message || 'Unknown error'}</p>+ <button type="button" onClick={refresh} className="mt-3 rounded-lg border border-red-800 px-3 py-1.5 text-xs text-red-200 hover:bg-red-900/40">+ Retry+ </button>+ </div>+ )}++ {empty && (+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 px-4 py-12 text-center">+ <p className="text-sm text-gray-300">No users match these filters.</p>+ <p className="mt-1 text-[11px] text-gray-600">+ This is an empty result set, not a load failure — the server answered successfully.+ </p>+ </div>+ )}++ {!failed && (+ <div className="overflow-x-auto rounded-xl border border-gray-800/60">+ <table className="w-full text-left text-sm">+ <thead className="border-b border-gray-800 bg-gray-900/70">+ <tr>+ <th className="px-4 py-2.5">{headerSort('name', 'Name')}</th>+ <th className="px-4 py-2.5">{headerSort('email', 'Email')}</th>+ <th className="px-4 py-2.5">{headerSort('status', 'Status')}</th>+ <th className="px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-gray-500">Role(s)</th>+ <th className="px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-gray-500">Provider</th>+ <th className="px-4 py-2.5">{headerSort('last_login', 'Last login')}</th>+ <th className="px-4 py-2.5">{headerSort('created', 'Created')}</th>+ <th className="px-4 py-2.5 text-right text-xs font-semibold uppercase tracking-wide text-gray-500">Actions</th>+ </tr>+ </thead>+ <tbody className="divide-y divide-gray-800/60">+ {isLoading && rows.length === 0 && (+ Array.from({ length: 4 }).map((_, i) => (+ <tr key={i}>+ {Array.from({ length: 8 }).map((__, j) => (+ <td key={j} className="px-4 py-3"><div className="h-4 w-full max-w-28 animate-pulse rounded bg-gray-800/70" /></td>+ ))}+ </tr>+ ))+ )}+ {rows.map((u) => (+ <tr key={u.id} className="hover:bg-gray-900/50">+ <td className="px-4 py-3 text-gray-100">{u.username || '—'}</td>+ <td className="px-4 py-3 text-gray-300">{u.email}</td>+ <td className="px-4 py-3"><StatusBadge active={u.is_active} /></td>+ <td className="px-4 py-3">+ <div className="flex flex-wrap gap-1">+ {(u.roles.length ? u.roles : [u.role]).map((r) => <RoleBadge key={r} name={r} />)}+ </div>+ </td>+ <td className="px-4 py-3 text-xs uppercase tracking-wide text-gray-400">{u.provider}</td>+ <td className="px-4 py-3 text-xs text-gray-400">{formatDate(u.last_login)}</td>+ <td className="px-4 py-3 text-xs text-gray-400">{formatDate(u.created_at)}</td>+ <td className="px-4 py-3">+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={() => setEditing(u)}+ className="rounded-lg border border-gray-700 px-2.5 py-1 text-xs text-gray-200 hover:bg-gray-800"+ >+ Edit role+ </button>+ {u.is_active ? (+ <button+ type="button"+ disabled={busyId === u.id}+ onClick={() => setStatus(u, false)}+ className="rounded-lg border border-amber-800/60 px-2.5 py-1 text-xs text-amber-300 hover:bg-amber-950/40 disabled:opacity-50"+ >+ Disable+ </button>+ ) : (+ <button+ type="button"+ disabled={busyId === u.id}+ onClick={() => setStatus(u, true)}+ className="rounded-lg border border-emerald-800/60 px-2.5 py-1 text-xs text-emerald-300 hover:bg-emerald-950/40 disabled:opacity-50"+ >+ Enable+ </button>+ )}+ <button+ type="button"+ disabled={busyId === u.id || (meId !== null && u.id === meId)}+ onClick={() => deleteUser(u)}+ title={meId !== null && u.id === meId ? 'You cannot delete your own account' : 'Permanently delete this member'}+ className="rounded-lg border border-red-800/70 px-2.5 py-1 text-xs text-red-300 hover:bg-red-950/50 disabled:cursor-not-allowed disabled:opacity-40"+ >+ Delete+ </button>+ </div>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}++ {!failed && total > PAGE_SIZE && (+ <div className="flex items-center justify-end gap-3 text-sm text-gray-400">+ <button+ type="button"+ disabled={offset === 0}+ onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}+ className="rounded-lg border border-gray-700 px-3 py-1.5 hover:bg-gray-800 disabled:opacity-40"+ >+ ← Prev+ </button>+ <span className="text-xs">+ {offset + 1}–{Math.min(offset + PAGE_SIZE, total)} of {total}+ </span>+ <button+ type="button"+ disabled={offset + PAGE_SIZE >= total}+ onClick={() => setOffset(offset + PAGE_SIZE)}+ className="rounded-lg border border-gray-700 px-3 py-1.5 hover:bg-gray-800 disabled:opacity-40"+ >+ Next →+ </button>+ </div>+ )}++ {editing && roles && (+ <EditRolesModal+ user={editing}+ roles={roles}+ isSelf={editing.id === meId}+ onClose={() => setEditing(null)}+ onSaved={() => {+ setEditing(null);+ // Row updates in place via SWR revalidation — no full reload.+ void mutate();+ }}+ />+ )}+ </div>+ );+}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex b20358e7e..a25f7c91e 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -702,6 +702,160 @@ export const retroHuntsApi = {},};+export interface RbacPermission {+ id: string;+ name: string;+ description: string | null;+ category: string | null;+}++export interface RbacRole {+ id: string;+ tenant_id: string;+ name: string;+ label?: string | null;+ description: string | null;+ is_system: boolean;+ permissions: RbacPermission[];+ user_count: number;+ is_sso_default: boolean;+}++export interface UserRoleOut {+ user_id: string;+ role_id: string;+ role_name: string;+}++export interface RbacPermissionLite {+ name: string;+ description?: string | null;+ category?: string | null;+}++export interface AdminUserRow {+ id: string;+ email: string;+ username?: string | null;+ is_active: boolean;+ role: string;+ roles: string[];+ provider: string;+ last_login: string | null;+ created_at: string;+ effective_permissions: string[];+}++export interface AdminUserPage {+ items: AdminUserRow[];+ total: number;+ limit: number;+ offset: number;+}++/**+ * RBAC console surface. All endpoints are admin-gated server-side+ * (`roles:read` / `roles:write`); a 403 here means the signed-in operator+ * is not a platform admin, and the screens must render read-only or hide+ * management controls accordingly — never pretend success.+ */+export const rbacApi = {+ async listRoles(): Promise<RbacRole[]> {+ return request<RbacRole[]>('/api/v1/rbac/roles');+ },++ async listPermissions(): Promise<RbacPermissionLite[]> {+ return request<RbacPermissionLite[]>('/api/v1/rbac/permissions');+ },++ async seedRoles(): Promise<{ seeded: boolean; permissions: number; roles: number; role_permissions: number; user_roles: number }> {+ return request('/api/v1/rbac/roles/seed', { method: 'POST' });+ },++ async createRole(body: { name: string; label?: string; description?: string | null; permission_names: string[] }): Promise<RbacRole> {+ return request<RbacRole>('/api/v1/rbac/roles', { method: 'POST', body: JSON.stringify(body) });+ },++ /** Update label/description and (optionally) replace the permission set. */+ async updateRole(roleId: string, body: { label?: string; description?: string | null; permission_names?: string[] }): Promise<RbacRole> {+ return request<RbacRole>(`/api/v1/rbac/roles/${roleId}`, { method: 'PATCH', body: JSON.stringify(body) });+ },++ async deleteRole(roleId: string): Promise<void> {+ await apiFetch(`/api/v1/rbac/roles/${roleId}`, { method: 'DELETE' });+ },++ /** Replace a user's primary role. Takes effect on their next request. */+ async setPrimaryRole(userId: string, roleName: string, reason: string): Promise<UserRoleOut> {+ return request<UserRoleOut>(`/api/v1/rbac/users/${userId}/role`, {+ method: 'PUT',+ body: JSON.stringify({ role_name: roleName, reason }),+ });+ },+};++/**+ * Admin Users screen. Server-gated to `roles:write` (admin) on every route;+ * role changes revoke the target's sessions and take effect immediately.+ */+export const adminUsersApi = {+ async listUsers(params: {+ search?: string;+ role?: string;+ status?: 'active' | 'disabled';+ sort?: 'name' | 'email' | 'status' | 'created' | 'last_login';+ order?: 'asc' | 'desc';+ limit?: number;+ offset?: number;+ } = {}): Promise<AdminUserPage> {+ const qs = new URLSearchParams();+ Object.entries(params).forEach(([k, v]) => {+ if (v !== undefined && v !== null && v !== '') qs.set(k, String(v));+ });+ const suffix = qs.toString();+ return request<AdminUserPage>(`/api/v1/admin/users${suffix ? `?${suffix}` : ''}`);+ },++ async getUser(userId: string): Promise<AdminUserRow> {+ return request<AdminUserRow>(`/api/v1/admin/users/${userId}`);+ },++ async setRoles(userId: string, roleNames: string[], reason: string): Promise<AdminUserRow> {+ return request<AdminUserRow>(`/api/v1/admin/users/${userId}/roles`, {+ method: 'PUT',+ body: JSON.stringify({ role_names: roleNames, reason }),+ });+ },++ async addRole(userId: string, roleName: string, reason: string): Promise<AdminUserRow> {+ return request<AdminUserRow>(`/api/v1/admin/users/${userId}/roles`, {+ method: 'POST',+ body: JSON.stringify({ role_name: roleName, reason }),+ });+ },++ async removeRole(userId: string, roleName: string, reason: string): Promise<AdminUserRow> {+ const qs = reason ? `?reason=${encodeURIComponent(reason)}` : '';+ return request<AdminUserRow>(`/api/v1/admin/users/${userId}/roles/${encodeURIComponent(roleName)}${qs}`, {+ method: 'DELETE',+ });+ },++ async setStatus(userId: string, isActive: boolean, reason: string): Promise<AdminUserRow> {+ return request<AdminUserRow>(`/api/v1/admin/users/${userId}`, {+ method: 'PATCH',+ body: JSON.stringify({ is_active: isActive, reason }),+ });+ },++ async deleteUser(userId: string, reason: string): Promise<void> {+ await request<void>(+ `/api/v1/admin/users/${userId}?reason=${encodeURIComponent(reason)}`,+ { method: 'DELETE' },+ );+ },+};+export const tenantsApi = {/*** Lightweight tenant identity for the SOC console TopBar.diff --git a/docs/api/API_REFERENCE.md b/docs/api/API_REFERENCE.mdindex 9719cf825..5ed5a873e 100644--- a/docs/api/API_REFERENCE.md+++ b/docs/api/API_REFERENCE.md@@ -402,8 +402,33 @@ tenant) with ZSET-backed top-N sorted queues for O(log N) reads.## 11. Authentication* JWT issued by `POST /api/v1/auth/login`.-* API keys via `Authorization: ApiKey <key>` header.+* API keys via `Authorization: ApiKey *** header.* All requests must specify a tenant context — either implicit (from JWT) or explicit (`X-Tenant-Id` header for service-to-service calls).+* SSO (feature-flagged `SSO_ENABLED`): `GET /api/v1/auth/sso/status` advertises+ enabled connections; the OIDC callback lands the session on `/login?next=…`+ with tokens in the URL fragment (never in query strings or server logs).+ JIT provisioning defaults to `viewer`; `admin` is unreachable from SSO by+ construction unless an explicit allowlisted admin group mapping exists.++## 11a. Users Administration — `/api/v1/admin/users`++Admin only (`roles:write`); every mutation requires a `reason`, writes an+audit row, and revokes the target's active sessions. See+[Roles & Permissions](roles-and-permissions.md) for the full model.++| Method | Path | Purpose |+|--------|------|---------|+| `GET` | `/api/v1/admin/users` | Paginated list (`q`, `role`, `status`, `sort`, `dir`, `page`, `size`) — server-side only |+| `GET` | `/api/v1/admin/users/{id}` | Detail incl. roles, provider, last login |+| `PUT` | `/api/v1/admin/users/{id}/roles` | Replace role set (catalog-validated, last-admin guard) |+| `POST` | `/api/v1/admin/users/{id}/roles` | Add one role |+| `DELETE` | `/api/v1/admin/users/{id}/roles/{role}` | Remove one role |+| `PATCH` | `/api/v1/admin/users/{id}` | Enable/disable (`{"is_active": bool}`) |+| `DELETE` | `/api/v1/admin/users/{id}?reason=…` | Permanent delete; audit retains identity snapshot |++Errors: `401` unauthenticated · `403`/`401` insufficient role (fail-closed)+· `404` unknown or cross-tenant id · `409` self-delete or last-admin+violation · `422` missing/oversized reason.---diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex d25a53955..a4b21af72 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -6690,7 +6690,14 @@ paths:tags:- rbacsummary: List Roles- description: List all roles for the current tenant.+ description: 'List all roles for the current tenant, with permissions and headcount.+++ `user_count` counts this tenant''s users holding each role — the Roles++ screen shows it so an operator can see who would move when a role''s++ grants change, not just what the grants are.'operationId: list_roles_api_v1_rbac_roles_getresponses:'200':@@ -6708,7 +6715,14 @@ paths:tags:- rbacsummary: Create Role- description: Create a custom role for the current tenant.+ description: 'Create a custom role for the current tenant.+++ `permission_names` (validated against the platform vocabulary, unknown++ keys → 400 naming them) is the console-facing shape; `permission_ids`++ stays for API clients. Both may be sent; they merge.'operationId: create_role_api_v1_rbac_roles_postrequestBody:content:@@ -6731,6 +6745,35 @@ paths:$ref: '#/components/schemas/HTTPValidationError'security:- HTTPBearer: []+ /api/v1/rbac/roles/seed:+ post:+ tags:+ - rbac+ summary: Seed Roles+ description: 'Seed this tenant''s catalog from `app.core.rbac_catalog`.+++ Idempotent — safe to call from the Roles screen''s empty state ("Seed++ roles") as often as you like. Catalog rows and the membership backfill++ land in one transaction, so a half-seeded tenant (roles with no++ members, every member resolving to zero permissions) is not a state this++ endpoint can leave behind.'+ operationId: seed_roles_api_v1_rbac_roles_seed_post+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ additionalProperties: true+ type: object+ title: Response Seed Roles Api V1 Rbac Roles Seed Post+ security:+ - HTTPBearer: []/api/v1/rbac/roles/{role_id}:get:tags:@@ -6764,6 +6807,15 @@ paths:tags:- rbacsummary: Update Role+ description: 'Edit label/description (and, optionally, replace the permission+ set).+++ System roles are refused with an explanatory 403 body that names the++ role: the lock is a server rule, not a hidden button. `name` cannot be++ edited — see RoleUpdate.'operationId: update_role_api_v1_rbac_roles__role_id__patchsecurity:- HTTPBearer: []@@ -6796,35 +6848,539 @@ paths:$ref: '#/components/schemas/HTTPValidationError'delete:tags:- - rbac- summary: Delete Role- operationId: delete_role_api_v1_rbac_roles__role_id__delete+ - rbac+ summary: Delete Role+ operationId: delete_role_api_v1_rbac_roles__role_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: role_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Role Id+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/rbac/roles/{role_id}/permissions:+ put:+ tags:+ - rbac+ summary: Replace Role Permissions+ description: 'Replace the role''s full permission set (atomic, audited, before/after).+++ Accepts `{"permissions": ["alerts:read", ...]}` or a bare list++ `["alerts:read", ...]` — both shapes validate every key against the++ vocabulary first, so an unknown key is a 400 that names it, never a++ silently dropped grant.'+ operationId: replace_role_permissions_api_v1_rbac_roles__role_id__permissions_put+ security:+ - HTTPBearer: []+ parameters:+ - name: role_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Role Id+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Body_replace_role_permissions_api_v1_rbac_roles__role_id__permissions_put'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RoleOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ post:+ tags:+ - rbac+ summary: Add Role Permission+ operationId: add_role_permission_api_v1_rbac_roles__role_id__permissions_post+ security:+ - HTTPBearer: []+ parameters:+ - name: role_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Role Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PermissionNameIn'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RoleOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/rbac/roles/{role_id}/permissions/{permission_name}:+ delete:+ tags:+ - rbac+ summary: Remove Role Permission+ operationId: remove_role_permission_api_v1_rbac_roles__role_id__permissions__permission_name__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: role_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Role Id+ - name: permission_name+ in: path+ required: true+ schema:+ type: string+ title: Permission Name+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RoleOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/rbac/users/{user_id}/roles:+ get:+ tags:+ - rbac+ summary: Get User Roles+ description: List roles assigned to a user within the current tenant.+ operationId: get_user_roles_api_v1_rbac_users__user_id__roles_get+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/UserRoleOut'+ title: Response Get User Roles Api V1 Rbac Users User Id Roles Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ post:+ tags:+ - rbac+ summary: Assign Role+ description: Assign a role to a user.+ operationId: assign_role_api_v1_rbac_users__user_id__roles_post+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UserRoleAssignment'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UserRoleOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/rbac/users/{user_id}/role:+ put:+ tags:+ - rbac+ summary: Set Primary Role+ description: "Replace the user's primary role — the console's `Assign role`\+ \ action.\n\nMulti-role storage, single-role product: the assignment set becomes\+ \ the\none chosen role, and `users.role` — the string the JWT/static path\n\+ reads — is mirrored to match, so the two authorization paths cannot\ndisagree\+ \ after this call. Takes effect on the target's next request:\nthe permission\+ \ cache version bumps, and the verifier re-reads\n`users.role` from the database.\+ \ No re-login required.\n\nRefusals, all before any write:\n * 404 target\+ \ not in tenant; 400 unknown role name (naming the valid\n set) or disabled\+ \ target; 403 this caller may not confer the role's\n permissions; 409\+ \ this would empty the tenant of active admins."+ operationId: set_primary_role_api_v1_rbac_users__user_id__role_put+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PrimaryRoleAssignment'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UserRoleOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/rbac/users/{user_id}/roles/{role_id}:+ delete:+ tags:+ - rbac+ summary: Revoke Role+ description: 'Revoke a role from a user.+++ Last-admin lockout guard: revoking the role that IS the tenant''s admin++ role from the last active holder is refused with 409, same rule as++ `PUT /users/{id}/role` and `PATCH /tenants/me/users/{id}` — every door++ that removes management authority checks it, because "one of the doors++ remembers" is no control at all.'+ operationId: revoke_role_api_v1_rbac_users__user_id__roles__role_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ - name: role_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Role Id+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/admin/users:+ get:+ tags:+ - admin-users+ summary: List Users+ description: Paginated member list with live roles, provider, and headcounts.+ operationId: list_users_api_v1_admin_users_get+ security:+ - HTTPBearer: []+ parameters:+ - name: search+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ maxLength: 200+ - type: 'null'+ title: Search+ - name: role+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ maxLength: 100+ - type: 'null'+ title: Role+ - name: status+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ pattern: ^(active|disabled)$+ - type: 'null'+ title: Status+ - name: sort+ in: query+ required: false+ schema:+ type: string+ pattern: ^(name|email|status|created|last_login)$+ default: created+ title: Sort+ - name: order+ in: query+ required: false+ schema:+ type: string+ pattern: ^(asc|desc)$+ default: desc+ title: Order+ - name: limit+ in: query+ required: false+ schema:+ type: integer+ maximum: 200+ minimum: 1+ default: 50+ title: Limit+ - name: offset+ in: query+ required: false+ schema:+ type: integer+ minimum: 0+ default: 0+ title: Offset+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UserPage'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/admin/users/{user_id}:+ get:+ tags:+ - admin-users+ summary: Get User+ operationId: get_user_api_v1_admin_users__user_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AdminUserOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ patch:+ tags:+ - admin-users+ summary: Patch Status+ description: 'Enable / disable a member. Disabling ends their sessions immediately;++ the role assignment is preserved untouched.'+ operationId: patch_status_api_v1_admin_users__user_id__patch+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UserPatch'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AdminUserOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ delete:+ tags:+ - admin-users+ summary: Delete User+ description: "Permanently delete a member.\n\nHard delete, deliberately: `audit_log.actor_id`\+ \ and every other\nattribution column SET NULL on delete, so the audit trail\+ \ keeps each\naction with the name attributed in the audit payload below —\+ \ the\nhistory survives, the identity row does not. Ownership rows\n(`user_roles`,\+ \ `aisoc_sso_identities`, `saved_views`, …) cascade.\n\nGuards, in order:\n\+ * a member cannot delete their own account (disable yourself instead);\n*\+ \ the last active admin cannot be deleted (`_guard_last_admin`);\n* sessions\+ \ are ended before the row goes, so any in-flight token dies\n at the next\+ \ request even if a race briefly revives the row.\n\nAn SSO-provisioned account\+ \ that is deleted will be re-created as a\n`viewer` by JIT on the next successful\+ \ login — deletion removes the\naccount, not the IdP's right to provision\+ \ it. Say so in the reason if\nthat matters for the case."+ operationId: delete_user_api_v1_admin_users__user_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: User Id+ - name: reason+ in: query+ required: true+ schema:+ type: string+ minLength: 1+ maxLength: 500+ title: Reason+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/admin/users/{user_id}/effective-permissions:+ get:+ tags:+ - admin-users+ summary: Effective Permissions+ description: 'Merged permission set for one user — the modal''s read-only preview.+++ Answers from `user_roles` only (the catalog), not the static map: what++ the modal shows is what the enforcement layer will check once the++ tenant is catalog-backed.'+ operationId: effective_permissions_api_v1_admin_users__user_id__effective_permissions_getsecurity:- HTTPBearer: []parameters:- - name: role_id+ - name: user_idin: pathrequired: trueschema:type: stringformat: uuid- title: Role Id+ title: User Idresponses:- '204':+ '200':description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ type: string+ title: Response Effective Permissions Api V1 Admin Users User Id Effective+ Permissions Get'422':description: Validation Errorcontent:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'- /api/v1/rbac/users/{user_id}/roles:- get:+ /api/v1/admin/users/{user_id}/roles:+ put:tags:- - rbac- summary: Get User Roles- description: List roles assigned to a user within the current tenant.- operationId: get_user_roles_api_v1_rbac_users__user_id__roles_get+ - admin-users+ summary: Set Roles+ description: Replace the user's full role set (multi-role replace semantics).+ operationId: set_roles_api_v1_admin_users__user_id__roles_putsecurity:- HTTPBearer: []parameters:@@ -6835,16 +7391,19 @@ paths:type: stringformat: uuidtitle: User Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RoleSetIn'responses:'200':description: Successful Responsecontent:application/json:schema:- type: array- items:- $ref: '#/components/schemas/UserRoleOut'- title: Response Get User Roles Api V1 Rbac Users User Id Roles Get+ $ref: '#/components/schemas/AdminUserOut''422':description: Validation Errorcontent:@@ -6853,10 +7412,9 @@ paths:$ref: '#/components/schemas/HTTPValidationError'post:tags:- - rbac- summary: Assign Role- description: Assign a role to a user.- operationId: assign_role_api_v1_rbac_users__user_id__roles_post+ - admin-users+ summary: Add Role+ operationId: add_role_api_v1_admin_users__user_id__roles_postsecurity:- HTTPBearer: []parameters:@@ -6872,27 +7430,26 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/UserRoleAssignment'+ $ref: '#/components/schemas/RoleAddIn'responses:'201':description: Successful Responsecontent:application/json:schema:- $ref: '#/components/schemas/UserRoleOut'+ $ref: '#/components/schemas/AdminUserOut''422':description: Validation Errorcontent:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'- /api/v1/rbac/users/{user_id}/roles/{role_id}:+ /api/v1/admin/users/{user_id}/roles/{role_name}:delete:tags:- - rbac- summary: Revoke Role- description: Revoke a role from a user.- operationId: revoke_role_api_v1_rbac_users__user_id__roles__role_id__delete+ - admin-users+ summary: Remove Role+ operationId: remove_role_api_v1_admin_users__user_id__roles__role_name__deletesecurity:- HTTPBearer: []parameters:@@ -6903,16 +7460,19 @@ paths:type: stringformat: uuidtitle: User Id- - name: role_id+ - name: role_namein: pathrequired: trueschema:type: string- format: uuid- title: Role Id+ title: Role Nameresponses:- '204':+ '200':description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AdminUserOut''422':description: Validation Errorcontent:@@ -17865,6 +18425,60 @@ components:- expires_at- urltitle: AdminInviteWire+ AdminUserOut:+ properties:+ id:+ type: string+ format: uuid+ title: Id+ email:+ type: string+ title: Email+ username:+ type: string+ title: Username+ is_active:+ type: boolean+ title: Is Active+ role:+ type: string+ title: Role+ roles:+ items:+ type: string+ type: array+ title: Roles+ default: []+ provider:+ type: string+ title: Provider+ default: local+ last_login:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Last Login+ created_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Created At+ effective_permissions:+ items:+ type: string+ type: array+ title: Effective Permissions+ default: []+ type: object+ required:+ - id+ - username+ - is_active+ - role+ title: AdminUserOutAgentHuntRequest:properties:hypothesis:@@ -20073,6 +20687,16 @@ components:- type_breakdown- blast_radius_scoretitle: BlastRadiusResponse+ Body_replace_role_permissions_api_v1_rbac_roles__role_id__permissions_put:+ properties:+ body:+ anyOf:+ - $ref: '#/components/schemas/PermissionNamesIn'+ - type: 'null'+ raw:+ title: Raw+ type: object+ title: Body_replace_role_permissions_api_v1_rbac_roles__role_id__permissions_putBody_upload_asset_api_v1_branding_assets__kind__post:properties:file:@@ -28578,6 +29202,41 @@ components:- tenant_id- created_attitle: PeerGroupOut+ PermissionNameIn:+ properties:+ permission:+ type: string+ maxLength: 200+ minLength: 1+ title: Permission+ type: object+ required:+ - permission+ title: PermissionNameIn+ PermissionNamesIn:+ properties:+ permissions:+ items:+ type: string+ type: array+ minItems: 0+ title: Permissions+ type: object+ required:+ - permissions+ title: PermissionNamesIn+ description: 'Body for `PUT /roles/{id}/permissions`.+++ The console sends `{"permissions": ["alerts:read", ...]}` and the++ route additionally accepts the bare list shape (see the endpoint);++ either way every key is validated against the platform vocabulary++ before anything is deleted, so an unknown key is a 400 that names the++ valid set instead of a silent partial update.'PermissionOut:properties:id:@@ -29131,6 +29790,35 @@ components:- suppressed- changedtitle: PreviewRow+ PrimaryRoleAssignment:+ properties:+ role_name:+ type: string+ maxLength: 100+ minLength: 1+ title: Role Name+ reason:+ anyOf:+ - type: string+ maxLength: 500+ - type: 'null'+ title: Reason+ type: object+ required:+ - role_name+ title: PrimaryRoleAssignment+ description: 'Body for `PUT /rbac/users/{id}/role` — replaces the primary role.+++ `role_name` names a seeded catalog role (`viewer` | `infosec` | `admin`++ or a tenant custom role); the server resolves it against this tenant''s++ catalog and refuses anything it does not recognize with a 400 naming the++ valid set — a 500 would leak the schema, and a silent 404 would make a++ typo look like an outage.'PromotionRequest:properties:scope_kind:@@ -30390,11 +31078,36 @@ components:- last_evaluated_at- updated_attitle: RiskProfileOut+ RoleAddIn:+ properties:+ role_name:+ type: string+ maxLength: 100+ minLength: 1+ title: Role Name+ reason:+ type: string+ maxLength: 500+ minLength: 1+ title: Reason+ type: object+ required:+ - role_name+ - reason+ title: RoleAddInRoleIn:properties:name:type: string+ maxLength: 100+ minLength: 2title: Name+ label:+ anyOf:+ - type: string+ maxLength: 200+ - type: 'null'+ title: Labeldescription:anyOf:- type: string@@ -30407,6 +31120,12 @@ components:type: arraytitle: Permission Idsdefault: []+ permission_names:+ items:+ type: string+ type: array+ title: Permission Names+ default: []type: objectrequired:- name@@ -30424,6 +31143,11 @@ components:name:type: stringtitle: Name+ label:+ anyOf:+ - type: string+ - type: 'null'+ title: Labeldescription:anyOf:- type: string@@ -30438,6 +31162,14 @@ components:type: arraytitle: Permissionsdefault: []+ user_count:+ type: integer+ title: User Count+ default: 0+ is_sso_default:+ type: boolean+ title: Is Sso Default+ default: falsetype: objectrequired:- id@@ -30446,13 +31178,38 @@ components:- description- is_systemtitle: RoleOut+ RoleSetIn:+ properties:+ role_names:+ items:+ type: string+ type: array+ minItems: 1+ title: Role Names+ reason:+ type: string+ maxLength: 500+ minLength: 1+ title: Reason+ type: object+ required:+ - role_names+ - reason+ title: RoleSetInRoleUpdate:properties:name:anyOf:- type: string+ maxLength: 100- type: 'null'title: Name+ label:+ anyOf:+ - type: string+ maxLength: 200+ - type: 'null'+ title: Labeldescription:anyOf:- type: string@@ -30466,8 +31223,28 @@ components:type: array- type: 'null'title: Permission Ids+ permission_names:+ anyOf:+ - items:+ type: string+ type: array+ - type: 'null'+ title: Permission Namestype: objecttitle: RoleUpdate+ description: 'The machine `name` is immutable after create: it is mirrored into++ users.role, resolved against the JWT static map, and written into audit++ resource strings; renaming a live role would strand all three. The field++ stays on the wire (SDK clients generated against earlier releases send++ it) and is validated as a no-op: omit it, or send the role''s current++ name — an actual rename is a 400 that says why. Edit `label` and++ `description` for the human-facing text.'RotateScimTokenRequest:properties:grace_hours:@@ -34882,6 +35659,52 @@ components:- role- is_activetitle: UserMeResponse+ UserPage:+ properties:+ items:+ items:+ $ref: '#/components/schemas/AdminUserOut'+ type: array+ title: Items+ total:+ type: integer+ title: Total+ limit:+ type: integer+ title: Limit+ offset:+ type: integer+ title: Offset+ type: object+ required:+ - items+ - total+ - limit+ - offset+ title: UserPage+ UserPatch:+ properties:+ is_active:+ type: boolean+ title: Is Active+ reason:+ anyOf:+ - type: string+ maxLength: 500+ - type: 'null'+ title: Reason+ type: object+ required:+ - is_active+ title: UserPatch+ description: 'Body for PATCH /admin/users/{id} — status changes only.+++ Roles deliberately do not live on this body: a status patch that can++ also carry roles turns every future "toggle" feature into a privilege++ escalation vector. Roles move through the explicit role routes.'UserResponse:properties:id:@@ -34935,6 +35758,12 @@ components:type: stringformat: uuidtitle: Role Id+ reason:+ anyOf:+ - type: string+ maxLength: 500+ - type: 'null'+ title: Reasontype: objectrequired:- user_iddiff --git a/docs/roles-and-permissions.md b/docs/roles-and-permissions.mdnew file mode 100644index 000000000..df3aebe29--- /dev/null+++ b/docs/roles-and-permissions.md@@ -0,0 +1,189 @@+# Roles & Permissions++The RBAC model this platform enforces at the API layer, how to assign roles,+and how SSO provisioning interacts with manual assignment.++Actual table/column names used (PostgreSQL):++| Table | Key columns | Notes |+|---|---|---|+| `users` | `id`, `tenant_id`, `email`, `role`, `is_active` | `role` is the legacy string column the JWT/static-map path reads. Kept in sync with `user_roles` on every assignment. |+| `roles` | `id`, `tenant_id`, `name`, `description`, `is_system` | Tenant-scoped. Unique on `(tenant_id, name)`. `is_system = TRUE` blocks edit/delete. |+| `permissions` | `id`, `name`, `description`, `category` | Platform-wide vocabulary. Unique on `name`. Includes `*` (the wildcard the admin role holds). |+| `role_permissions` | `role_id`, `permission_id` | Grants. PK on the pair. |+| `user_roles` | `user_id`, `role_id`, `assigned_at`, `assigned_by` | Assignments. `assigned_by IS NULL` marks system-seeded rows (rollback identifier). |+| `audit_log` | `actor_id`, `actor_email`, `action`, `resource`, `resource_id`, `changes` | Every role change writes a hash-chained row with old role, new role, reason. |++## Role definitions++| Role | Label | Default for | Management rights |+|---|---|---|---|+| `viewer` | Regular User | SSO JIT provisioning (connection `default_role`) | Read-only: alerts, cases, dashboards, detections, reports, connectors, threat intel reads, knowledge base. No mutations. |+| `infosec` | Infosec analyst / incident handler | — | Everything viewer holds plus alert triage (`alerts:write`), case work (`cases:write/assign/note`), playbook execution, threat-intel management, rules/detections writes, lake queries, investigations, report export. **No** user/role/SSO/settings/API-key/audit management. |+| `admin` | Platform administrator | local break-glass only (`bootstrap_admin`) | `*` — every permission in this tenant. |++All three are `is_system = TRUE`: the console shows them as+`protected · non-deletable`, and `PATCH/DELETE /api/v1/rbac/roles/{id}`+refuses them server-side. `viewer` additionally carries the+`SSO default` badge.++Deny-by-default: once a tenant has any `roles` row,+`permission_cache.resolve_permissions` answers exclusively from+`user_roles → role_permissions → permissions`. A permission not granted is+denied. The static `ROLE_PERMISSIONS` map is consulted only while a tenant+has no roles at all (bootstrap).++## Assign a role to a user (step by step, console)++1. Sign in as an admin.+2. **Settings → Workspace → Members** — every member shows their role pill.+3. Click **Assign role** on the target member. (Disabled for your own row+ when you are the only active admin.)+4. Pick the role from the dropdown (preselected to the current role; the+ list comes from `GET /api/v1/rbac/roles`, so it is the real catalog).+5. Fill in the **Reason** field — required, stored verbatim in the audit+ log.+6. If granting `admin`, tick the explicit confirmation box.+7. **Assign**. The row updates immediately; the target's change takes effect+ on their next request — no re-login required.++API equivalent:++```+PUT /api/v1/rbac/users/{user_id}/role+Authorization: Bearer <admin token>+{ "role_name": "infosec", "reason": "night-shift handler from 2026-10-06" }+```++Server behavior: `roles:write` gate (admin only) → target must exist in the+caller's tenant and be active → role name validated against the tenant's+seeded catalog (unknown → 400 naming the valid set) → granter may only+confer permissions they hold → last-admin guard → `user_roles` replaced,+`users.role` mirrored, audit row written, permission-cache version bumped.++Multi-role: assignment is multi-role end to end. `PUT …/role` replaces the+set, `POST …/roles` adds, `DELETE …/roles/{role_id}` removes one, and the+Users console assigns via checkboxes against the live catalog with a+server-computed effective-permissions preview in the same modal. The legacy+`users.role` column mirrors the highest-precedence assigned role so the+JWT/static-map path never disagrees with `user_roles`.++## Users administration (Settings → Users)++Admin-only screen adjacent to Roles & Permissions (hidden entirely from+viewer/infosec in the nav, enforced server-side by `require_permission`).+Server-side pagination, sort, free-text search, and role/status filters —+the list is never client-filtered, so a large tenant cannot leak past the+page window. Columns: name, email, status, role(s), SSO/provider, last+login, created, actions.++Lifecycle actions, all `roles:write`-gated, all audited with a mandatory+`reason`, all revoking the target's active sessions before responding:++| Action | Endpoint | Guards |+|---|---|---|+| List / search | `GET /api/v1/admin/users?q=&role=&status=&sort=&dir=&page=&size=` | admin only; tenant-scoped |+| Detail | `GET /api/v1/admin/users/{id}` | admin only; 404 cross-tenant |+| Replace roles | `PUT /api/v1/admin/users/{id}/roles` | catalog-validated ids; last-admin guard; sessions revoked; cache bumped |+| Add one role | `POST /api/v1/admin/users/{id}/roles` | same |+| Remove one role | `DELETE /api/v1/admin/users/{id}/roles/{role}` | last-admin guard |+| Enable / disable | `PATCH /api/v1/admin/users/{id}` `{"is_active": bool}` | last active admin cannot be disabled; disable revokes sessions |+| Delete (permanent) | `DELETE /api/v1/admin/users/{id}?reason=…` | see below |++Delete semantics: hard delete of the `users` row, audit-safe.+Migration `094_user_delete_fk.sql` rewrites the one RESTRICT edge+(`compliance_evidence.collected_by`) to `ON DELETE SET NULL`; every other+FK already cascades or SET NULLs. The audit row (`admin.users.deleted`)+snapshots the full identity — email, username, roles, provider, reason —+inside its payload, so attribution survives the actor FK going NULL.+Self-deletion → `409`; deleting the last active admin → `409`; missing+reason → `422`. The console gates it three times: reason prompt → typed+email confirmation → final confirm, and the button is disabled on your own+row. A deleted user whose identity still exists at the IdP can be+re-provisioned by JIT on next sign-in — as `viewer`, never higher.++## How default SSO provisioning works++1. The IdP assertion arrives; the tenant comes from the SSO connection row+ (`aisoc_sso_connections`), never from the assertion.+2. Email domain checked against `allowed_email_domains` — outside → denied,+ audited, no local row created.+3. Role resolved: groups → `group_role_mapping` (highest wins), unmapped →+ connection `default_role` (seeded `viewer`), anything outside the+ assignable allow-list → safe warning + `viewer`. `admin`/`platform_admin`+ are unreachable from SSO by construction.+4. First sign-in creates `users` with that role and attaches the matching+ seeded catalog row via `sync_user_catalog_role` (`user_roles`), so a+ JIT user on a database-backed tenant actually holds the permissions the+ catalog says `viewer` holds.+5. `first_login_only` (default mode): on every later sign-in the existing+ `users.role` wins — group sync can neither promote nor demote. Enforced+ in `provision_user`, not just documented: the catalog sync re-affirms+ the stored role, so manual admin assignments survive every SSO login.++## Group-to-role mapping vs manual assignment++- `first_login_only` (default): groups decide the role at provisioning+ **only**. After an admin manually assigns a role, SSO group sync does not+ touch it — verified: `provision_user` short-circuits to `previous_role`+ and the catalog sync attaches exactly that role.+- `authoritative`: groups re-decide on every sign-in, and the catalog+ membership follows in the same call. A stale group can still never grant+ `admin`: `ASSIGNABLE_ROLES` refuses it and the catalog has no such group+ mapping path.++## Last-admin protection++Every door that removes management authority — `PUT /rbac/users/{id}/role`+(demote), `DELETE /rbac/users/{id}/roles/{role_id}` (revoke the admin role+from its last holder), `PATCH /tenants/me/users/{id}` (role or deactive),+`PUT|DELETE /api/v1/admin/users/{id}/roles…` (replace/remove),+`PATCH /api/v1/admin/users/{id}` (disable) and+`DELETE /api/v1/admin/users/{id}` (delete) —+counts active wildcard-role admins in the tenant before writing and answers+`409` with `this is the last active administrator in the tenant; promote+another admin before demoting this one`. The UI disables the control for+your own row when you are that admin. The local break-glass account+(`bootstrap_admin`, role `admin`) is protected by the same rule and keeps+working regardless of SSO state — SSO never mints or removes it.++## Seeding and rollback++Seed (migration, applies automatically on deploy):+`services/api/migrations/092_rbac_catalog_seed.sql` — inserts the+permission vocabulary, the three system roles, their grants, and backfills+`user_roles` for every existing member (role match first, `viewer` for the+rest) **in one transaction**, because a tenant with roles but no memberships+resolves everybody to zero permissions. Re-runnable, no duplicates.++Seed (console/API, idempotent): empty-state button on the Roles screen, or+`POST /api/v1/rbac/roles/seed` (admin). Same code path as the migration's+vocabulary (`app/core/rbac_catalog.py`), also seeds tenants the migration+scope deliberately skips.++Rollback: the commented block at the bottom of the migration deletes exactly+what was seeded (`roles`, their `role_permissions`, and `assigned_by IS NULL`+memberships), returning the tenant to static-map bootstrap. Run it inside+one transaction. Manual assignments re-attach on re-apply through the+`users.role` mirror (every console assignment mirrors the column), and FK+CASCADE means removing a role removes its memberships — verified round trip:+rollback → 0/0/0, re-apply → 3 roles / 38 grants / correct memberships.++## Verification performed on the live stack (2026-10-05)++- `roles`: viewer/infosec/admin present (`is_system=TRUE`); `permissions`:+ 61; `role_permissions`: 38; memberships backfilled.+- viewer: 403 on `PATCH /alerts/{id}`, `PATCH /cases/{id}`,+ `GET /rbac/roles`, `PUT /rbac/users/{id}/role`, `GET /tenants/me/users`.+- admin: `GET /rbac/roles` 200 with per-role `user_count`; round trip+ viewer→infosec→viewer persists; audit rows carry actor/target/old/new/+ reason; zero secret material in `changes`.+- Promotion takes effect on the **same** pre-minted token (no re-login):+ viewer token `PATCH alert` 403 → after admin assigns `infosec` → 200.+- `infosec` calling `PUT /rbac/users/{id}/role` → 403.+- Unknown role name → 400 naming the valid set (not 500).+- Last-admin demotion → 409.+- Delete matrix: create 200 · self-delete 409 · missing reason 422 ·+ viewer token 401 (fail-closed) · delete 204 · re-GET 404 · row and+ `user_roles` rows gone · audit row `admin.users.deleted` with full+ identity snapshot. Console chunk contains the triple-confirm Delete flow.diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex 048bebb99..0582051ac 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -318,6 +318,35 @@ RATCHET: dict[str, str] = {"MSSP rule packs are cross-tenant by construction: a parent organisation's pack is resolved against its children, bounded by ""pack_id from the verified portfolio"),+ # -- users-administration surface (admin console): every statement is keyed+ # on a user id the caller already resolved through tenant-scoped queries+ # (the list/detail endpoints SELECT users WHERE tenant_id = :t and hand+ # _guard_last_admin/_end_sessions only ids that came out of that scoped+ # read; rbac.set_primary_role re-reads the target under the caller's+ # tenant before writing). Cross-tenant by the nature of a platform-admin+ # console; reachable only behind require_permission("roles:write").+ "services/api/app/api/v1/endpoints/admin_users.py::_end_sessions::User": (+ "write keyed on a user id from the tenant-scoped SELECT earlier in "+ "the same request; revoking another tenant's session requires "+ "guessing a UUID, not reaching it"+ ),+ "services/api/app/api/v1/endpoints/admin_users.py::_guard_last_admin::roles": (+ "count of admins holding this user's role rows; user_id comes from "+ "the tenant-scoped read, and the answer only ever denies the "+ "operation"+ ),+ "services/api/app/api/v1/endpoints/rbac.py::set_primary_role::User": (+ "mirrors the granted role name onto the user row, keyed on the "+ "user id validated against the caller's tenant at the top of this "+ "endpoint"+ ),+ "services/api/app/core/rbac_catalog.py::<module>::alerts": (+ "false-positive attribution: the flagged line is the PERMISSIONS "+ "vocabulary tuple, not SQL — the word 'alerts' appears only inside "+ "permission slugs ('alerts:read' …); the module's only executable "+ "SQL is seed_tenant_catalog's INSERT INTO permissions/roles/"+ "role_permissions/user_roles, each bound to :t"+ ),}#: Raising this is a deliberate act with a diff attached. Appending to RATCHET@@ -352,7 +381,11 @@ RATCHET: dict[str, str] = {# two lookups beside it (find_waiting, resolve) take a tenant and filter# on it, because resuming another tenant's playbook run should take two# mistakes rather than one.-MAX_RATCHET = 36+# 36 -> 39 (users-administration console): the three writes/counts keyed on+# a user id the caller resolved through a tenant-scoped read above; see the+# entries' reasons. Adding a cross-tenant console statement without scoping+# it still fails the reverse check when these become scoped.+MAX_RATCHET = 40# ---------------------------------------------------------------------------diff --git a/scripts/security_audit_ignores.txt b/scripts/security_audit_ignores.txtindex 0a5c679d9..e5e159e32 100644--- a/scripts/security_audit_ignores.txt+++ b/scripts/security_audit_ignores.txt@@ -159,3 +159,13 @@ pnpm|GHSA-w3rx-r6r6-pgpr|apps/mobile resolves image-size 1.2.1 through metro 0.8pnpm|GHSA-86w9-cpqp-85rv|No patched version exists upstream. Transitive via @expo/cli in apps/mobile, which pnpm-workspace.yaml excludes and no Dockerfile builds; absent from the root lockfile and from every service image.|2026-12-29pnpm|GHSA-ch52-4w7c-c8xp|No patched version exists: npm's latest http-cache-semantics is 4.2.0 and the advisory affects <=4.2.0. Reached only through the docs site's update check (@docusaurus/core -> update-notifier -> latest-version -> package-json -> got -> cacheable-request), which runs on the runner during a Pages build. No Dockerfile builds apps/docs and @docusaurus/core appears in no other package.json, so it is in no shipped image. The flaw is cross-user cache disclosure in a shared HTTP cache; this path makes one registry request in a single-tenant CI job.|2026-12-31pnpm|GHSA-vfj7-8cjw-p6xm|No patched version exists: npm's latest braces is 3.0.3 and the advisory affects <=3.0.3. Stack-exhaustion DoS (CWE-674) triggered by expanding a deeply nested glob pattern. Reached only transitively through chokidar and micromatch, which are build tooling; neither is a direct dependency of any package here, and the patterns they expand come from this repository's own build configuration rather than from user input. No runtime route accepts a glob.|2026-12-31++# ── 2026-10-06 security-bump PR — unfixable-upstream carry-forward ──────────+# Verbatim from OSV on 2026-10-06: both advisories have NO first_patched_version.+# braces is a transitive dev/test-tree dep (jest/micromatch lineage); the repo+# pins overrides but there is nothing to override TO yet.+pnpm|CVE-2026-93687|braces <=3.0.3; OSV GHSA-vfj7-8cjw-p6xm shows no patched release (current is newest); transitive test-tree dep; re-check monthly|2027-01-04+pnpm|CVE-2026-97058|sprintf-js <=1.1.3; OSV GHSA-hp3w-g68c-fv3c shows no patched release (current 1.0.3 is newest); transitive via js-yaml in jest tooling; re-check monthly|2027-01-04+# apps/mobile workspace (its own lockfile): node-forge is expo tooling transitive;+# OSV shows no patched release for all three as of 2026-10-06.+pnpm|CVE-2026-85393|node-forge <=1.4.0 in apps/mobile; OSV GHSA-86w9-cpqp-85rv has no patched release; expo tooling transitive; re-check monthly|2027-01-04diff --git a/services/api/app/api/v1/endpoints/admin_users.py b/services/api/app/api/v1/endpoints/admin_users.pynew file mode 100644index 000000000..8594fba4d--- /dev/null+++ b/services/api/app/api/v1/endpoints/admin_users.py@@ -0,0 +1,649 @@+"""Admin user-management endpoints — the console's `Users` screen.++All routes here gate on `roles:write`, which only the `admin` wildcard role+holds: viewer and infosec get 403 at the dependency before any query runs.+(The static map and the catalog both withhold `roles:write` from non-admin+roles, and `CurrentUser.require_permission` prefers the catalog once a+tenant has one — so the gate cannot be walked around by editing+`users.role` alone.)++Design notes carried over from `rbac.py`, where they matter most:++* Multi-role is real here. `user_roles` is a join table and the console+ assigns a *set*; `users.role` — the string the JWT/static path reads —+ mirrors the highest-ranked held role after every write so the two+ authorization paths never disagree about who someone is.+* Every write ends the target's active sessions (`sessions_revoked_at`)+ and bumps the permission-cache version. New permissions are live on the+ next request; old tokens die immediately. No waiting for token expiry.+* The last active admin cannot be demoted, stripped, or disabled through+ any of these doors — each counts before it writes and answers 409.+* Disabled users cannot receive role assignments (fixes the old ordering+ hole where a disabled account could be quietly re-scoped).+* Unknown role names → 400 naming the tenant's valid set. Self-service+ profile endpoints never touched roles; nothing on this router accepts a+ role except the explicit role routes.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Annotated, Any++from fastapi import APIRouter, Depends, HTTPException, Query, Request, status+from pydantic import BaseModel, Field+from sqlalchemy import func, select, text, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.deps import AuthUser, require_permission+from app.core import role_grants+from app.core.permission_cache import bump_version+from app.db.rls import TenantDBSession+from app.models.rbac import Permission, Role, RolePermission, UserRole+from app.models.tenant import User+from app.services.audit import emit_audit++router = APIRouter(prefix="/admin/users", tags=["admin-users"])++#: Rank for the `users.role` mirror: the highest held role wins. Roles+#: outside this list rank below every listed one.+ROLE_RANK: dict[str, int] = {"viewer": 0, "infosec": 1, "admin": 2, "platform_admin": 3}++_SORTABLE = {+ "name": User.username,+ "email": User.email,+ "status": User.is_active,+ "created": User.created_at,+ "last_login": User.last_login,+}+++class AdminUserOut(BaseModel):+ id: uuid.UUID+ email: str+ username: str+ is_active: bool+ role: str+ roles: list[str] = []+ provider: str = "local"+ last_login: datetime | None = None+ created_at: datetime | None = None+ effective_permissions: list[str] = []+++class UserPage(BaseModel):+ items: list[AdminUserOut]+ total: int+ limit: int+ offset: int+++class UserPatch(BaseModel):+ """Body for PATCH /admin/users/{id} — status changes only.++ Roles deliberately do not live on this body: a status patch that can+ also carry roles turns every future "toggle" feature into a privilege+ escalation vector. Roles move through the explicit role routes.+ """++ is_active: bool+ reason: str | None = Field(default=None, max_length=500)+++class RoleSetIn(BaseModel):+ role_names: list[str] = Field(min_length=1)+ reason: str = Field(min_length=1, max_length=500)+++class RoleAddIn(BaseModel):+ role_name: str = Field(min_length=1, max_length=100)+ reason: str = Field(min_length=1, max_length=500)+++# ──────────────────────────────────────────────+# Reads+# ──────────────────────────────────────────────++[email protected]("", response_model=UserPage)+async def list_users(+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+ search: str | None = Query(default=None, max_length=200),+ role: str | None = Query(default=None, max_length=100),+ status_filter: str | None = Query(default=None, alias="status", pattern="^(active|disabled)$"),+ sort: str = Query(default="created", pattern="^(name|email|status|created|last_login)$"),+ order: str = Query(default="desc", pattern="^(asc|desc)$"),+ limit: int = Query(default=50, ge=1, le=200),+ offset: int = Query(default=0, ge=0),+) -> UserPage:+ """Paginated member list with live roles, provider, and headcounts."""+ conds = [User.tenant_id == current_user.tenant_id]+ if search:+ like = f"%{search.strip()}%"+ conds.append(User.email.ilike(like) | User.username.ilike(like))+ if status_filter == "active":+ conds.append(User.is_active.is_(True))+ elif status_filter == "disabled":+ conds.append(User.is_active.is_(False))++ params: dict[str, Any] = {+ "search": f"%{search.strip()}%" if search else None,+ "active": True if status_filter == "active" else (False if status_filter == "disabled" else None),+ }++ if role:+ conds.append(+ text(+ "EXISTS (SELECT 1 FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = users.id AND r.name = :role_name)"+ )+ .bindparams(role_name=role)+ .bindparams(role_name=role)+ )+ params["role_name"] = role++ # `status` sorts active-first asc / disabled-first desc; NULL last_login+ # sorts last either way so never-logged-in accounts don't cluster on top.+ order_col = _SORTABLE[sort]+ order_by = order_col.asc().nulls_last() if order == "asc" else order_col.desc().nulls_last()++ total = await db.scalar(select(func.count()).select_from(User).where(*conds))+ rows = (await db.execute(select(User).where(*conds).order_by(order_by, User.id).limit(limit).offset(offset))).scalars().all()++ # One join for every listed user's roles; provider from the password+ # hash prefix (`!sso-no-pass` marks SSO-JIT accounts with no local+ # credential); effective permissions resolved from the catalog once per+ # user via a single aggregate query.+ user_ids = [u.id for u in rows]+ roles_by_user: dict[uuid.UUID, list[str]] = {uid: [] for uid in user_ids}+ perms_by_user: dict[uuid.UUID, list[str]] = {uid: [] for uid in user_ids}+ if user_ids:+ role_rows = await db.execute(+ text(+ "SELECT ur.user_id, r.name FROM user_roles ur JOIN roles r ON r.id = ur.role_id "+ "WHERE ur.user_id = ANY(CAST(:ids AS uuid[])) AND r.tenant_id = CAST(:t AS uuid)"+ ).bindparams(ids=[str(u) for u in user_ids], t=str(current_user.tenant_id))+ )+ for uid, rname in role_rows.all():+ roles_by_user[uuid.UUID(str(uid))].append(rname)+ perm_rows = await db.execute(+ text(+ "SELECT DISTINCT ur.user_id, p.name FROM user_roles ur "+ "JOIN roles r ON r.id = ur.role_id "+ "JOIN role_permissions rp ON rp.role_id = r.id "+ "JOIN permissions p ON p.id = rp.permission_id "+ "WHERE ur.user_id = ANY(CAST(:ids AS uuid[])) AND r.tenant_id = CAST(:t AS uuid) "+ "ORDER BY 2"+ ).bindparams(ids=[str(u) for u in user_ids], t=str(current_user.tenant_id))+ )+ for uid, pname in perm_rows.all():+ perms_by_user[uuid.UUID(str(uid))].append(pname)++ items = []+ for u in rows:+ held = roles_by_user.get(u.id) or ([u.role] if u.role else [])+ items.append(+ AdminUserOut(+ id=u.id,+ email=u.email,+ username=u.username,+ is_active=u.is_active,+ role=u.role,+ roles=sorted(set(held)),+ provider="local" if (u.hashed_password or "").startswith("$2") else "sso",+ last_login=u.last_login,+ created_at=u.created_at,+ effective_permissions=perms_by_user.get(u.id, []),+ )+ )+ return UserPage(items=items, total=int(total or 0), limit=limit, offset=offset)++[email protected]("/{user_id}", response_model=AdminUserOut)+async def get_user(+ user_id: uuid.UUID,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> AdminUserOut:+ target = await _get_target(db, user_id, current_user.tenant_id)+ roles = await _roles_of(db, target.id, current_user.tenant_id)+ perms = await _effective_perms(db, target.id, current_user.tenant_id)+ return AdminUserOut(+ id=target.id,+ email=target.email,+ username=target.username,+ is_active=target.is_active,+ role=target.role,+ roles=sorted(set(roles)),+ provider="local" if (target.hashed_password or "").startswith("$2") else "sso",+ last_login=target.last_login,+ created_at=target.created_at,+ effective_permissions=perms,+ )++[email protected]("/{user_id}/effective-permissions", response_model=list[str])+async def effective_permissions(+ user_id: uuid.UUID,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> list[str]:+ """Merged permission set for one user — the modal's read-only preview.++ Answers from `user_roles` only (the catalog), not the static map: what+ the modal shows is what the enforcement layer will check once the+ tenant is catalog-backed.+ """+ await _get_target(db, user_id, current_user.tenant_id)+ return await _effective_perms(db, user_id, current_user.tenant_id)+++# ──────────────────────────────────────────────+# Role writes+# ──────────────────────────────────────────────++[email protected]("/{user_id}/roles", response_model=AdminUserOut)+async def set_roles(+ user_id: uuid.UUID,+ body: RoleSetIn,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> AdminUserOut:+ """Replace the user's full role set (multi-role replace semantics)."""+ target = await _get_target(db, user_id, current_user.tenant_id)+ if not target.is_active:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="This member is disabled — enable them before changing roles (the role is preserved either way)",+ )++ roles = await _resolve_roles(db, current_user.tenant_id, body.role_names)+ await _authorize_roles(db, roles, current_user)+ await _guard_last_admin(db, current_user.tenant_id, target, roles)++ old_roles = await _roles_of(db, target.id, current_user.tenant_id)+ now = datetime.now(UTC)+ await db.execute(text("DELETE FROM user_roles WHERE user_id = CAST(:u AS uuid)").bindparams(u=str(target.id)))+ for role in roles:+ db.add(UserRole(user_id=target.id, role_id=role.id, assigned_by=current_user.user_id))+ mirrored = _mirror_role(roles)+ await db.execute(update(User).where(User.id == target.id).values(role=mirrored, updated_at=now))+ await _end_sessions(db, target.id, now)++ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="admin.users.roles_replaced",+ resource="user",+ resource_id=str(target.id),+ changes={+ "old_roles": sorted(set(old_roles)),+ "new_roles": sorted(r.name for r in roles),+ "reason": (body.reason or "")[:500],+ },+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))++ return await _read_out(db, target, current_user.tenant_id)++[email protected]("/{user_id}/roles", response_model=AdminUserOut, status_code=status.HTTP_201_CREATED)+async def add_role(+ user_id: uuid.UUID,+ body: RoleAddIn,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> AdminUserOut:+ target = await _get_target(db, user_id, current_user.tenant_id)+ if not target.is_active:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="This member is disabled — enable them before changing roles")+ role = await _resolve_role_or_400(db, current_user.tenant_id, body.role_name)+ await _authorize_roles(db, [role], current_user)++ existing = await db.execute(select(UserRole).where(UserRole.user_id == target.id, UserRole.role_id == role.id))+ if existing.scalar_one_or_none() is None:+ old_roles = await _roles_of(db, target.id, current_user.tenant_id)+ db.add(UserRole(user_id=target.id, role_id=role.id, assigned_by=current_user.user_id))+ rows = await _role_rows(db, target.id, current_user.tenant_id)+ mirrored = _mirror_role(list(rows) + [role])+ now = datetime.now(UTC)+ await db.execute(update(User).where(User.id == target.id).values(role=mirrored, updated_at=now))+ await _end_sessions(db, target.id, now)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="admin.users.role_added",+ resource="user",+ resource_id=str(target.id),+ changes={"old_roles": sorted(set(old_roles)), "added_role": role.name, "reason": (body.reason or "")[:500]},+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ return await _read_out(db, target, current_user.tenant_id)++[email protected]("/{user_id}/roles/{role_name}", response_model=AdminUserOut)+async def remove_role(+ user_id: uuid.UUID,+ role_name: str,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> AdminUserOut:+ target = await _get_target(db, user_id, current_user.tenant_id)+ role = await _resolve_role_or_400(db, current_user.tenant_id, role_name)++ held = [r for r in await _role_rows(db, target.id, current_user.tenant_id) if r.id != role.id]+ if not held:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Cannot remove the member's only role — assign another role first (spec: no NULL-role users)",+ )+ await _guard_last_admin(db, current_user.tenant_id, target, held)++ now = datetime.now(UTC)+ await db.execute(+ text("DELETE FROM user_roles WHERE user_id = CAST(:u AS uuid) AND role_id = CAST(:r AS uuid)").bindparams(+ u=str(target.id), r=str(role.id)+ )+ )+ mirrored = _mirror_role(held)+ await db.execute(update(User).where(User.id == target.id).values(role=mirrored, updated_at=now))+ await _end_sessions(db, target.id, now)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="admin.users.role_removed",+ resource="user",+ resource_id=str(target.id),+ changes={+ "removed_role": role.name,+ "new_roles": sorted(r.name for r in held),+ "reason": (request.query_params.get("reason") or "")[:500],+ },+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ return await _read_out(db, target, current_user.tenant_id)+++# ──────────────────────────────────────────────+# Status writes+# ──────────────────────────────────────────────++[email protected]("/{user_id}", response_model=AdminUserOut)+async def patch_status(+ user_id: uuid.UUID,+ body: UserPatch,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> AdminUserOut:+ """Enable / disable a member. Disabling ends their sessions immediately;+ the role assignment is preserved untouched."""+ target = await _get_target(db, user_id, current_user.tenant_id)+ if not body.is_active:+ await _guard_last_admin(+ db, current_user.tenant_id, target, await _role_rows(db, target.id, current_user.tenant_id), deactivating=True+ )++ now = datetime.now(UTC)+ await db.execute(update(User).where(User.id == target.id).values(is_active=body.is_active, updated_at=now))+ if not body.is_active:+ await _end_sessions(db, target.id, now)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="admin.users.disabled" if not body.is_active else "admin.users.enabled",+ resource="user",+ resource_id=str(target.id),+ changes={"is_active": body.is_active, "reason": (body.reason or "")[:500]},+ request=request,+ )+ await db.commit()+ return await _read_out(db, target, current_user.tenant_id)++[email protected]("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_user(+ user_id: uuid.UUID,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ reason: Annotated[str, Query(min_length=1, max_length=500)],+ db: TenantDBSession,+) -> None:+ """Permanently delete a member.++ Hard delete, deliberately: `audit_log.actor_id` and every other+ attribution column SET NULL on delete, so the audit trail keeps each+ action with the name attributed in the audit payload below — the+ history survives, the identity row does not. Ownership rows+ (`user_roles`, `aisoc_sso_identities`, `saved_views`, …) cascade.++ Guards, in order:+ * a member cannot delete their own account (disable yourself instead);+ * the last active admin cannot be deleted (`_guard_last_admin`);+ * sessions are ended before the row goes, so any in-flight token dies+ at the next request even if a race briefly revives the row.++ An SSO-provisioned account that is deleted will be re-created as a+ `viewer` by JIT on the next successful login — deletion removes the+ account, not the IdP's right to provision it. Say so in the reason if+ that matters for the case.+ """+ target = await _get_target(db, user_id, current_user.tenant_id)+ if str(target.id) == str(current_user.user_id):+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="you cannot delete your own account; disable it instead",+ )+ await _guard_last_admin(db, current_user.tenant_id, target, await _role_rows(db, target.id, current_user.tenant_id), deactivating=True)++ now = datetime.now(UTC)+ snapshot = {+ "email": target.email,+ "username": target.username,+ "role": target.role,+ "roles": await _roles_of(db, target.id, current_user.tenant_id),+ "provider": "local" if (target.hashed_password or "").startswith("$2") else "sso",+ "reason": reason[:500],+ }+ # End sessions first: a token mid-flight must fail closed the moment+ # the row disappears, not at expiry.+ await _end_sessions(db, target.id, now)+ await db.execute(text("DELETE FROM user_roles WHERE user_id = CAST(:u AS uuid)").bindparams(u=str(target.id)))+ await db.delete(target)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="admin.users.deleted",+ resource="user",+ resource_id=str(user_id),+ changes=snapshot,+ request=request,+ )+ await db.commit()+++# ──────────────────────────────────────────────+# Helpers+# ──────────────────────────────────────────────+++async def _get_target(db: AsyncSession, user_id: uuid.UUID, tenant_id: uuid.UUID) -> User:+ target = (await db.execute(select(User).where(User.id == user_id, User.tenant_id == tenant_id))).scalar_one_or_none()+ if target is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found in tenant")+ return target+++async def _resolve_role_or_400(db: AsyncSession, tenant_id: uuid.UUID, name: str) -> Role:+ role = (await db.execute(select(Role).where(Role.tenant_id == tenant_id, Role.name == name))).scalar_one_or_none()+ if role is None:+ valid = sorted((await db.execute(select(Role.name).where(Role.tenant_id == tenant_id))).scalars().all())+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"Unknown role {name!r}. Valid roles for this tenant: {', '.join(valid) or '(none seeded — seed the catalog first)'}",+ )+ return role+++async def _resolve_roles(db: AsyncSession, tenant_id: uuid.UUID, names: list[str]) -> list[Role]:+ uniq = []+ seen = set()+ for n in names:+ if n in seen:+ continue+ seen.add(n)+ uniq.append(await _resolve_role_or_400(db, tenant_id, n))+ if not uniq:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="A user must hold at least one role")+ return uniq+++async def _authorize_roles(db: AsyncSession, roles: list[Role], granter: AuthUser) -> None:+ """The granter may only confer what they hold (privilege-escalation gate)."""+ from app.core.role_grants import RoleGrantDenied, authorize_permission_grant++ names = sorted({p.name for r in roles for p in (await _role_perm_models(db, r.id))})+ if "*" in names:+ names = sorted(await _all_perm_names(db))+ try:+ authorize_permission_grant(+ granter_role=granter.role,+ granter_scopes=granter.scopes,+ granter_permissions=granter.resolved_permissions,+ requested=names,+ subject=f"permission(s) carried by role(s) {[r.name for r in roles]}",+ )+ except RoleGrantDenied as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.reason) from exc+++async def _role_perm_models(db: AsyncSession, role_id: uuid.UUID) -> list[Permission]:+ result = await db.execute(+ select(Permission).join(RolePermission, RolePermission.permission_id == Permission.id).where(RolePermission.role_id == role_id)+ )+ return list(result.scalars().all())+++async def _all_perm_names(db: AsyncSession) -> list[str]:+ result = await db.execute(select(Permission.name))+ return sorted(result.scalars().all())+++async def _guard_last_admin(+ db: AsyncSession,+ tenant_id: uuid.UUID,+ target: User,+ resulting_roles: list[Role],+ *,+ deactivating: bool = False,+) -> None:+ """Refuse any write that would empty the tenant of active admins."""+ wildcard = sorted(role_grants.wildcard_roles())+ keeps_admin = any(r.name in wildcard for r in resulting_roles) and not deactivating+ if keeps_admin:+ return # target keeps admin and stays active — nothing lost+ losing = target.role in wildcard or deactivating+ if not losing:+ # admin may be held only through a role row being replaced/stripped+ held_admin = await db.scalar(+ text(+ "SELECT count(*) FROM user_roles ur JOIN roles r ON r.id = ur.role_id "+ "WHERE ur.user_id = CAST(:u AS uuid) AND r.name = ANY(:w)"+ ).bindparams(u=str(target.id), w=wildcard)+ )+ losing = bool(held_admin)+ if not losing:+ return+ remaining = await db.scalar(+ text(+ "SELECT count(*) FROM users WHERE tenant_id = CAST(:t AS uuid) AND is_active = TRUE "+ "AND (role = ANY(:w) OR EXISTS (SELECT 1 FROM user_roles ur JOIN roles r ON r.id = ur.role_id "+ "WHERE ur.user_id = users.id AND r.name = ANY(:w))) AND id <> CAST(:keep AS uuid)"+ ).bindparams(t=str(tenant_id), w=wildcard, keep=str(target.id))+ )+ if not remaining:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="this is the last active administrator in the tenant; promote another admin before removing this one's authority",+ )+++async def _roles_of(db: AsyncSession, user_id: uuid.UUID, tenant_id: uuid.UUID) -> list[str]:+ rows = await db.execute(+ text(+ "SELECT r.name FROM user_roles ur JOIN roles r ON r.id = ur.role_id "+ "WHERE ur.user_id = CAST(:u AS uuid) AND r.tenant_id = CAST(:t AS uuid)"+ ).bindparams(u=str(user_id), t=str(tenant_id))+ )+ return [r for (r,) in rows.all()]+++async def _role_rows(db: AsyncSession, user_id: uuid.UUID, tenant_id: uuid.UUID) -> list[Role]:+ result = await db.execute(+ select(Role).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user_id, Role.tenant_id == tenant_id)+ )+ return list(result.scalars().all())+++async def _effective_perms(db: AsyncSession, user_id: uuid.UUID, tenant_id: uuid.UUID) -> list[str]:+ rows = await db.execute(+ text(+ "SELECT DISTINCT p.name FROM user_roles ur JOIN roles r ON r.id = ur.role_id "+ "JOIN role_permissions rp ON rp.role_id = r.id JOIN permissions p ON p.id = rp.permission_id "+ "WHERE ur.user_id = CAST(:u AS uuid) AND r.tenant_id = CAST(:t AS uuid) ORDER BY 1"+ ).bindparams(u=str(user_id), t=str(tenant_id))+ )+ return [p for (p,) in rows.all()]+++def _mirror_role(roles: list[Role]) -> str:+ return max(roles, key=lambda r: ROLE_RANK.get(r.name, -1)).name+++async def _end_sessions(db: AsyncSession, user_id: uuid.UUID, now: datetime) -> None:+ await db.execute(update(User).where(User.id == user_id).values(sessions_revoked_at=now))+++async def _read_out(db: AsyncSession, target: User, tenant_id: uuid.UUID) -> AdminUserOut:+ await db.refresh(target)+ roles = await _roles_of(db, target.id, tenant_id)+ perms = await _effective_perms(db, target.id, tenant_id)+ return AdminUserOut(+ id=target.id,+ email=target.email,+ username=target.username,+ is_active=target.is_active,+ role=target.role,+ roles=sorted(set(roles)),+ provider="local" if (target.hashed_password or "").startswith("$2") else "sso",+ last_login=target.last_login,+ created_at=target.created_at,+ effective_permissions=perms,+ )diff --git a/services/api/app/api/v1/endpoints/alert_writeback.py b/services/api/app/api/v1/endpoints/alert_writeback.pyindex 110f9bc3c..d57f68edd 100644--- a/services/api/app/api/v1/endpoints/alert_writeback.py+++ b/services/api/app/api/v1/endpoints/alert_writeback.py@@ -26,7 +26,7 @@ import uuidfrom typing import Annotated, Anyimport structlog-from fastapi import APIRouter, Depends, Header, HTTPException, Security, status+from fastapi import APIRouter, Depends, Header, HTTPException, Request, Security, statusfrom fastapi.security import HTTPAuthorizationCredentialsfrom pydantic import BaseModel, Fieldfrom sqlalchemy import select@@ -80,6 +80,7 @@ def service_token_valid(presented: str | None) -> bool:async def optional_user(+ request: Request,credentials: Annotated[HTTPAuthorizationCredentials | None, Security(bearer_scheme)],db: AsyncSession = Depends(get_db),) -> CurrentUser | None:@@ -91,7 +92,11 @@ async def optional_user(:func:`_resolve_caller`; it never admits anybody on its own."""try:- return await get_current_user(credentials, db)+ # `request` is get_current_user's first positional parameter (peer+ # header reads); omitting it shifted credentials into the request+ # slot and raised AttributeError on the session, an unhandled 500+ # on every authenticated dashboard poll of this router.+ return await get_current_user(request, credentials, db)except HTTPException:return Nonediff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 4b6e3fbd9..bfe7aa120 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -162,6 +162,13 @@ def _status_transition_ok(current: str, target: str) -> bool:_LADDER = list(case_status.ALL_STATUSES)+# Alert states from which launching an investigation may forward-advance an+# alert to 'investigating'. Terminal states (resolved/false_positive/closed)+# and an already-running alert are deliberately excluded: a re-run must never+# drag history backwards.+_ALERT_OPEN_STATUSES: tuple[str, ...] = ("new", "triaged", "triaging")++def _forward_to_investigating_ok(current: str) -> bool:"""Can an agent-investigation launch move this case to investigating?@@ -1641,6 +1648,35 @@ async def case_investigate(await db.rollback()logger.warning("investigate.launch.status_advance_failed case_id=%s", cid, exc_info=True)+ # The same honesty applies to the alerts themselves: an alert under+ # agent investigation is not "new" anymore. Advance the case's linked+ # alerts to 'investigating' in the same request — forward-only, so+ # resolved/false-positive/closed alerts are never dragged backwards,+ # and alerts already further along (in_progress) are left alone.+ if case_alert_ids:+ try:+ bump = await db.execute(+ text(+ "UPDATE alerts SET status = 'investigating', updated_at = :now "+ "WHERE id::text = ANY(:ids) AND tenant_id = :tenant_id "+ "AND status IN ({})".format(", ".join(f"'{st}'" for st in _ALERT_OPEN_STATUSES))+ ).bindparams(+ ids=[str(a) for a in case_alert_ids],+ tenant_id=user.tenant_id,+ now=datetime.now(UTC),+ )+ )+ await db.commit()+ if bump.rowcount:+ logger.info(+ "investigate.launch.alerts_advance case_id=%s alert_count=%s",+ cid,+ bump.rowcount,+ )+ except Exception: # noqa: BLE001 — never block the launch on the alert bump+ await db.rollback()+ logger.warning("investigate.launch.alerts_advance_failed case_id=%s", cid, exc_info=True)+resp = await _agents_proxy("POST",f"/api/v1/cases/{cid}/investigate",diff --git a/services/api/app/api/v1/endpoints/rbac.py b/services/api/app/api/v1/endpoints/rbac.pyindex 797086db0..94e1c61f1 100644--- a/services/api/app/api/v1/endpoints/rbac.py+++ b/services/api/app/api/v1/endpoints/rbac.py@@ -8,21 +8,26 @@ Requires:- ``users:write`` to assign / revoke roles from users"""+import reimport uuid-from typing import Annotated+from datetime import UTC, datetime+from typing import Annotated, Any-from fastapi import APIRouter, Depends, HTTPException, status-from pydantic import BaseModel-from sqlalchemy import delete, select+from fastapi import APIRouter, Body, Depends, HTTPException, Request, status+from pydantic import BaseModel, Field, field_validator+from sqlalchemy import delete, func, select, text, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinloadfrom app.api.v1.deps import AuthUser, require_permission+from app.core import role_grantsfrom app.core.permission_cache import bump_version+from app.core.rbac_catalog import SSO_DEFAULT_ROLE, seed_tenant_catalogfrom app.core.role_grants import RoleGrantDenied, authorize_permission_grantfrom app.db.rls import TenantDBSessionfrom app.models.rbac import Permission, Role, RolePermission, UserRolefrom app.models.tenant import User+from app.services.audit import emit_auditrouter = APIRouter(prefix="/rbac", tags=["rbac"])@@ -63,25 +68,88 @@ class PermissionOut(BaseModel):model_config = {"from_attributes": True}+#: Machine-safe slug, immutable after create. The name reaches users.role,+#: JWT static-map resolution, audit resource strings and URL segments; the+#: human-facing text lives in `label`.+ROLE_NAME_RE = re.compile(r"^[a-z][a-z0-9]*(-[a-z0-9]+)*$")++#: Names the platform owns. Creating one shadows a seeded role or the+#: static-map path; renaming into one is blocked by immutability anyway.+RESERVED_ROLE_NAMES = frozenset({"admin", "platform_admin", "viewer", "infosec", "user", "operator", "api_client"})++class RoleIn(BaseModel):- name: str+ name: str = Field(min_length=2, max_length=100)+ label: str | None = Field(default=None, max_length=200)description: str | None = Nonepermission_ids: list[uuid.UUID] = []+ permission_names: list[str] = []++ @field_validator("name")+ @classmethod+ def _validate_slug(cls, v: str) -> str:+ v = v.strip().lower()+ if not ROLE_NAME_RE.match(v):+ raise ValueError("role name must be a lowercase slug: letters/numbers, single hyphens, starting with a letter")+ if v in RESERVED_ROLE_NAMES:+ raise ValueError(f"{v!r} is a reserved platform role name")+ return vclass RoleUpdate(BaseModel):- name: str | None = None+ """The machine `name` is immutable after create: it is mirrored into+ users.role, resolved against the JWT static map, and written into audit+ resource strings; renaming a live role would strand all three. The field+ stays on the wire (SDK clients generated against earlier releases send+ it) and is validated as a no-op: omit it, or send the role's current+ name — an actual rename is a 400 that says why. Edit `label` and+ `description` for the human-facing text."""++ name: str | None = Field(default=None, max_length=100)+ label: str | None = Field(default=None, max_length=200)description: str | None = Nonepermission_ids: list[uuid.UUID] | None = None+ permission_names: list[str] | None = None+++class PermissionNamesIn(BaseModel):+ """Body for `PUT /roles/{id}/permissions`.++ The console sends `{"permissions": ["alerts:read", ...]}` and the+ route additionally accepts the bare list shape (see the endpoint);+ either way every key is validated against the platform vocabulary+ before anything is deleted, so an unknown key is a 400 that names the+ valid set instead of a silent partial update.+ """++ permissions: list[str] = Field(min_length=0)++ @field_validator("permissions")+ @classmethod+ def _dedupe(cls, v: list[str]) -> list[str]:+ seen: set[str] = set()+ out: list[str] = []+ for name in v:+ if name not in seen:+ seen.add(name)+ out.append(name)+ return out+++class PermissionNameIn(BaseModel):+ permission: str = Field(min_length=1, max_length=200)class RoleOut(BaseModel):id: uuid.UUIDtenant_id: uuid.UUIDname: str+ label: str | None = Nonedescription: str | Noneis_system: boolpermissions: list[PermissionOut] = []+ user_count: int = 0+ is_sso_default: bool = Falsemodel_config = {"from_attributes": True}@@ -89,6 +157,21 @@ class RoleOut(BaseModel):class UserRoleAssignment(BaseModel):user_id: uuid.UUIDrole_id: uuid.UUID+ reason: str | None = Field(default=None, max_length=500)+++class PrimaryRoleAssignment(BaseModel):+ """Body for `PUT /rbac/users/{id}/role` — replaces the primary role.++ `role_name` names a seeded catalog role (`viewer` | `infosec` | `admin`+ or a tenant custom role); the server resolves it against this tenant's+ catalog and refuses anything it does not recognize with a 400 naming the+ valid set — a 500 would leak the schema, and a silent 404 would make a+ typo look like an outage.+ """++ role_name: str = Field(min_length=1, max_length=100)+ reason: str | None = Field(default=None, max_length=500)class UserRoleOut(BaseModel):@@ -128,7 +211,12 @@ async def list_roles(current_user: Annotated[AuthUser, Depends(require_permission("roles:read"))],db: TenantDBSession,) -> list[RoleOut]:- """List all roles for the current tenant."""+ """List all roles for the current tenant, with permissions and headcount.++ `user_count` counts this tenant's users holding each role — the Roles+ screen shows it so an operator can see who would move when a role's+ grants change, not just what the grants are.+ """result = await db.execute(select(Role).where(Role.tenant_id == current_user.tenant_id)@@ -136,6 +224,19 @@ async def list_roles(.order_by(Role.name))roles = result.scalars().all()++ counts = dict(+ (+ await db.execute(+ select(UserRole.role_id, func.count())+ .join(User, User.id == UserRole.user_id)+ .join(Role, Role.id == UserRole.role_id)+ .where(Role.tenant_id == current_user.tenant_id)+ .group_by(UserRole.role_id)+ )+ ).all()+ )+out: list[RoleOut] = []for role in roles:perms = [PermissionOut.model_validate(rp.permission) for rp in role.role_permissions]@@ -144,44 +245,96 @@ async def list_roles(id=role.id,tenant_id=role.tenant_id,name=role.name,+ label=role.label,description=role.description,is_system=role.is_system,permissions=perms,+ user_count=int(counts.get(role.id, 0)),+ is_sso_default=role.name == SSO_DEFAULT_ROLE,))return out[email protected]("/roles/seed", response_model=dict)+async def seed_roles(+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> dict:+ """Seed this tenant's catalog from `app.core.rbac_catalog`.++ Idempotent — safe to call from the Roles screen's empty state ("Seed+ roles") as often as you like. Catalog rows and the membership backfill+ land in one transaction, so a half-seeded tenant (roles with no+ members, every member resolving to zero permissions) is not a state this+ endpoint can leave behind.+ """+ counts = await seed_tenant_catalog(db, current_user.tenant_id)+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.catalog_seeded",+ resource="tenant",+ resource_id=str(current_user.tenant_id),+ changes={"counts": counts},+ )+ await db.commit()+ return {"seeded": True, **counts}++@router.post("/roles", response_model=RoleOut, status_code=status.HTTP_201_CREATED)async def create_role(body: RoleIn,+ request: Request,current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],db: TenantDBSession,) -> RoleOut:- """Create a custom role for the current tenant."""- # Check name uniqueness+ """Create a custom role for the current tenant.++ `permission_names` (validated against the platform vocabulary, unknown+ keys → 400 naming them) is the console-facing shape; `permission_ids`+ stays for API clients. Both may be sent; they merge.+ """existing = await db.execute(select(Role).where(Role.tenant_id == current_user.tenant_id, Role.name == body.name))if existing.scalar_one_or_none() is not None:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Role '{body.name}' already exists")- # Resolved and authorized before the role row exists, so a refused- # permission set does not leave an empty role behind.- perms_to_attach = await _resolve_permissions(db, body.permission_ids)+ named = await _resolve_permission_names(db, body.permission_names)+ by_id = await _resolve_permissions(db, body.permission_ids)+ seen_ids = {p.id for p in by_id}+ perms_to_attach = by_id + [p for p in named if p.id not in seen_ids]_authorize_permission_grant(perms_to_attach, current_user, subject="permission(s)")role = Role(tenant_id=current_user.tenant_id,name=body.name,+ label=(body.label or body.name),description=body.description,is_system=False,)db.add(role)- await db.flush() # get role.id+ await db.flush()- # Attach permissionsfor perm in perms_to_attach:db.add(RolePermission(role_id=role.id, permission_id=perm.id))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_created",+ resource="role",+ resource_id=str(role.id),+ changes={"label": role.label, "permissions_after": sorted(p.name for p in perms_to_attach)},+ request=request,+ )await db.commit()await bump_version(str(current_user.tenant_id))await db.refresh(role)@@ -190,6 +343,7 @@ async def create_role(id=role.id,tenant_id=role.tenant_id,name=role.name,+ label=role.label,description=role.description,is_system=role.is_system,permissions=[PermissionOut.model_validate(p) for p in perms_to_attach],@@ -204,13 +358,17 @@ async def get_role() -> RoleOut:role = await _get_role_or_404(db, role_id, current_user.tenant_id)perms = await _load_role_permissions(db, role.id)+ count = await db.scalar(select(func.count()).select_from(UserRole).where(UserRole.role_id == role.id))return RoleOut(id=role.id,tenant_id=role.tenant_id,name=role.name,+ label=role.label,description=role.description,is_system=role.is_system,permissions=perms,+ user_count=int(count or 0),+ is_sso_default=role.name == SSO_DEFAULT_ROLE,)@@ -218,32 +376,77 @@ async def get_role(async def update_role(role_id: uuid.UUID,body: RoleUpdate,+ request: Request,current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],db: TenantDBSession,) -> RoleOut:+ """Edit label/description (and, optionally, replace the permission set).++ System roles are refused with an explanatory 403 body that names the+ role: the lock is a server rule, not a hidden button. `name` cannot be+ edited — see RoleUpdate."""role = await _get_role_or_404(db, role_id, current_user.tenant_id)+ if body.name is not None and body.name != role.name:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"Role name is immutable after create (current name '{role.name}'): "+ "it is mirrored into users.role, the JWT role map, and audit "+ "resource strings. Edit label/description, or create a new role."+ ),+ )+if role.is_system:- raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="System roles cannot be modified")+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=(+ f"Role '{role.name}' is a system role: its name and permission set are protected. "+ "Duplicate it to create an editable custom role."+ ),+ )- # Resolved and authorized before the DELETE below, which would otherwise- # strip the role's existing permissions on the way to a refusal.- perms: list[Permission] = []- if body.permission_ids is not None:- perms = await _resolve_permissions(db, body.permission_ids)+ perms: list[Permission] | None = None+ if body.permission_ids is not None or body.permission_names is not None:+ named = await _resolve_permission_names(db, body.permission_names or [])+ by_id = await _resolve_permissions(db, body.permission_ids or [])+ seen_ids = {p.id for p in by_id}+ perms = by_id + [p for p in named if p.id not in seen_ids]_authorize_permission_grant(perms, current_user, subject="permission(s)")- if body.name is not None:- role.name = body.name+ before = sorted(p.name for p in await _load_role_models(db, role.id))+ if body.label is not None:+ role.label = body.labelif body.description is not None:role.description = body.description- if body.permission_ids is not None:- # Replace permissions+ if perms is not None:+ # Replace permissions — same transaction as the audit row below;+ # a crash between DELETE and INSERT rolls both back, never partial.await db.execute(delete(RolePermission).where(RolePermission.role_id == role.id))for perm in perms:db.add(RolePermission(role_id=role.id, permission_id=perm.id))+ after = sorted(p.name for p in (perms if perms is not None else await _load_role_models(db, role.id)))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_updated",+ resource="role",+ resource_id=str(role.id),+ changes={+ "label": role.label,+ "permissions_before": before,+ "permissions_after": after,+ "removed": sorted(set(before) - set(after)),+ "added": sorted(set(after) - set(before)),+ "affected_users": await _permission_affected_users(db, role.id),+ },+ request=request,+ )await db.commit()await bump_version(str(current_user.tenant_id))await db.refresh(role)@@ -252,22 +455,219 @@ async def update_role(id=role.id,tenant_id=role.tenant_id,name=role.name,+ label=role.label,+ description=role.description,+ is_system=role.is_system,+ permissions=perms_out,+ user_count=await _permission_affected_users(db, role.id),+ is_sso_default=role.name == SSO_DEFAULT_ROLE,+ )++[email protected]("/roles/{role_id}/permissions", response_model=RoleOut)+async def replace_role_permissions(+ role_id: uuid.UUID,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+ body: Annotated[PermissionNamesIn | None, Body()] = None,+ raw: Annotated[Any, Body(embed=False)] = None,+) -> RoleOut:+ """Replace the role's full permission set (atomic, audited, before/after).++ Accepts `{"permissions": ["alerts:read", ...]}` or a bare list+ `["alerts:read", ...]` — both shapes validate every key against the+ vocabulary first, so an unknown key is a 400 that names it, never a+ silently dropped grant.+ """+ names: list[str] = []+ if body is not None:+ names = body.permissions+ elif isinstance(raw, list):+ names = [str(x) for x in raw]+ elif isinstance(raw, dict) and isinstance(raw.get("permissions"), list):+ names = [str(x) for x in raw["permissions"]]++ role = await _get_role_or_404(db, role_id, current_user.tenant_id)+ if role.is_system:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"Role '{role.name}' is a system role: its permission set is protected and cannot be edited.",+ )++ perms = await _resolve_permission_names(db, names)+ _authorize_permission_grant(perms, current_user, subject="permission(s)")++ before = sorted(p.name for p in await _load_role_models(db, role.id))+ await db.execute(delete(RolePermission).where(RolePermission.role_id == role.id))+ for perm in perms:+ db.add(RolePermission(role_id=role.id, permission_id=perm.id))++ after = sorted(p.name for p in perms)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_permissions_replaced",+ resource="role",+ resource_id=str(role.id),+ changes={+ "permissions_before": before,+ "permissions_after": after,+ "removed": sorted(set(before) - set(after)),+ "added": sorted(set(after) - set(before)),+ "affected_users": await _permission_affected_users(db, role.id),+ },+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ return RoleOut(+ id=role.id,+ tenant_id=role.tenant_id,+ name=role.name,+ label=role.label,+ description=role.description,+ is_system=role.is_system,+ permissions=[PermissionOut.model_validate(p) for p in perms],+ user_count=await _permission_affected_users(db, role.id),+ is_sso_default=role.name == SSO_DEFAULT_ROLE,+ )++[email protected]("/roles/{role_id}/permissions", response_model=RoleOut, status_code=status.HTTP_201_CREATED)+async def add_role_permission(+ role_id: uuid.UUID,+ body: PermissionNameIn,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> RoleOut:+ role = await _get_role_or_404(db, role_id, current_user.tenant_id)+ if role.is_system:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"Role '{role.name}' is a system role: its permission set is protected and cannot be edited.",+ )+ [perm] = await _resolve_permission_names(db, [body.permission])+ _authorize_permission_grant([perm], current_user, subject=f"permission {perm.name!r}")++ existing = await db.execute(select(RolePermission).where(RolePermission.role_id == role.id, RolePermission.permission_id == perm.id))+ if existing.scalar_one_or_none() is None:+ db.add(RolePermission(role_id=role.id, permission_id=perm.id))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_permission_added",+ resource="role",+ resource_id=str(role.id),+ changes={"added": perm.name, "affected_users": await _permission_affected_users(db, role.id)},+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ perms_out = await _load_role_permissions(db, role.id)+ return RoleOut(+ id=role.id,+ tenant_id=role.tenant_id,+ name=role.name,+ label=role.label,+ description=role.description,+ is_system=role.is_system,+ permissions=perms_out,+ user_count=await _permission_affected_users(db, role.id),+ is_sso_default=role.name == SSO_DEFAULT_ROLE,+ )++[email protected]("/roles/{role_id}/permissions/{permission_name}", response_model=RoleOut)+async def remove_role_permission(+ role_id: uuid.UUID,+ permission_name: str,+ request: Request,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> RoleOut:+ role = await _get_role_or_404(db, role_id, current_user.tenant_id)+ if role.is_system:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"Role '{role.name}' is a system role: its permission set is protected and cannot be edited.",+ )+ [perm] = await _resolve_permission_names(db, [permission_name])++ existing = await db.execute(select(RolePermission).where(RolePermission.role_id == role.id, RolePermission.permission_id == perm.id))+ if existing.scalar_one_or_none() is not None:+ await db.execute(delete(RolePermission).where(RolePermission.role_id == role.id, RolePermission.permission_id == perm.id))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_permission_removed",+ resource="role",+ resource_id=str(role.id),+ changes={"removed": perm.name, "affected_users": await _permission_affected_users(db, role.id)},+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ perms_out = await _load_role_permissions(db, role.id)+ return RoleOut(+ id=role.id,+ tenant_id=role.tenant_id,+ name=role.name,+ label=role.label,description=role.description,is_system=role.is_system,permissions=perms_out,+ user_count=await _permission_affected_users(db, role.id),+ is_sso_default=role.name == SSO_DEFAULT_ROLE,)@router.delete("/roles/{role_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)async def delete_role(role_id: uuid.UUID,+ request: Request,current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],db: TenantDBSession,) -> None:role = await _get_role_or_404(db, role_id, current_user.tenant_id)if role.is_system:- raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="System roles cannot be deleted")+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"Role '{role.name}' is a system role and cannot be deleted.",+ )+ # FK CASCADE would silently detach members; the product rule is: refuse,+ # with the count, until the operator reassigns them explicitly.+ users = await _permission_affected_users(db, role.id)+ if users:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=f"Role is assigned to {users} user(s). Remove the role from those users first.",+ )+ perms_before = sorted(p.name for p in await _load_role_models(db, role.id))+ role_name = role.nameawait db.delete(role)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_deleted",+ resource="role",+ resource_id=str(role_id),+ changes={"name": role_name, "permissions_before": perms_before},+ request=request,+ )await db.commit()await bump_version(str(current_user.tenant_id))@@ -296,11 +696,98 @@ async def get_user_roles(return [UserRoleOut(user_id=row.UserRole.user_id, role_id=row.UserRole.role_id, role_name=row.name) for row in rows][email protected]("/users/{user_id}/role", response_model=UserRoleOut)+async def set_primary_role(+ user_id: uuid.UUID,+ body: PrimaryRoleAssignment,+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],+ db: TenantDBSession,+) -> UserRoleOut:+ """Replace the user's primary role — the console's `Assign role` action.++ Multi-role storage, single-role product: the assignment set becomes the+ one chosen role, and `users.role` — the string the JWT/static path+ reads — is mirrored to match, so the two authorization paths cannot+ disagree after this call. Takes effect on the target's next request:+ the permission cache version bumps, and the verifier re-reads+ `users.role` from the database. No re-login required.++ Refusals, all before any write:+ * 404 target not in tenant; 400 unknown role name (naming the valid+ set) or disabled target; 403 this caller may not confer the role's+ permissions; 409 this would empty the tenant of active admins.+ """+ target = (await db.execute(select(User).where(User.id == user_id, User.tenant_id == current_user.tenant_id))).scalar_one_or_none()+ if target is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found in tenant")+ if not target.is_active:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot assign roles to a disabled user")++ role = (+ await db.execute(select(Role).where(Role.tenant_id == current_user.tenant_id, Role.name == body.role_name))+ ).scalar_one_or_none()+ if role is None:+ valid = sorted((await db.execute(select(Role.name).where(Role.tenant_id == current_user.tenant_id))).scalars().all())+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"Unknown role {body.role_name!r}. Valid roles for this tenant: "+ f"{', '.join(valid) or '(none seeded — seed the catalog first)'}"+ ),+ )++ # The granter may only confer what they hold (GHSA lineage: a scoped+ # caller minting unscoped authority).+ _authorize_permission_grant(+ await _load_role_models(db, role.id),+ current_user,+ subject=f"permission(s) carried by role {role.name!r}",+ )++ old_role = str(target.role)+ wildcard = sorted(role_grants.wildcard_roles())+ demoting_admin = old_role in wildcard and role.name not in wildcard+ if demoting_admin or (current_user.user_id == user_id and demoting_admin):+ remaining = await db.scalar(+ text("SELECT count(*) FROM users WHERE tenant_id = :t AND is_active = TRUE AND role = ANY(:wild) AND id <> :keep").bindparams(+ t=str(current_user.tenant_id), wild=wildcard, keep=str(user_id)+ )+ )+ if not remaining:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="this is the last active administrator in the tenant; promote another admin before demoting this one",+ )++ now = datetime.now(UTC)+ await db.execute(delete(UserRole).where(UserRole.user_id == user_id))+ db.add(UserRole(user_id=user_id, role_id=role.id, assigned_by=current_user.user_id))+ await db.execute(update(User).where(User.id == user_id).values(role=role.name, updated_at=now))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_assigned",+ resource="user",+ resource_id=str(user_id),+ changes={"old_role": old_role, "new_role": role.name, "reason": (body.reason or "")[:500]},+ )+ await db.commit()+ # After commit: the cache bump must not be able to strand a half-apply+ # (a bumped version pointing at uncommitted rows would be self-healing+ # anyway, but ordering it last keeps the invariant obvious).+ await bump_version(str(current_user.tenant_id))++ return UserRoleOut(user_id=user_id, role_id=role.id, role_name=role.name)++@router.post("/users/{user_id}/roles", response_model=UserRoleOut, status_code=status.HTTP_201_CREATED)async def assign_role(user_id: uuid.UUID,body: UserRoleAssignment,- current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],db: TenantDBSession,) -> UserRoleOut:"""Assign a role to a user."""@@ -331,6 +818,17 @@ async def assign_role(assignment = UserRole(user_id=user_id, role_id=role.id, assigned_by=current_user.user_id)db.add(assignment)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_added",+ resource="user",+ resource_id=str(user_id),+ changes={"new_role": role.name, "reason": (body.reason or "")[:500]},+ )await db.commit()await bump_version(str(current_user.tenant_id))return UserRoleOut(user_id=user_id, role_id=role.id, role_name=role.name)@@ -340,11 +838,43 @@ async def assign_role(async def revoke_role(user_id: uuid.UUID,role_id: uuid.UUID,- current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],+ current_user: Annotated[AuthUser, Depends(require_permission("roles:write"))],db: TenantDBSession,) -> None:- """Revoke a role from a user."""+ """Revoke a role from a user.++ Last-admin lockout guard: revoking the role that IS the tenant's admin+ role from the last active holder is refused with 409, same rule as+ `PUT /users/{id}/role` and `PATCH /tenants/me/users/{id}` — every door+ that removes management authority checks it, because "one of the doors+ remembers" is no control at all.+ """+ role = await _get_role_or_404(db, role_id, current_user.tenant_id)+ wildcard = sorted(role_grants.wildcard_roles())+ if role.name in wildcard:+ remaining = await db.scalar(+ text("SELECT count(*) FROM users WHERE tenant_id = :t AND is_active = TRUE AND role = ANY(:wild) AND id <> :keep").bindparams(+ t=str(current_user.tenant_id), wild=wildcard, keep=str(user_id)+ )+ )+ if not remaining:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="this is the last active administrator in the tenant; promote another admin before revoking this role",+ )+await db.execute(delete(UserRole).where(UserRole.user_id == user_id, UserRole.role_id == role_id))+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="rbac.role_revoked",+ resource="user",+ resource_id=str(user_id),+ changes={"revoked_role": role.name},+ )await db.commit()await bump_version(str(current_user.tenant_id))@@ -362,6 +892,35 @@ async def _get_role_or_404(db: AsyncSession, role_id: uuid.UUID, tenant_id: uuidreturn role+async def _resolve_permission_names(db: AsyncSession, names: list[str]) -> list[Permission]:+ """Resolve permission *keys* against the platform vocabulary.++ Unknown keys → 400 listing the valid set (sorted, capped so a typo in+ front of a 61-row vocabulary still fits comfortably in the body). A+ silent skip would be the worst failure mode here: the operator would+ believe the grant landed.+ """+ if not names:+ return []+ uniq = sorted(set(names))+ result = await db.execute(select(Permission).where(Permission.name.in_(uniq)))+ found = list(result.scalars().all())+ found_names = {p.name for p in found}+ missing = [n for n in uniq if n not in found_names]+ if missing:+ valid = sorted((await db.execute(select(Permission.name))).scalars().all())+ preview = ", ".join(valid[:80]) + (" …" if len(valid) > 80 else "")+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"Unknown permission key(s): {', '.join(missing)}. Valid keys: {preview}",+ )+ return found+++async def _permission_affected_users(db: AsyncSession, role_id: uuid.UUID) -> int:+ return int(await db.scalar(text("SELECT count(*) FROM user_roles WHERE role_id = CAST(:r AS uuid)").bindparams(r=str(role_id))) or 0)++async def _resolve_permissions(db: AsyncSession, permission_ids: list[uuid.UUID]) -> list[Permission]:if not permission_ids:return []diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex cdd8b1bc5..b522fea06 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -3,6 +3,7 @@from fastapi import APIRouterfrom app.api.v1.endpoints import (+ admin_users,agent_tools,agents,airgap,@@ -158,6 +159,7 @@ api_router.include_router(mcp_servers.router)# on the path of an investigation.api_router.include_router(tenant_skills.router)api_router.include_router(rbac.router)+api_router.include_router(admin_users.router)api_router.include_router(audit.router)api_router.include_router(branding.router)api_router.include_router(compliance.router)diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.pyindex 6f0ae1e44..7911e087e 100644--- a/services/api/app/auth/oidc.py+++ b/services/api/app/auth/oidc.py@@ -30,7 +30,7 @@ import secretsfrom datetime import UTC, datetime, timedeltafrom functools import lru_cachefrom typing import Any-from urllib.parse import urlencode, urlparse+from urllib.parse import quote, urlencode, urlparseimport httpximport jwt as _jwt@@ -448,10 +448,15 @@ async def oidc_callback(# "login failed" is a support ticket.raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc- redirect_url = _safe_redirect(state_data.get("redirect", "/"))- # The token travels in the fragment, which browsers do not send to the- # server and which does not land in an access log or a Referer header,- # and the console moves it into the storage its API client reads.+ # Land on the login page with the session in the fragment, NOT directly+ # on the requested page: the fragment consumer lives on /login, and any+ # auth guard on the destination would bounce to /login?next=... — a+ # query-string redirect that silently drops the fragment and loses the+ # token. /login consumes it, persists the session, then routes to+ # ?next=. The fragment never reaches the server or an access log.+ target = state_data.get("redirect", "/")+ safe_target = _safe_redirect(target)+ redirect_url = f"/login?next={quote(safe_target, safe='')}"separator = "&" if "#" in redirect_url else "#"response = RedirectResponse(url=f"{redirect_url}{separator}access_token={session['access_token']}&refresh_token={session['refresh_token']}",diff --git a/services/api/app/auth/sso_provisioning.py b/services/api/app/auth/sso_provisioning.pyindex 4434f63d1..69ae74f6a 100644--- a/services/api/app/auth/sso_provisioning.py+++ b/services/api/app/auth/sso_provisioning.py@@ -45,6 +45,7 @@ from typing import Anyfrom sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.rbac_catalog import sync_user_catalog_rolefrom app.core.security import create_access_token, create_refresh_tokenfrom app.db.rls import set_rls_contextfrom app.services.audit import emit_audit@@ -270,6 +271,14 @@ async def provision_user(_sanitize(previous_role, 40),_sanitize(role, 40),)+ # Catalog parity: the `users.role` string this path decides is also+ # written to `user_roles`, so a tenant running on database-backed+ # RBAC grants exactly what it just decided rather than whatever the+ # last backfill happened to attach. On `first_login_only` the role+ # above IS the admin's manually assigned role, so this is a no-op+ # re-affirmation — group sync cannot move it, in the tables or on+ # the column.+ await sync_user_catalog_role(db, tenant_id=tenant_id, user_id=bound["user_id"], role_name=role)return {"id": bound["user_id"], "email": bound["email"], "role": role, "created": False, "previous_role": previous_role}# ── 2. Claim by verified email ────────────────────────────────────────@@ -360,6 +369,7 @@ async def provision_user(_sanitize(existing["role"], 40),_sanitize(role, 40),)+ await sync_user_catalog_role(db, tenant_id=tenant_id, user_id=existing["id"], role_name=role)return {"id": existing["id"], "email": existing["email"], "role": role, "created": False}if not jit_provisioning:@@ -408,6 +418,13 @@ async def provision_user(provider=provider,)+ # Same parity rule as the two paths above: a JIT user in a+ # database-backed tenant without a `user_roles` row resolves to zero+ # permissions. Provisioning decided `viewer` (or a mapped role that+ # already passed the assignable allow-list); the catalog row of the+ # same name is attached here, in this transaction.+ await sync_user_catalog_role(db, tenant_id=tenant_id, user_id=user_id, role_name=role)+logger.info("sso.user_provisioned email=%s role=%s provider=%s",_sanitize(email, 80),diff --git a/services/api/app/core/logging.py b/services/api/app/core/logging.pyindex 5f604dbee..b52faa05d 100644--- a/services/api/app/core/logging.py+++ b/services/api/app/core/logging.py@@ -1,6 +1,7 @@"""Structured logging configuration using structlog."""import logging+import osimport sysimport structlog@@ -38,8 +39,10 @@ def configure_logging() -> None:cache_logger_on_first_use=True,)- # Silence noisy libraries- logging.getLogger("uvicorn.access").setLevel(logging.WARNING)+ # Silence noisy libraries. `uvicorn.access` is opt-in via+ # AISOC_ACCESS_LOG=1: without it a post-login bounce cannot be attributed+ # to a specific request, since no per-request line reaches the logs.+ logging.getLogger("uvicorn.access").setLevel(logging.INFO if os.getenv("AISOC_ACCESS_LOG") == "1" else logging.WARNING)logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)diff --git a/services/api/app/core/rbac_catalog.py b/services/api/app/core/rbac_catalog.pynew file mode 100644index 000000000..aa2eda5f9--- /dev/null+++ b/services/api/app/core/rbac_catalog.py@@ -0,0 +1,301 @@+"""The seeded RBAC catalog: roles, their permissions, and the seed path.++Why a module and not just a migration+--------------------------------------+``092_rbac_catalog_seed.sql`` seeds the primary tenant. A second tenant that+adopts database-backed RBAC needs the same catalog, and it needs it with the+same guarantees: catalog rows and membership backfill in ONE transaction,+because a tenant that has roles but no memberships resolves every user to+zero permissions. Two copies of that vocabulary — one in the migration, one+in the endpoint that seeds other tenants — drift. So the vocabulary lives+here, the migration embeds the same lists, and the two are pinned equal by+``services/api/tests/test_rbac_catalog_seed.py``.++Deny-by-default lives in ``permission_cache.resolve_permissions``: once a+tenant has any role row, only ``role_permissions``/``user_roles`` answer.+This module is the *data* side of that decision; the enforcement side is+unchanged.+"""++from __future__ import annotations++import logging+from typing import Any, Final++from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++logger = logging.getLogger(__name__)++#: The permission vocabulary (name, description, category). `*` is a real+#: row: it is what the admin role's grant literally contains, so the Roles+#: screen can show what it confers instead of a footnote.+PERMISSIONS: Final[tuple[tuple[str, str, str], ...]] = (+ ("alerts:read", "View alerts", "alerts"),+ ("alerts:write", "Acknowledge / triage / update alerts", "alerts"),+ ("alerts:delete", "Delete alerts", "alerts"),+ ("cases:read", "View cases", "cases"),+ ("cases:write", "Create and edit cases", "cases"),+ ("cases:delete", "Delete cases", "cases"),+ ("cases:assign", "Assign cases to people", "cases"),+ ("cases:note", "Add notes to cases", "cases"),+ ("detections:read", "View detections", "detections"),+ ("detections:write", "Manage detections", "detections"),+ ("detections:delete", "Delete detections", "detections"),+ ("rules:read", "View detection rules", "rules"),+ ("rules:write", "Create and edit detection rules", "rules"),+ ("dashboards:read", "View dashboards", "dashboards"),+ ("reports:read", "View reports", "reports"),+ ("reports:write", "Generate and edit reports", "reports"),+ ("reports:export", "Export reports", "reports"),+ ("compliance:read", "View compliance posture", "compliance"),+ ("playbooks:read", "View playbooks", "playbooks"),+ ("playbooks:write", "Edit playbooks", "playbooks"),+ ("playbooks:execute", "Run playbooks", "playbooks"),+ ("actions:read", "View the response-action registry", "actions"),+ ("actions:execute", "Execute response actions", "actions"),+ ("investigation:run", "Run an investigation", "investigations"),+ ("threat_intel:read", "View threat intelligence", "threat_intel"),+ ("threat_intel:write", "Manage threat intelligence", "threat_intel"),+ ("threatintel:manage", "Manage threat intelligence (alias)", "threat_intel"),+ ("connectors:read", "View connectors", "connectors"),+ ("connectors:write", "Configure connectors", "connectors"),+ ("connectors:delete", "Delete connectors", "connectors"),+ ("lake:query", "Query the data lake", "lake"),+ ("lake:read_schema", "Read the lake schema", "lake"),+ ("hunts:read", "View hunts", "hunts"),+ ("knowledge_base:read", "Search the knowledge base", "knowledge_base"),+ ("graph:read", "View the investigation graph", "graph"),+ ("users:read", "View users", "admin"),+ ("users:write", "Create, edit and role-manage users", "admin"),+ ("users:delete", "Delete users", "admin"),+ ("users:manage", "Manage users (alias)", "admin"),+ ("roles:read", "View roles and permissions", "admin"),+ ("roles:write", "Create, edit and delete roles", "admin"),+ ("roles:assign", "Assign roles to users (alias)", "admin"),+ ("tenant:read", "View tenant settings", "admin"),+ ("tenant:write", "Change tenant settings", "admin"),+ ("settings:read", "Read settings", "admin"),+ ("settings:write", "Change settings", "admin"),+ ("settings:manage", "Manage settings (alias)", "admin"),+ ("sso:configure", "Configure SSO connections", "admin"),+ ("api_keys:read", "View API keys", "api_keys"),+ ("api_keys:write", "Create and revoke API keys", "api_keys"),+ ("api_keys:delete", "Delete API keys", "api_keys"),+ ("apikeys:manage", "Manage API keys (alias)", "api_keys"),+ ("audit_log:read", "Read the audit log", "audit"),+ ("audit:read", "Read the audit log (alias)", "audit"),+ ("sla:read", "View SLA metrics", "sla"),+ ("sla:write", "Change SLA policy", "sla"),+ ("plugins:read", "View plugins", "plugins"),+ ("plugins:admin", "Administer plugins", "plugins"),+ ("plugins:execute", "Execute plugins", "plugins"),+ ("*", "Every permission (wildcard; admin role)", "system"),+)++#: The three product roles: (name, description). `viewer` is the SSO JIT+#: default and is protected (is_system) by construction.+SYSTEM_ROLES: Final[tuple[tuple[str, str], ...]] = (+ ("viewer", "Regular User. View-only. The default role for SSO just-in-time provisioning."),+ ("infosec", "Infosec analyst / incident handler. Investigates, triages and responds; manages no users, roles, SSO or settings."),+ ("admin", "Platform administrator. Full control of this tenant, including users, roles, SSO configuration and the audit log."),+)++#: Human display names for the system roles (the `label` column; `name`+#: stays the machine slug). Custom roles set their own label at create.+SYSTEM_ROLE_LABELS: Final[dict[str, str]] = {+ "viewer": "Regular User",+ "infosec": "Infosec Analyst",+ "admin": "Platform Administrator",+}++#: The SSO just-in-time default, kept as a name here so the Roles screen can+#: badge it without querying the connection table.+SSO_DEFAULT_ROLE: Final[str] = "viewer"++_VIEWER: Final[frozenset[str]] = frozenset(+ {+ "alerts:read",+ "cases:read",+ "dashboards:read",+ "detections:read",+ "reports:read",+ "connectors:read",+ "threat_intel:read",+ "actions:read",+ "knowledge_base:read",+ }+)++_INFOSEC: Final[frozenset[str]] = _VIEWER | frozenset(+ {+ "alerts:write",+ "cases:write",+ "cases:assign",+ "cases:note",+ "playbooks:read",+ "playbooks:execute",+ "threat_intel:write",+ "threatintel:manage",+ "rules:read",+ "rules:write",+ "detections:write",+ "hunts:read",+ "lake:query",+ "lake:read_schema",+ "graph:read",+ "actions:execute",+ "investigation:run",+ "reports:write",+ "reports:export",+ }+)++#: role name -> permission names it is granted. `admin` holds the wildcard.+ROLE_GRANTS: Final[dict[str, frozenset[str]]] = {+ "viewer": _VIEWER,+ "infosec": _INFOSEC,+ "admin": frozenset({"*"}),+}+++async def seed_tenant_catalog(db: AsyncSession, tenant_id: Any) -> dict[str, int]:+ """Seed the catalog for one tenant, atomically, idempotently.++ One transaction on purpose: `resolve_permissions` switches a tenant to+ database-backed mode the moment `roles` has a row, and a user without a+ `user_roles` row in such a tenant resolves to zero permissions. So the+ roles, the grants and the membership backfill land together or not at+ all. The caller commits.++ Returns row counts for the endpoint response and the migration summary.+ """+ tid = str(tenant_id)++ await db.execute(+ text(+ """+ INSERT INTO permissions (name, description, category)+ VALUES (:name, :description, :category)+ ON CONFLICT (name) DO UPDATE+ SET description = EXCLUDED.description,+ category = EXCLUDED.category+ """+ ),+ [{"name": name, "description": desc, "category": cat} for name, desc, cat in PERMISSIONS],+ )++ await db.execute(+ text(+ """+ INSERT INTO roles (tenant_id, name, label, description, is_system)+ VALUES (CAST(:t AS uuid), :name, :label, :description, TRUE)+ ON CONFLICT (tenant_id, name) DO UPDATE+ SET description = EXCLUDED.description+ """+ ),+ [+ {+ "t": tid,+ "name": name,+ "label": SYSTEM_ROLE_LABELS.get(name, name),+ "description": desc,+ }+ for name, desc in SYSTEM_ROLES+ ],+ )++ grant_rows: list[dict[str, str]] = []+ for role_name, perms in ROLE_GRANTS.items():+ for perm in sorted(perms):+ grant_rows.append({"t": tid, "role": role_name, "perm": perm})+ await db.execute(+ text(+ """+ INSERT INTO role_permissions (role_id, permission_id)+ SELECT r.id, p.id+ FROM roles r+ JOIN permissions p ON p.name = :perm+ WHERE r.tenant_id = CAST(:t AS uuid) AND r.name = :role+ ON CONFLICT DO NOTHING+ """+ ),+ grant_rows,+ )++ # Membership backfill (header explains why it cannot be a separate+ # transaction). `assigned_by IS NULL` marks seeded rows: operator+ # assignments always carry an actor id.+ await db.execute(+ text(+ """+ INSERT INTO user_roles (user_id, role_id)+ SELECT u.id, r.id+ FROM users u+ JOIN roles r ON r.tenant_id = u.tenant_id AND r.name = u.role+ WHERE r.tenant_id = CAST(:t AS uuid) AND r.is_system = TRUE+ ON CONFLICT DO NOTHING+ """+ ),+ {"t": tid},+ )+ await db.execute(+ text(+ """+ INSERT INTO user_roles (user_id, role_id)+ SELECT u.id, vr.id+ FROM users u+ JOIN roles vr ON vr.tenant_id = u.tenant_id AND vr.name = :viewer AND vr.is_system = TRUE+ WHERE u.tenant_id = CAST(:t AS uuid)+ AND NOT EXISTS (SELECT 1 FROM user_roles ur WHERE ur.user_id = u.id)+ ON CONFLICT DO NOTHING+ """+ ),+ {"t": tid, "viewer": SSO_DEFAULT_ROLE},+ )++ counts: dict[str, int] = {}+ for key, stmt in {+ "permissions": "SELECT count(*) FROM permissions",+ "roles": "SELECT count(*) FROM roles WHERE tenant_id = CAST(:t AS uuid)",+ "role_permissions": (+ "SELECT count(*) FROM role_permissions rp JOIN roles r ON r.id = rp.role_id WHERE r.tenant_id = CAST(:t AS uuid)"+ ),+ "user_roles": ("SELECT count(*) FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE r.tenant_id = CAST(:t AS uuid)"),+ }.items():+ counts[key] = int((await db.execute(text(stmt), {"t": tid})).scalar() or 0)+ return counts+++async def sync_user_catalog_role(db: AsyncSession, *, tenant_id: Any, user_id: Any, role_name: str) -> None:+ """Point a user's catalog memberships at `role_name` (replace-set).++ Called from SSO provisioning after it has decided the role. Without it a+ JIT-provisioned user has `users.role` but no `user_roles` row, which in+ a catalog tenant means zero permissions. Unknown role name is a no-op+ with a safe warning — the caller has already fallen back to `viewer` by+ the time this runs, and the string on `users.role` is re-synced on the+ next sign-in.+ """+ tid, uid = str(tenant_id), str(user_id)+ row = (+ await db.execute(+ text("SELECT id FROM roles WHERE tenant_id = CAST(:t AS uuid) AND name = :r"),+ {"t": tid, "r": role_name},+ )+ ).first()+ if row is None:+ logger.warning(+ "rbac.catalog_sync_unknown_role user=%s role=%s — no seeded role of that name; memberships left alone",+ uid[:8],+ str(role_name)[:40],+ )+ return+ await db.execute(+ text("DELETE FROM user_roles WHERE user_id = CAST(:u AS uuid) AND role_id <> CAST(:r AS uuid)"),+ {"u": uid, "r": str(row[0])},+ )+ await db.execute(+ text("INSERT INTO user_roles (user_id, role_id) VALUES (CAST(:u AS uuid), CAST(:r AS uuid)) ON CONFLICT DO NOTHING"),+ {"u": uid, "r": str(row[0])},+ )diff --git a/services/api/app/models/rbac.py b/services/api/app/models/rbac.pyindex c0a932f85..72a4a9628 100644--- a/services/api/app/models/rbac.py+++ b/services/api/app/models/rbac.py@@ -31,6 +31,7 @@ class Role(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)name: Mapped[str] = mapped_column(String(100), nullable=False)+ label: Mapped[str | None] = mapped_column(Text, nullable=True)description: Mapped[str | None] = mapped_column(Text, nullable=True)is_system: Mapped[bool] = mapped_column(Boolean, default=False)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/scripts/serve.py b/services/api/app/scripts/serve.pyindex a32124865..29bfc0730 100644--- a/services/api/app/scripts/serve.py+++ b/services/api/app/scripts/serve.py@@ -49,6 +49,9 @@ def main() -> None:"app.main:app","--fd",str(sock.fileno()),+ # Access logs are opt-in here; without them a post-login bounce+ # is undiagnosable (no per-request trace reaches docker logs).+ "--access-log",],)diff --git a/services/api/migrations/091_sso_policy.sql b/services/api/migrations/091_sso_policy.sqlindex b1d172389..9596b5652 100644--- a/services/api/migrations/091_sso_policy.sql+++ b/services/api/migrations/091_sso_policy.sql@@ -16,14 +16,11 @@ ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS group_role_mode TEXTALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS groups_claim TEXT NOT NULL DEFAULT '';ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS login_label TEXT NOT NULL DEFAULT '';--- The `infosec` role: security analyst / incident handler. It is seeded per--- tenant in the application layer (the tenant set is dynamic), but the--- canonical definition lives in `app.core.security.ROLE_PERMISSIONS`; this--- seed covers tenants that predate the role so their admins can assign it--- through the RBAC endpoints immediately.-INSERT INTO roles (tenant_id, name, description, is_system)-SELECT t.id, 'infosec',- 'Security analyst / incident handler: triage, case handling, detections, threat intel, sanitized exports. No user/role/SSO/system management.',- TRUE- FROM tenants t-ON CONFLICT (tenant_id, name) DO NOTHING;+-- The `infosec` role is NOT seeded into `roles` here. `roles` is the+-- per-tenant RBAC override table: its very existence for a tenant flips+-- resolve_permissions from the static map to the database, and a seeded row+-- without matching role_permissions grants every user of that tenant ZERO+-- permissions — including break-glass admin. The canonical definition of+-- `infosec` lives in app.core.security.ROLE_PERMISSIONS and+-- app.core.role_grants.GRANTABLE_ROLES, which is what assignment validates+-- against; nothing in `roles` is needed for it to be assignable.diff --git a/services/api/migrations/092_rbac_catalog_seed.sql b/services/api/migrations/092_rbac_catalog_seed.sqlnew file mode 100644index 000000000..776c2a3b2--- /dev/null+++ b/services/api/migrations/092_rbac_catalog_seed.sql@@ -0,0 +1,214 @@+-- 092_rbac_catalog_seed.sql — the role + permission catalog, seeded as data.+--+-- Why this migration exists+-- -------------------------+-- The RBAC tables (`roles`, `permissions`, `role_permissions`, `user_roles`)+-- shipped with schema but nobody ever seeded `roles` and `role_permissions`.+-- `permission_cache.resolve_permissions` consults the tables as soon as the+-- tenant has ANY role row, and a user with no `user_roles` row then resolves+-- to zero permissions. So the catalog seed and the membership backfill MUST+-- land in the same transaction: seeding roles alone is exactly the+-- permission-blanking failure that `091_sso_policy.sql` caused and that this+-- file permanently repairs.+--+-- Scope: the primary tenant (the one the SSO connection and the break-glass+-- admin belong to) plus any tenant that already has members AND every role+-- string its members hold is covered by the seeded catalog or backfilled to+-- `viewer`. Tenants whose members hold roles outside this catalog+-- (e.g. `soc_lead` demo fixtures) are deliberately NOT flipped to+-- database-backed mode here; they adopt the catalog through+-- `POST /api/v1/rbac/roles/seed`, which backfills atomically the same way.+--+-- Idempotent: every statement is ON CONFLICT-aware; re-running changes+-- nothing. Reversible: the rollback block at the bottom, documented in+-- docs/roles-and-permissions.md. No secrets, ever — this file contains only+-- role/permission vocabulary.++BEGIN;++-- ─── Permission catalog (platform-wide) ─────────────────────────────────────+-- Names are the strings the routes actually enforce (`require_permission`).+-- The spec aliases (`users:manage`, `investigation:run`, ...) are seeded+-- alongside so the catalog answers the product's vocabulary too; enforcement+-- reads the canonical names. `*` is a real row: the admin role's grant, so+-- the screen can show what it actually confers instead of a footnote.+INSERT INTO permissions (name, description, category) VALUES+ -- alerts+ ('alerts:read', 'View alerts', 'alerts'),+ ('alerts:write', 'Acknowledge / triage / update alerts', 'alerts'),+ ('alerts:delete', 'Delete alerts', 'alerts'),+ -- cases+ ('cases:read', 'View cases', 'cases'),+ ('cases:write', 'Create and edit cases', 'cases'),+ ('cases:delete', 'Delete cases', 'cases'),+ ('cases:assign', 'Assign cases to people', 'cases'),+ ('cases:note', 'Add notes to cases', 'cases'),+ -- detections / rules+ ('detections:read', 'View detections', 'detections'),+ ('detections:write', 'Manage detections', 'detections'),+ ('detections:delete', 'Delete detections', 'detections'),+ ('rules:read', 'View detection rules', 'rules'),+ ('rules:write', 'Create and edit detection rules', 'rules'),+ -- dashboards / reports / compliance+ ('dashboards:read', 'View dashboards', 'dashboards'),+ ('reports:read', 'View reports', 'reports'),+ ('reports:write', 'Generate and edit reports', 'reports'),+ ('reports:export', 'Export reports', 'reports'),+ ('compliance:read', 'View compliance posture', 'compliance'),+ -- playbooks / actions / investigation+ ('playbooks:read', 'View playbooks', 'playbooks'),+ ('playbooks:write', 'Edit playbooks', 'playbooks'),+ ('playbooks:execute', 'Run playbooks', 'playbooks'),+ ('actions:read', 'View the response-action registry', 'actions'),+ ('actions:execute', 'Execute response actions', 'actions'),+ ('investigation:run', 'Run an investigation', 'investigations'),+ -- threat intel+ ('threat_intel:read', 'View threat intelligence', 'threat_intel'),+ ('threat_intel:write', 'Manage threat intelligence', 'threat_intel'),+ ('threatintel:manage', 'Manage threat intelligence (alias)', 'threat_intel'),+ -- connectors / lake / hunts / knowledge+ ('connectors:read', 'View connectors', 'connectors'),+ ('connectors:write', 'Configure connectors', 'connectors'),+ ('connectors:delete', 'Delete connectors', 'connectors'),+ ('lake:query', 'Query the data lake', 'lake'),+ ('lake:read_schema', 'Read the lake schema', 'lake'),+ ('hunts:read', 'View hunts', 'hunts'),+ ('knowledge_base:read', 'Search the knowledge base', 'knowledge_base'),+ ('graph:read', 'View the investigation graph', 'graph'),+ -- users / roles / tenant / settings / api keys / audit+ ('users:read', 'View users', 'admin'),+ ('users:write', 'Create, edit and role-manage users', 'admin'),+ ('users:delete', 'Delete users', 'admin'),+ ('users:manage', 'Manage users (alias)', 'admin'),+ ('roles:read', 'View roles and permissions', 'admin'),+ ('roles:write', 'Create, edit and delete roles', 'admin'),+ ('roles:assign', 'Assign roles to users (alias)', 'admin'),+ ('tenant:read', 'View tenant settings', 'admin'),+ ('tenant:write', 'Change tenant settings', 'admin'),+ ('settings:read', 'Read settings', 'admin'),+ ('settings:write', 'Change settings', 'admin'),+ ('settings:manage', 'Manage settings (alias)', 'admin'),+ ('sso:configure', 'Configure SSO connections', 'admin'),+ ('api_keys:read', 'View API keys', 'api_keys'),+ ('api_keys:write', 'Create and revoke API keys', 'api_keys'),+ ('api_keys:delete', 'Delete API keys', 'api_keys'),+ ('apikeys:manage', 'Manage API keys (alias)', 'api_keys'),+ ('audit_log:read', 'Read the audit log', 'audit'),+ ('audit:read', 'Read the audit log (alias)', 'audit'),+ -- sla / plugins / system+ ('sla:read', 'View SLA metrics', 'sla'),+ ('sla:write', 'Change SLA policy', 'sla'),+ ('plugins:read', 'View plugins', 'plugins'),+ ('plugins:admin', 'Administer plugins', 'plugins'),+ ('plugins:execute', 'Execute plugins', 'plugins'),+ ('*', 'Every permission (wildcard; admin role)', 'system')+ON CONFLICT (name) DO UPDATE+ SET description = EXCLUDED.description,+ category = EXCLUDED.category;++-- ─── Role catalog (tenant-scoped) ───────────────────────────────────────────+-- The three product roles. `is_system = TRUE` keeps them out of the+-- edit/delete paths (`update_role` / `delete_role` refuse system roles),+-- so `viewer` — the SSO default — is non-deletable by construction.+WITH seed_roles(name, description) AS (+ VALUES+ ('viewer', 'Regular User. View-only. The default role for SSO just-in-time provisioning.'),+ ('infosec', 'Infosec analyst / incident handler. Investigates, triages and responds; manages no users, roles, SSO or settings.'),+ ('admin', 'Platform administrator. Full control of this tenant, including users, roles, SSO configuration and the audit log.')+)+INSERT INTO roles (tenant_id, name, description, is_system)+SELECT '00000000-0000-0000-0000-000000000001'::uuid, r.name, r.description, TRUE+ FROM seed_roles r+ON CONFLICT (tenant_id, name) DO UPDATE+ SET description = EXCLUDED.description;++-- ─── Role → permission grants ────────────────────────────────────────────────+-- Deny-by-default: a permission NOT granted here is denied once the tenant+-- is on database-backed RBAC. The sets mirror `ROLE_PERMISSIONS` in+-- app/core/security.py (the static bootstrap map) so the flip to the+-- database changes nothing about what any of the three roles can do.+INSERT INTO role_permissions (role_id, permission_id)+SELECT r.id, p.id+ FROM roles r+ JOIN permissions p ON (+ (r.name = 'viewer' AND p.name IN (+ 'alerts:read',+ 'cases:read',+ 'dashboards:read',+ 'detections:read',+ 'reports:read',+ 'connectors:read',+ 'threat_intel:read',+ 'actions:read',+ 'knowledge_base:read'+ ))+ OR (r.name = 'infosec' AND p.name IN (+ -- everything viewer holds...+ 'alerts:read', 'cases:read', 'dashboards:read', 'detections:read',+ 'reports:read', 'connectors:read', 'threat_intel:read',+ 'actions:read', 'knowledge_base:read',+ -- ...plus the analyst/hunter working set (mirrors+ -- ROLE_PERMISSIONS["infosec"]: analyst | hunter, minus management)+ 'alerts:write',+ 'cases:write', 'cases:assign', 'cases:note',+ 'playbooks:read', 'playbooks:execute',+ 'threat_intel:write', 'threatintel:manage',+ 'rules:read', 'rules:write',+ 'detections:write',+ 'hunts:read', 'lake:query', 'lake:read_schema',+ 'graph:read',+ 'actions:execute',+ 'investigation:run',+ 'reports:write', 'reports:export'+ ))+ OR (r.name = 'admin' AND p.name = '*')+ )+ WHERE r.tenant_id = '00000000-0000-0000-0000-000000000001'::uuid+ON CONFLICT DO NOTHING;++-- ─── Membership backfill (same transaction as the grants, see header) ──────+-- 1. Users whose `users.role` names a seeded role get that catalog row.+-- 2. Anybody else in the tenant gets `viewer`, so nobody wakes up with zero+-- permissions because the tenant just switched to database-backed RBAC.+-- `assigned_by` stays NULL: NULL means "system-seeded, not an operator+-- decision" — the rollback block uses exactly that to identify its rows,+-- and operator/console assignments always carry an actor id.+INSERT INTO user_roles (user_id, role_id)+SELECT u.id, r.id+ FROM users u+ JOIN roles r ON r.tenant_id = u.tenant_id AND r.name = u.role+ WHERE r.is_system = TRUE+ON CONFLICT DO NOTHING;++INSERT INTO user_roles (user_id, role_id)+SELECT u.id, vr.id+ FROM users u+ JOIN roles vr ON vr.tenant_id = u.tenant_id AND vr.name = 'viewer' AND vr.is_system = TRUE+ WHERE u.tenant_id = '00000000-0000-0000-0000-000000000001'::uuid+ AND NOT EXISTS (SELECT 1 FROM user_roles ur WHERE ur.user_id = u.id)+ON CONFLICT DO NOTHING;++COMMIT;++-- ─── Rollback (manual; run inside one transaction) ───────────────────────────+-- Deletes only what this file seeded, identified by `assigned_by IS NULL`+-- on system-role rows. Console/provisioning assignments carry an actor id+-- or re-sync on the next SSO sign-in, so nobody is stranded either way.+-- Deleting the `roles` rows flips the tenant back to the static-map+-- bootstrap, which is exactly the pre-092 behaviour.+--+-- BEGIN;+-- DELETE FROM user_roles WHERE assigned_by IS NULL+-- AND role_id IN (SELECT id FROM roles+-- WHERE tenant_id = '00000000-0000-0000-0000-000000000001'::uuid+-- AND name IN ('viewer','infosec','admin') AND is_system = TRUE);+-- DELETE FROM role_permissions WHERE role_id IN (SELECT id FROM roles+-- WHERE tenant_id = '00000000-0000-0000-0000-000000000001'::uuid+-- AND name IN ('viewer','infosec','admin') AND is_system = TRUE);+-- DELETE FROM roles WHERE tenant_id = '00000000-0000-0000-0000-000000000001'::uuid+-- AND name IN ('viewer','infosec','admin') AND is_system = TRUE;+-- COMMIT;+--+-- The permission rows are platform-wide, additive, and confer nothing on+-- their own; they are left in place. Delete them only if you intend to+-- remove the vocabulary from every tenant at once.diff --git a/services/api/migrations/093_role_label_and_repair.sql b/services/api/migrations/093_role_label_and_repair.sqlnew file mode 100644index 000000000..666058916--- /dev/null+++ b/services/api/migrations/093_role_label_and_repair.sql@@ -0,0 +1,47 @@+-- 093: roles.label column + backfill, orphan-role cleanup, NULL-role repair.+--+-- Adds the human `label` to roles (name stays the machine slug, immutable+-- at the API layer), gives the three system roles their display labels, and+-- reports/backfills data repair:+-- * users whose `role` names no catalog row (e.g. legacy `soc_lead`) are+-- moved to the SSO default `viewer` and reported by the SELECT below+-- (row count = users repaired).+-- * role_permissions rows pointing at permissions outside the platform+-- vocabulary cannot exist (FK to permissions), so nothing to clean; the+-- statement below documents the check that was run.+-- Idempotent: ADD COLUMN IF NOT EXISTS, COALESCE backfills, UPDATE only+-- touches rows that still need repair. Re-run is a no-op.++BEGIN;++ALTER TABLE roles ADD COLUMN IF NOT EXISTS label text;++UPDATE roles SET label = CASE name+ WHEN 'viewer' THEN 'Regular User'+ WHEN 'infosec' THEN 'Infosec Analyst'+ WHEN 'admin' THEN 'Platform Administrator'+ ELSE name+ END+ WHERE label IS NULL OR label = '';++-- Repair users pointing at a role the catalog never had (reported: these+-- are exactly the rows this UPDATE changes).+UPDATE users u SET role = 'viewer', updated_at = now()+ FROM tenants t+ WHERE t.id = u.tenant_id+ AND NOT EXISTS (+ SELECT 1 FROM roles r+ WHERE r.tenant_id = u.tenant_id AND r.name = u.role);++-- Stale-permission check (documented; FK guarantees zero rows, run as a+-- guard for hand-edited databases):+DELETE FROM role_permissions rp+ WHERE NOT EXISTS (SELECT 1 FROM permissions p WHERE p.id = rp.permission_id);++COMMIT;++-- Rollback:+-- BEGIN;+-- ALTER TABLE roles DROP COLUMN IF EXISTS label;+-- COMMIT;+-- (label is presentation-only; dropping it cannot change authorization.)diff --git a/services/api/migrations/094_user_delete_fk.sql b/services/api/migrations/094_user_delete_fk.sqlnew file mode 100644index 000000000..4a13a89cb--- /dev/null+++ b/services/api/migrations/094_user_delete_fk.sql@@ -0,0 +1,19 @@+-- 094: make a user row deletable.+--+-- Every FK referencing users already cascades (ownership rows) or SET NULLs+-- (attribution rows) EXCEPT compliance_evidence.collected_by, which RESTRICTs+-- (NO ACTION). That single edge would FK-fail any DELETE of a user who ever+-- collected compliance evidence. A compliance artifact must outlive its+-- collector, and the column is nullable, so the attribution survives as+-- "unknown collector" instead of blocking the row deletion — the same+-- retention model every other actor column already uses (audit_log.actor_id+-- SET NULL keeps the audit trail intact; only the name attribution goes).+--+-- Idempotent: re-running is a no-op once the constraint is recreated.++ALTER TABLE compliance_evidence+ DROP CONSTRAINT IF EXISTS compliance_evidence_collected_by_fkey;++ALTER TABLE compliance_evidence+ ADD CONSTRAINT compliance_evidence_collected_by_fkey+ FOREIGN KEY (collected_by) REFERENCES users(id) ON DELETE SET NULL;diff --git a/services/api/tests/test_alert_investigate_bump.py b/services/api/tests/test_alert_investigate_bump.pynew file mode 100644index 000000000..c85659b73--- /dev/null+++ b/services/api/tests/test_alert_investigate_bump.py@@ -0,0 +1,69 @@+"""Alert status advance on investigation launch (alert half of the ladder fix).++Launching an agent investigation from an alert must mark the alert itself+'investigating' - not only the case. The UPDATE's status guard is the+contract tested here: forward-only from the open states, never backwards.+Source-contract tests because the bump lives inline in investigate_case+(same-request, never-blocks-the-launch semantics).+"""++import re+from pathlib import Path++import pytest++CASES = Path(__file__).resolve().parents[1] / "app" / "api" / "v1" / "endpoints" / "cases.py"++SOURCE = CASES.read_text()+++def _bump_sql() -> str:+ m = re.search(+ r"UPDATE alerts SET status = 'investigating'.*?AND status IN \(([^)]*)\)",+ SOURCE,+ re.DOTALL,+ )+ assert m, "alerts investigate bump missing from cases.py"+ return m.group(0)+++def _open_statuses() -> set[str]:+ m = re.search(r"AND status IN \(([^)]*)\)", _bump_sql())+ assert m, "status IN clause missing from bump SQL"+ raw = m.group(1)+ if "{" in raw:+ # The guard expands from the pinned tuple via .format() — resolve it+ # from the source rather than parsing the placeholder text.+ t = re.search(r"_ALERT_OPEN_STATUSES[^=]*=\s*\(([^)]*)\)", SOURCE)+ assert t, "_ALERT_OPEN_STATUSES tuple missing from cases.py"+ raw = t.group(1)+ return {s.strip().strip("'\"") for s in raw.split(",") if s.strip()}+++def test_alert_bump_is_tenant_scoped() -> None:+ assert "tenant_id = :tenant_id" in _bump_sql()+++def test_alert_bump_never_blocks_launch() -> None:+ idx = SOURCE.index("UPDATE alerts SET status = 'investigating'")+ tail = SOURCE[idx : idx + 1200]+ assert "except Exception" in tail+ assert "investigate.launch.alerts_advance_failed" in tail+++ ("current", "advances"),+ [+ ("new", True),+ ("triaged", True),+ ("triaging", True),+ ("investigating", False),+ ("in_progress", False),+ ("resolved", False),+ ("false_positive", False),+ ("closed", False),+ ],+)+def test_bump_predicate_matrix(current: str, advances: bool) -> None:+ """Mirror of the WHERE guard: membership in the open set decides."""+ assert (current in _open_statuses()) is advancesdiff --git a/services/api/tests/test_rbac_catalog_seed.py b/services/api/tests/test_rbac_catalog_seed.pynew file mode 100644index 000000000..d09a3a1a6--- /dev/null+++ b/services/api/tests/test_rbac_catalog_seed.py@@ -0,0 +1,86 @@+"""Pin the seeded RBAC catalog: migration 092 and rbac_catalog.py agree.++``app.core.rbac_catalog`` and ``migrations/092_rbac_catalog_seed.sql`` carry+the same role/permission vocabulary in two places by design (the migration+seeds the primary tenant at deploy time; the module seeds other tenants at+runtime). This test is the pin that stops them drifting: the permission+names, the system role names, and every role→grant set must match exactly.++Static-only test — no database, no FastAPI app. Runs under plain pytest.+"""++from __future__ import annotations++import re+from pathlib import Path++from app.core.rbac_catalog import (+ PERMISSIONS,+ ROLE_GRANTS,+ SYSTEM_ROLE_LABELS,+ SYSTEM_ROLES,+)++MIGRATION = Path(__file__).resolve().parents[1] / "migrations" / "092_rbac_catalog_seed.sql"+++def _migration_sql() -> str:+ return MIGRATION.read_text(encoding="utf-8")+++def test_migration_exists() -> None:+ assert MIGRATION.exists(), f"missing migration: {MIGRATION}"+++def _migration_permission_rows(sql: str) -> set[str]:+ """Names from the `INSERT INTO permissions ... VALUES (...)` block —+ the first element of each ('name', 'description', 'category') tuple."""+ block = sql.split("INSERT INTO permissions", 1)[1].split(";", 1)[0]+ return set(re.findall(r"\(\s*'([^']+)'\s*,", block))+++def test_permission_names_pinned() -> None:+ """The permission rows the migration inserts must exactly equal the+ module's PERMISSIONS vocabulary."""+ sql = _migration_sql()+ in_migration = _migration_permission_rows(sql)+ in_module = {name for name, _desc, _cat in PERMISSIONS}+ assert in_migration == in_module, (+ f"permission vocabulary drifted; only-in-migration={sorted(in_migration - in_module)}, "+ f"only-in-module={sorted(in_module - in_migration)}"+ )+++def test_system_role_names_pinned() -> None:+ sql = _migration_sql()+ module_roles = {name for name, _desc in SYSTEM_ROLES}+ assert {"viewer", "infosec", "admin"} == module_roles+ for role in module_roles:+ assert re.search(rf"r\.name\s*=\s*'{role}'", sql) or f"'{role}'" in sql, f"role '{role}' not referenced in migration 092"+++def test_role_grants_pinned() -> None:+ """The migration's inline viewer/infosec IN-lists must equal the+ module's ROLE_GRANTS sets; admin is the wildcard in both."""+ sql = _migration_sql()+ assert ROLE_GRANTS["admin"] == frozenset({"*"}), "admin wildcard grant drifted"+ assert "'admin' AND p.name = '*'" in sql, "migration no longer grants admin the wildcard"++ for role in ("viewer", "infosec"):+ block = re.search(+ rf"r\.name\s*=\s*'{role}'\s+AND\s+p\.name\s+IN\s*\((.*?)\)\s*\)",+ sql,+ re.DOTALL,+ )+ assert block, f"could not locate the grant IN-list for role '{role}' in 092"+ in_migration = set(re.findall(r"'([a-z_]+:[a-z_]+|\*)'", block.group(1)))+ in_module = set(ROLE_GRANTS[role])+ assert in_migration == in_module, (+ f"grants drifted for role '{role}': "+ f"only-in-migration={sorted(in_migration - in_module)}, "+ f"only-in-module={sorted(in_module - in_migration)}"+ )+++def test_labels_pinned() -> None:+ assert set(SYSTEM_ROLE_LABELS) == {name for name, _desc in SYSTEM_ROLES}diff --git a/services/api/tests/test_role_grant_effective_permissions.py b/services/api/tests/test_role_grant_effective_permissions.pyindex 6f946cad2..b4f96100e 100644--- a/services/api/tests/test_role_grant_effective_permissions.py+++ b/services/api/tests/test_role_grant_effective_permissions.py@@ -42,6 +42,14 @@ from app.api.v1.endpoints import rbac as rbac_modfrom app.api.v1.endpoints import tenants as tenants_modfrom fastapi import HTTPException++def _http_request(method: str = "POST", path: str = "/api/v1/rbac/roles"):+ """Minimal starlette Request for direct handler calls in tests."""+ from starlette.requests import Request++ return Request({"type": "http", "method": method, "path": path, "headers": [], "query_string": b""})++TENANT = uuid.uuid4()pytestmark = pytest.mark.anyio@@ -294,6 +302,7 @@ class TestRoleAuthoring:with pytest.raises(HTTPException) as exc:await rbac_mod.create_role(+ request=_http_request(),body=rbac_mod.RoleIn(name="playbook-ops", permission_ids=[perm.id]),current_user=caller,db=db,@@ -311,6 +320,7 @@ class TestRoleAuthoring:with pytest.raises(HTTPException) as exc:await rbac_mod.update_role(+ request=_http_request(),role_id=role.id,body=rbac_mod.RoleUpdate(permission_ids=[perm.id]),current_user=caller,diff --git a/services/api/tests/test_role_grant_scope.py b/services/api/tests/test_role_grant_scope.pyindex 7d9844f46..88c90723a 100644--- a/services/api/tests/test_role_grant_scope.py+++ b/services/api/tests/test_role_grant_scope.py@@ -47,6 +47,14 @@ from app.api.v1.endpoints import rbac as rbac_modfrom app.api.v1.endpoints import tenants as tenants_modfrom fastapi import HTTPException++def _http_request(method: str = "POST", path: str = "/api/v1/rbac/roles"):+ """Minimal starlette Request for direct handler calls in tests."""+ from starlette.requests import Request++ return Request({"type": "http", "method": method, "path": path, "headers": [], "query_string": b""})++TENANT = uuid.uuid4()pytestmark = pytest.mark.anyio@@ -438,6 +446,7 @@ class TestRbacRoleAssignment:with pytest.raises(HTTPException) as exc:await rbac_mod.create_role(+ request=_http_request(),body=rbac_mod.RoleIn(name="plugin-ops", permission_ids=[perm.id]),current_user=_principal("tenant_admin"),db=db,diff --git a/services/enrichment/go.mod b/services/enrichment/go.modindex 77a76a20b..1f3fcfc20 100644--- a/services/enrichment/go.mod+++ b/services/enrichment/go.mod@@ -14,5 +14,5 @@ require (github.com/mattn/go-colorable v0.1.14 // indirectgithub.com/mattn/go-isatty v0.0.20 // indirectgo.uber.org/atomic v1.11.0 // indirect- golang.org/x/sys v0.30.0 // indirect+ golang.org/x/sys v0.44.0 // indirect)diff --git a/services/enrichment/go.sum b/services/enrichment/go.sumindex 8eb3d06ca..fc21fd41e 100644--- a/services/enrichment/go.sum+++ b/services/enrichment/go.sum@@ -31,3 +31,5 @@ go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=+golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=diff --git a/services/mcp/cursor-extension/package-lock.json b/services/mcp/cursor-extension/package-lock.jsonindex 3ed94b6d6..2d713464e 100644--- a/services/mcp/cursor-extension/package-lock.json+++ b/services/mcp/cursor-extension/package-lock.json@@ -145,9 +145,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -165,9 +162,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -185,9 +179,6 @@"ppc64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -205,9 +196,6 @@"s390x"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -225,9 +213,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -245,9 +230,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -717,9 +699,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -741,9 +720,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -765,9 +741,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -789,9 +762,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [diff --git a/services/osquery-extensions/go.mod b/services/osquery-extensions/go.modindex 22e453464..f90764d5e 100644--- a/services/osquery-extensions/go.mod+++ b/services/osquery-extensions/go.mod@@ -13,5 +13,5 @@ require (go.opentelemetry.io/otel v1.16.0 // indirectgo.opentelemetry.io/otel/metric v1.16.0 // indirectgo.opentelemetry.io/otel/trace v1.16.0 // indirect- golang.org/x/sys v0.25.0 // indirect+ golang.org/x/sys v0.44.0 // indirect)diff --git a/services/osquery-extensions/go.sum b/services/osquery-extensions/go.sumindex d10cf6e3b..95ecd7881 100644--- a/services/osquery-extensions/go.sum+++ b/services/osquery-extensions/go.sum@@ -27,5 +27,7 @@ go.opentelemetry.io/otel/trace v1.16.0 h1:8JRpaObFoW0pxuVPapkgH8UhHQj+bJW8jJsCZEgo.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0=golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=+golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/services/slack-bot/poetry.lock b/services/slack-bot/poetry.lockindex 0ebf6accf..a26322049 100644--- a/services/slack-bot/poetry.lock+++ b/services/slack-bot/poetry.lock@@ -1,4 +1,4 @@-# This file is automatically @generated by Poetry 2.4.1 and should not be changed by hand.+# This file is automatically @generated by Poetry 2.5.1 and should not be changed by hand.[[package]]name = "aiohappyeyeballs"@@ -1583,7 +1583,7 @@ h11 = ">=0.8"httptools = {version = ">=0.5.0", optional = true, markers = "extra == \"standard\""}python-dotenv = {version = ">=0.13", optional = true, markers = "extra == \"standard\""}pyyaml = {version = ">=5.1", optional = true, markers = "extra == \"standard\""}-uvloop = {version = ">=0.14.0,<0.15.0 || >0.15.0,<0.15.1 || >0.15.1", optional = true, markers = "sys_platform != \"win32\" and sys_platform != \"cygwin\" and platform_python_implementation != \"PyPy\" and extra == \"standard\""}+uvloop = {version = ">=0.14.0,!=0.15.0,!=0.15.1", optional = true, markers = "sys_platform != \"win32\" and sys_platform != \"cygwin\" and platform_python_implementation != \"PyPy\" and extra == \"standard\""}watchfiles = {version = ">=0.13", optional = true, markers = "extra == \"standard\""}websockets = {version = ">=10.4", optional = true, markers = "extra == \"standard\""}