Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Limit the default organization in multi-org mode
rcourtmanf37c1025350a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 1f19cde52f..08e0037b24 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -10988,3 +10988,11 @@ replacement. Session withdrawal does not cancel independent agents, updates,deployments, backups or legacy executions, nor prove original recovery.`TestContractSessionReadLogoutBoundary` covers persisted logout and nativeHTTP/WS refusal; the API contract describes the credential and idle boundaries.++### Agent event streams follow organization access++`/api/agent/events` for a signed-in user now also re-checks the organization+access policy, so a user who loses default-organization membership or+instance administration stops receiving findings and approval events within+10 seconds. Token streams keep their existing credential and binding checks.+Agent enrollment, reports and command channels are unchanged.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 22be03f5d2..440e2139c4 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -13723,3 +13723,18 @@ earlier raw object; that current-read object remains usable for the same liveID. A later full read, context withdrawal or deletion invalidates the oldconfirmation. The registered sequential scope-edit/revoke consumer regressionand earlier-read rejection test cover both sides without ID-only admission.++### Default-organization access policy++`DefaultAuthorizationChecker.CheckAccessContext` is the one organization+access policy for tenant selection, action authority, organization handlers,+the WebSocket hub and long-lived reads. In shared-process multi-organization+mode a signed-in user reaches the default organization only as an instance+administrator (local admin, RBAC admin grant evaluated with inheritance and+deny precedence, or a proxy principal admitted with the admin role) or as an+explicit default member. A request that names no organization lands in the+user's first organization, and `resolveTenantOrgID` returns the authorized+organization so handlers agree with that decision. Other refusals of the+default organization answer `default_org_access_denied`; the browser client+clears that stale selection and retries reads only. WebSocket and SSE reads+re-check the policy every 10 seconds. API-token bindings are unchanged.diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 7e28e5651a..b60baa9288 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -3982,3 +3982,12 @@ withhold saved links until the read succeeds. It is not erasure of every copyalready held elsewhere, live IdP or original administrator recovery. Registeredmetadata-lifetime, Workloads consumer and runtime tests cover the boundaries;desktop/narrow browser proof must exercise the actual platform consumer.++### Organization bootstrap without default access++Hosted runtimes keep the open default organization; this only changes+self-hosted multi-organization mode. There, browser bootstrap recovers from a+refused default selection by clearing it and retrying reads, and a user with no+usable organization gets the invitation screen instead of a connection+failure. Hosted tenant selection, subscription gating and paid capabilities+are unchanged.diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.mdindex a755548a80..1fed0220c0 100644--- a/docs/release-control/v6/internal/subsystems/organization-settings.md+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md@@ -695,3 +695,18 @@ Registered `ReportingPanel.reader.test.tsx`, `useReportingPanelState.test.ts`,late body completion, same-reader refresh, refused-save retry, malformed inventory,confirmation, route props and existing reporting/delivery behaviour. Actual AppSettings/API-client/browser proof remains required for the consuming surface.++### Default organization in shared-process multi-organization mode++With `PULSE_MULTI_TENANT_ENABLED=true` on a self-hosted (not hosted) runtime,+the default organization is open only to instance administrators and to+explicit members in its `org.json`, loaded strictly. Other signed-in users no+longer reach it by header, cookie or socket. Instance administrators manage+its members from Organization access: an add takes effect at once, members+are viewers, and membership never grants organization management. The first+start in this mode seeds RBAC-assigned users who belong to no other+organization and records `default-org-access-migration.json`. A signed-in+user with no usable organization sees their pending invitations at bootstrap.+Single-tenant and hosted runtimes keep the open default organization.+`TestOrgHandlers_DefaultOrgMembersInSharedMultiOrgMode` and the+`org_access_policy_test.go` suite cover these rules.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex a6df4a2da9..cefb3676cc 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -4271,3 +4271,14 @@ Registered `ReportingPanel.reader.test.tsx`, `useReportingPanelState.test.ts`,late body completion, same-reader refresh, refused-save retry, malformed inventory,confirmation, route props and existing reporting/delivery behaviour. Actual AppSettings/API-client/browser proof remains required for the consuming surface.++### Default-organization access in multi-organization mode++`internal/api/router.go` now builds one organization access policy and hands it+to tenant selection, action authority, the organization handlers and the+WebSocket hub. In self-hosted multi-organization mode the default organization+admits only instance administrators (local admin, an RBAC admin grant that+honours inheritance and deny precedence, or a proxy user admitted with the+admin role, bound to that username) and explicit members of its strictly+loaded `org.json`. Live WebSocket, SSE and agent-event reads re-check the+policy every 10 seconds. API-token bindings are unchanged.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex c59d327075..06064b310e 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -9485,3 +9485,11 @@ replacement. Session withdrawal does not cancel independent agents, updates,deployments, backups or legacy executions, nor prove original recovery.`TestContractSessionReadLogoutBoundary` covers persisted logout and nativeHTTP/WS refusal; the API contract describes the credential and idle boundaries.++### Default-organization access policy is not a storage path++The default-organization access change in `internal/api/` adds no storage or+recovery path beyond default-organization membership in the existing+`org.json` and a one-time marker, `default-org-access-migration.json`, in the+base data directory. The migration writes nothing when tenant metadata or RBAC+assignments cannot be read, so recovery of those stores is unchanged.diff --git a/frontend-modern/browser-verification/7e3ad72adc85c091.json b/frontend-modern/browser-verification/7e3ad72adc85c091.jsonnew file mode 100644index 0000000000..f79ad78036--- /dev/null+++ b/frontend-modern/browser-verification/7e3ad72adc85c091.json@@ -0,0 +1,59 @@+{+ "version": 1,+ "base_sha": "02dbae7b6cab82ca8eb361911b564bbcd92bdb2c",+ "verified_at": "2026-11-03T15:56:30Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/api/orgs.ts",+ "frontend-modern/src/components/AppBootstrapStatus.tsx",+ "frontend-modern/src/components/NoOrganizationAccess.tsx",+ "frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx",+ "frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx",+ "frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts",+ "frontend-modern/src/stores/organizationAccessBootstrap.ts",+ "frontend-modern/src/utils/apiClient.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/api/orgs.ts": "cac8ceea932563f16e91c2cfc67c412cb029c9950ea827043663fd3335077031",+ "frontend-modern/src/components/AppBootstrapStatus.tsx": "b81c75ccc789bf1dea66f2a9b8ed0082ae7ee067ff2d9044168d34fd05ac27c0",+ "frontend-modern/src/components/NoOrganizationAccess.tsx": "fbacac743066e6a595d7f45ec087293da40fe27dc4a7be69b048868ee46d8514",+ "frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx": "540dd5fcadf8917097f086b24296036db9f8dbf8d9ab4a6cb9af7255484970cb",+ "frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx": "0ac41c35bc8e40cf1468995cd70c556ba3cc5f0db8188894e19ecc4c485715c9",+ "frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts": "24dbaac47b70a58d5202378dcc07704d5594a33995c2463243d35aeabf9f50aa",+ "frontend-modern/src/stores/organizationAccessBootstrap.ts": "b321ed0f7bffa304b2866b7accf8d30983fc9e7234a265216a39e1fbe62b305e",+ "frontend-modern/src/utils/apiClient.ts": "097df9a93714ba1aed3b610cb63ffd9f354138c68adeecc2fe92dfaa725581f5"+ },+ "routes": [+ "/settings/organization/access",+ "/proxmox/overview",+ "/"+ ],+ "viewports": [+ {+ "width": 1440,+ "height": 1000+ },+ {+ "width": 375,+ "height": 812+ }+ ],+ "states": [+ "branch fix/default-org-access applied to origin/main 02dbae7b6c, built with npm run build and go build ./cmd/pulse on pulse-dev",+ "mock mode, PULSE_MULTI_TENANT_ENABLED=true, proxy authentication with a role header; org acme owned by alice with member bob and a pending invitation for carol",+ "three proxy identities on separate hostnames: rcadmin with the admin role, bob and carol with viewer roles",+ "rig proxy added multi_tenant to /api/license/runtime-capabilities, which a dev build without a license omits; backend checks were unmodified",+ "dark theme, desktop and phone layouts"+ ],+ "interactions": [+ "rcadmin opened Settings > Organization > Access for the default organization: Add Member form with a Viewer-only role, no role picker on member rows",+ "rcadmin added dave: toast \"Added dave as viewer.\", row listed as viewer; removed dave with Remove and the row disappeared",+ "bob opened / with no org selection and landed in Acme; the org chip showed only Acme, no default organization",+ "bob with a stale pulse_org_id=default cookie and session selection reloaded: /api/state/summary returned 403 default_org_access_denied, the client cleared the selection, the retry returned 200 and the app stayed in Acme",+ "carol, invited but not a member, saw \"No organization access yet\" with her Acme invitation, Accept, Decline, Check again and Sign out, at 1440x1000 and 375x812 with no horizontal overflow",+ "after the bootstrap failed, AppBootstrapStatus probed /api/state/summary, saw default_org_access_denied and showed the invitation screen instead of the connection error",+ "carol clicked Sign out: POST /api/logout returned 200 and the page returned to /; the rig has no proxy logout URL, so the proxy signed her straight back in to the same screen",+ "carol clicked Accept at 375x812: POST /api/org-invitations/acme/accept returned 200, the app reloaded and, after the Acme tenant runtime cold-started, opened the Acme overview",+ "found and fixed during the pass: GET /api/orgs/{id}/invitations returned null for an organization with no pending invitations, which the access panel rejected"+ ]+}diff --git a/frontend-modern/src/api/__tests__/orgs.test.ts b/frontend-modern/src/api/__tests__/orgs.test.tsindex c8d2963e24..8f3b727f5e 100644--- a/frontend-modern/src/api/__tests__/orgs.test.ts+++ b/frontend-modern/src/api/__tests__/orgs.test.ts@@ -354,4 +354,35 @@ describe('OrgsAPI', () => {);});});++ describe('default organization members', () => {+ it('keeps the server-reported member management capability', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ id: 'default',+ displayName: 'default',+ canManageMembers: true,+ });++ const result = await OrgsAPI.get('default');++ expect(result.canManageMembers).toBe(true);+ });++ it('adds a default organization member through the members route', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ kind: 'member',+ member: { userId: 'bob', role: 'viewer' },+ });++ await OrgsAPI.inviteMember('default', { userId: 'bob', role: 'viewer' });++ expect(apiFetchJSON).toHaveBeenCalledWith(+ '/api/orgs/default/members',+ expect.objectContaining({+ method: 'POST',+ body: JSON.stringify({ userId: 'bob', role: 'viewer' }),+ }),+ );+ });+ });});diff --git a/frontend-modern/src/api/orgs.ts b/frontend-modern/src/api/orgs.tsindex 8a1f2f781d..fb9a810ca6 100644--- a/frontend-modern/src/api/orgs.ts+++ b/frontend-modern/src/api/orgs.ts@@ -40,6 +40,8 @@ export interface Organization {createdAt?: string;ownerUserId?: string;members?: OrganizationMember[];+ /** Set on the default organization when the caller may change its members. */+ canManageMembers?: boolean;}export interface OrganizationShare {diff --git a/frontend-modern/src/components/AppBootstrapStatus.tsx b/frontend-modern/src/components/AppBootstrapStatus.tsxindex 9ac6b0a19f..797157b074 100644--- a/frontend-modern/src/components/AppBootstrapStatus.tsx+++ b/frontend-modern/src/components/AppBootstrapStatus.tsx@@ -1,6 +1,11 @@-import { Show, createSignal, onCleanup, onMount, type Component } from 'solid-js';+import { Show, createResource, createSignal, onCleanup, onMount, type Component } from 'solid-js';import { Button } from '@/components/shared/Button';import { LoadingSpinner } from '@/components/shared/LoadingSpinner';+import { NoOrganizationAccess } from '@/components/NoOrganizationAccess';+import {+ probeNoOrganizationAccess,+ signOutWithoutOrganization,+} from '@/stores/organizationAccessBootstrap';export const APP_BOOTSTRAP_SLOW_DELAY_MS = 10_000;@@ -12,6 +17,12 @@ interface AppBootstrapStatusProps {export const AppBootstrapStatus: Component<AppBootstrapStatusProps> = (props) => {const [isSlow, setIsSlow] = createSignal(false);+ // A signed-in user with no usable organization is not a connection failure:+ // offer their invitations instead.+ const [noOrganizationAccess] = createResource(+ () => props.failed || undefined,+ probeNoOrganizationAccess,+ );onMount(() => {const timeout = window.setTimeout(@@ -30,50 +41,61 @@ export const AppBootstrapStatus: Component<AppBootstrapStatusProps> = (props) =>};return (- <main- class="flex min-h-screen items-center justify-center px-4 py-8 text-base-content"- aria-labelledby="app-bootstrap-title"+ <Show+ when={props.failed && noOrganizationAccess() === true}+ fallback={renderConnectionStatus()}>- <div class="w-full max-w-md rounded-md border border-border bg-surface p-6 text-center shadow-xs sm:p-8">- <Show when={!props.failed}>- <LoadingSpinner size="xl" tone="info" class="mb-4" />- </Show>- <h1 id="app-bootstrap-title" class="text-lg font-semibold tracking-tight">- {props.failed ? 'Could not check your session' : 'Connecting to Pulse'}- </h1>- <p- class="mt-2 text-sm leading-6 text-muted"- role="status"- aria-live="polite"- aria-atomic="true"- >- <Show- when={props.failed}- fallback={- <Show when={isSlow()} fallback="Checking your session and preparing the workspace.">- Pulse is taking longer than expected to respond. The server may still be starting or- busy.- </Show>- }+ <NoOrganizationAccess onSignOut={signOutWithoutOrganization} />+ </Show>+ );++ function renderConnectionStatus() {+ return (+ <main+ class="flex min-h-screen items-center justify-center px-4 py-8 text-base-content"+ aria-labelledby="app-bootstrap-title"+ >+ <div class="w-full max-w-md rounded-md border border-border bg-surface p-6 text-center shadow-xs sm:p-8">+ <Show when={!props.failed}>+ <LoadingSpinner size="xl" tone="info" class="mb-4" />+ </Show>+ <h1 id="app-bootstrap-title" class="text-lg font-semibold tracking-tight">+ {props.failed ? 'Could not check your session' : 'Connecting to Pulse'}+ </h1>+ <p+ class="mt-2 text-sm leading-6 text-muted"+ role="status"+ aria-live="polite"+ aria-atomic="true">- Pulse could not check your session. Your saved sign-in details have not been cleared.+ <Show+ when={props.failed}+ fallback={+ <Show when={isSlow()} fallback="Checking your session and preparing the workspace.">+ Pulse is taking longer than expected to respond. The server may still be starting+ or busy.+ </Show>+ }+ >+ Pulse could not check your session. Your saved sign-in details have not been cleared.+ </Show>+ </p>+ <Show when={props.failed || isSlow()}>+ <div class="mt-5 border-t border-border pt-5">+ <p class="mb-4 text-sm leading-6 text-muted">+ {props.failed+ ? 'Check that Pulse is available, then retry the connection.'+ : 'You can keep waiting, or retry the connection.'}+ </p>+ <Button variant="primary" size="md" onClick={retry}>+ Retry connection+ </Button>+ </div></Show>- </p>- <Show when={props.failed || isSlow()}>- <div class="mt-5 border-t border-border pt-5">- <p class="mb-4 text-sm leading-6 text-muted">- {props.failed- ? 'Check that Pulse is available, then retry the connection.'- : 'You can keep waiting, or retry the connection.'}- </p>- <Button variant="primary" size="md" onClick={retry}>- Retry connection- </Button>- </div>- </Show>- </div>- </main>- );+ </div>+ </main>+ );+ }};export default AppBootstrapStatus;diff --git a/frontend-modern/src/components/NoOrganizationAccess.tsx b/frontend-modern/src/components/NoOrganizationAccess.tsxnew file mode 100644index 0000000000..bc95ff6239--- /dev/null+++ b/frontend-modern/src/components/NoOrganizationAccess.tsx@@ -0,0 +1,130 @@+import { For, Show, createResource, createSignal, type Component } from 'solid-js';+import { OrgsAPI, type UserOrganizationInvitation } from '@/api/orgs';+import { Button } from '@/components/shared/Button';+import { OrganizationRoleBadge } from '@/components/shared/OrganizationBadges';+import { logger } from '@/utils/logger';+import { normalizeRole } from '@/utils/orgUtils';++interface NoOrganizationAccessProps {+ onSignOut: () => void | Promise<void>;+ /** Reloads the app after an invitation is accepted. */+ onReload?: () => void;+}++/**+ * Shown to a signed-in user who can use no organization yet, typically someone+ * invited to an organization who has not accepted. Accepting an invitation+ * reloads the app into that organization.+ */+export const NoOrganizationAccess: Component<NoOrganizationAccessProps> = (props) => {+ const [invitations, { refetch }] = createResource<UserOrganizationInvitation[]>(async () => {+ try {+ const list = await OrgsAPI.listMyInvitations();+ return Array.isArray(list) ? list : [];+ } catch (error) {+ logger.warn('Failed to load organization invitations', error);+ return [];+ }+ });+ const [busyOrgID, setBusyOrgID] = createSignal<string | null>(null);+ const [actionError, setActionError] = createSignal<string | null>(null);++ const reload = () => (props.onReload ? props.onReload() : window.location.reload());++ const respond = async (orgId: string, accept: boolean) => {+ if (busyOrgID()) return;+ setBusyOrgID(orgId);+ setActionError(null);+ try {+ if (accept) {+ await OrgsAPI.acceptMyInvitation(orgId);+ reload();+ return;+ }+ await OrgsAPI.declineMyInvitation(orgId);+ await refetch();+ } catch (error) {+ logger.warn('Failed to answer organization invitation', error);+ setActionError(+ accept ? 'Could not accept the invitation.' : 'Could not decline the invitation.',+ );+ } finally {+ setBusyOrgID(null);+ }+ };++ return (+ <main+ class="flex min-h-screen items-center justify-center px-4 py-8 text-base-content"+ aria-labelledby="no-organization-access-title"+ >+ <div class="w-full max-w-md rounded-md border border-border bg-surface p-6 shadow-xs sm:p-8">+ <h1 id="no-organization-access-title" class="text-lg font-semibold tracking-tight">+ No organization access yet+ </h1>+ <p class="mt-2 text-sm leading-6 text-muted">+ You are signed in, but you are not a member of an organization on this Pulse server.+ </p>++ <Show when={!invitations.loading}>+ <Show+ when={(invitations() ?? []).length > 0}+ fallback={+ <p class="mt-4 text-sm leading-6 text-muted">+ Ask a Pulse administrator to add you to an organization.+ </p>+ }+ >+ <ul class="mt-4 divide-y divide-border rounded-md border border-border">+ <For each={invitations()}>+ {(invitation) => (+ <li class="flex items-center gap-3 px-3 py-2">+ <span class="min-w-0 flex-1 truncate text-sm">+ {invitation.orgDisplayName || invitation.orgId}+ </span>+ <OrganizationRoleBadge role={normalizeRole(invitation.role)} />+ <Button+ variant="primary"+ size="sm"+ disabled={busyOrgID() !== null}+ onClick={() => void respond(invitation.orgId, true)}+ >+ Accept+ </Button>+ <Button+ variant="secondary"+ size="sm"+ disabled={busyOrgID() !== null}+ onClick={() => void respond(invitation.orgId, false)}+ >+ Decline+ </Button>+ </li>+ )}+ </For>+ </ul>+ </Show>+ </Show>++ <Show when={actionError()}>+ {(message) => (+ <p class="mt-3 text-sm text-red-600 dark:text-red-400" role="alert">+ {message()}+ </p>+ )}+ </Show>++ <div class="mt-5 flex flex-wrap gap-2 border-t border-border pt-5">+ <Button variant="secondary" size="md" onClick={reload}>+ Check again+ </Button>+ <Button variant="ghost" size="md" onClick={() => void props.onSignOut()}>+ Sign out+ </Button>+ </div>+ </div>+ </main>+ );+};++export default NoOrganizationAccess;diff --git a/frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx b/frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsxindex c409a35c77..313d8f179f 100644--- a/frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx+++ b/frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx@@ -1,11 +1,16 @@-import type { OrganizationRole } from '@/api/orgs';+import type { Organization, OrganizationRole } from '@/api/orgs';import { Component, For, Show } from 'solid-js';import { Button } from '@/components/shared/Button';import { FormSelect } from '@/components/shared/FormSelect';import { ORGANIZATION_MEMBER_ROLE_OPTIONS } from '@/utils/organizationRolePresentation';import { getOrganizationAccessManageRequiredMessage } from '@/utils/organizationSettingsPresentation';+import { DEFAULT_ORG_SCOPE } from '@/utils/orgScope';import type { useOrganizationAccessPanelState } from './useOrganizationAccessPanelState';+// Adding someone to the default organization grants access at once, and its+// members are viewers: instance roles decide what they can do.+const isDefaultOrg = (org: Organization) => org.id === DEFAULT_ORG_SCOPE;+interface OrganizationAccessManagementSectionProps {currentUser?: string;state: ReturnType<typeof useOrganizationAccessPanelState>;@@ -19,7 +24,9 @@ export const OrganizationAccessManagementSection: Component<<><Show when={props.state.canManageCurrentOrg()}><div class="rounded-md border border-border p-4 space-y-3">- <h4 class="text-sm font-semibold text-base-content">Invite Member</h4>+ <h4 class="text-sm font-semibold text-base-content">+ {isDefaultOrg(currentOrg()) ? 'Add Member' : 'Invite Member'}+ </h4><div class="grid gap-2 sm:grid-cols-[1fr_auto_auto]"><inputtype="text"@@ -40,9 +47,10 @@ export const OrganizationAccessManagementSection: Component<selectBaseClass="rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500"><For- each={ORGANIZATION_MEMBER_ROLE_OPTIONS.filter(- (option) =>- option.value !== 'owner' || currentOrg().ownerUserId === props.currentUser,+ each={ORGANIZATION_MEMBER_ROLE_OPTIONS.filter((option) =>+ isDefaultOrg(currentOrg())+ ? option.value === 'viewer'+ : option.value !== 'owner' || currentOrg().ownerUserId === props.currentUser,)}>{(option) => <option value={option.value}>{option.label}</option>}@@ -55,7 +63,7 @@ export const OrganizationAccessManagementSection: Component<onClick={props.state.inviteMember}disabled={props.state.saving()}>- {props.state.saving() ? 'Saving...' : 'Invite'}+ {props.state.saving() ? 'Saving...' : isDefaultOrg(currentOrg()) ? 'Add' : 'Invite'}</Button></div></div>diff --git a/frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx b/frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsxindex cf350a8223..535b0f5db1 100644--- a/frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx+++ b/frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx@@ -4,6 +4,7 @@ import { FormSelect } from '@/components/shared/FormSelect';import { OrganizationRoleBadge } from '@/components/shared/OrganizationBadges';import { PulseDataGrid } from '@/components/shared/PulseDataGrid';import { ORGANIZATION_MEMBER_ROLE_OPTIONS } from '@/utils/organizationRolePresentation';+import { DEFAULT_ORG_SCOPE } from '@/utils/orgScope';import { formatOrgDate, normalizeRole } from '@/utils/orgUtils';import { getOrganizationAccessEmptyState } from '@/utils/organizationSettingsPresentation';import Trash2 from 'lucide-solid/icons/trash-2';@@ -37,7 +38,7 @@ export const OrganizationAccessMembersSection: Component<OrganizationAccessMembeconst isOwner = () => member.userId === currentOrg().ownerUserId;return (<Show- when={props.state.canManageCurrentOrg()}+ when={props.state.canManageCurrentOrg() && currentOrg().id !== DEFAULT_ORG_SCOPE}fallback={<OrganizationRoleBadge role={role} />}><FormSelectdiff --git a/frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts b/frontend-modern/src/components/Settings/useOrganizationAccessPanelState.tsindex aca9c9439e..5586d877a6 100644--- a/frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts+++ b/frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts@@ -18,7 +18,7 @@ import {} from '@/stores/sessionPresentationPolicy';import { getOrgID } from '@/utils/apiClient';import { logger } from '@/utils/logger';-import { normalizeOrgScope } from '@/utils/orgScope';+import { DEFAULT_ORG_SCOPE, normalizeOrgScope } from '@/utils/orgScope';import {getOrganizationAddMemberErrorMessage,getOrganizationAccessInvitationAcceptedMessage,@@ -46,6 +46,11 @@ interface OrganizationAccessPanelProps {currentUser?: string;}+// Instance administrators manage the default organization's members without+// belonging to it, so the server reports that capability directly.+const canManageMembers = (org: Organization | null, currentUser?: string): boolean =>+ org?.id === DEFAULT_ORG_SCOPE ? org.canManageMembers === true : canManageOrg(org, currentUser);+export function useOrganizationAccessPanelState(props: OrganizationAccessPanelProps) {const [loading, setLoading] = createSignal(true);const [loadError, setLoadError] = createSignal<string | null>(null);@@ -77,7 +82,7 @@ export function useOrganizationAccessPanelState(props: OrganizationAccessPanelPr() =>hasCurrentAccess() &&!presentationPolicyIsReadOnly() &&- canManageOrg(org(), props.currentUser),+ canManageMembers(org(), props.currentUser),);const canChangeAccess = () =>hasCurrentAccess() && !!props.currentUser && !presentationPolicyIsReadOnly() && !saving();@@ -135,7 +140,7 @@ export function useOrganizationAccessPanelState(props: OrganizationAccessPanelPrif (!orgData || orgData.id !== orgId) {throw new Error('Organization access returned a different selection');}- const manageable = canManageOrg(orgData, user);+ const manageable = canManageMembers(orgData, user);const [memberData, invitationData, myInvitationData] = await Promise.all([OrgsAPI.listMembers(orgId, options),manageable ? OrgsAPI.listPendingInvitations(orgId, options) : Promise.resolve([]),diff --git a/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx b/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsxindex 38eaa5865b..db7c0e1fa0 100644--- a/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx+++ b/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx@@ -1,11 +1,86 @@-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { APP_BOOTSTRAP_SLOW_DELAY_MS, AppBootstrapStatus } from '@/components/AppBootstrapStatus';+const orgsApi = vi.hoisted(() => ({+ listMyInvitations: vi.fn(),+ acceptMyInvitation: vi.fn(),+ declineMyInvitation: vi.fn(),+}));+const client = vi.hoisted(() => ({ apiFetch: vi.fn(), clearAuth: vi.fn() }));++vi.mock('@/api/orgs', () => ({ OrgsAPI: orgsApi }));+vi.mock('@/utils/apiClient', () => client);++const jsonResponse = (status: number, body: unknown) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });++const refuseEveryOrganization = () =>+ client.apiFetch.mockImplementation(async (url: string) => {+ if (url === '/api/state/summary') {+ return jsonResponse(403, {+ error: 'default_org_access_denied',+ message: 'User is not a member of the default organization',+ });+ }+ if (url === '/api/security/status') return jsonResponse(200, {});+ return jsonResponse(200, { success: true });+ });+describe('AppBootstrapStatus', () => {+ beforeEach(() => {+ client.apiFetch.mockResolvedValue(new Response('unavailable', { status: 503 }));+ });+afterEach(() => {cleanup();vi.useRealTimers();+ vi.clearAllMocks();+ });++ it('offers pending invitations to a signed-in user with no organization', async () => {+ refuseEveryOrganization();+ orgsApi.listMyInvitations.mockResolvedValue([+ {+ orgId: 'acme',+ orgDisplayName: 'Acme',+ userId: 'bob',+ role: 'viewer',+ invitedAt: '2026-11-03T00:00:00Z',+ invitedBy: 'alice',+ },+ ]);+ render(() => <AppBootstrapStatus failed />);++ expect(await screen.findByText('Acme')).toBeVisible();+ expect(screen.getByRole('main')).toHaveAccessibleName('No organization access yet');+ expect(screen.queryByRole('button', { name: 'Retry connection' })).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Sign out' }));+ await waitFor(() =>+ expect(client.apiFetch).toHaveBeenCalledWith(+ '/api/logout',+ expect.objectContaining({ method: 'POST' }),+ ),+ );+ });++ it('tells a user without invitations who can grant access', async () => {+ refuseEveryOrganization();+ orgsApi.listMyInvitations.mockResolvedValue([]);+ render(() => <AppBootstrapStatus failed />);++ expect(+ await screen.findByText('Ask a Pulse administrator to add you to an organization.'),+ ).toBeVisible();+ });++ it('does not probe organization access while the bootstrap is still running', () => {+ render(() => <AppBootstrapStatus />);+ expect(client.apiFetch).not.toHaveBeenCalled();});it('names and announces the initial connection work', () => {diff --git a/frontend-modern/src/stores/organizationAccessBootstrap.ts b/frontend-modern/src/stores/organizationAccessBootstrap.tsnew file mode 100644index 0000000000..e8be59129d--- /dev/null+++ b/frontend-modern/src/stores/organizationAccessBootstrap.ts@@ -0,0 +1,56 @@+import { apiFetch, clearAuth } from '@/utils/apiClient';+import { logger } from '@/utils/logger';++/**+ * Multi-organization mode limits the default organization to instance+ * administrators and its members. A signed-in user who belongs to no other+ * organization yet has no organization the app can open, and the server+ * answers its bootstrap read with `default_org_access_denied` even after the+ * client drops a stale selection.+ */+export const isNoOrganizationAccessResponse = async (response: Response): Promise<boolean> => {+ if (response.status !== 403) return false;+ try {+ const body = await response.clone().json();+ return body?.error === 'default_org_access_denied';+ } catch {+ return false;+ }+};++/** Reports whether a failed bootstrap failed because the user can use no organization. */+export const probeNoOrganizationAccess = async (): Promise<boolean> => {+ try {+ const response = await apiFetch('/api/state/summary', {+ headers: { 'X-Requested-With': 'XMLHttpRequest', Accept: 'application/json' },+ });+ return await isNoOrganizationAccessResponse(response);+ } catch {+ return false;+ }+};++/**+ * Ends the session of a user who never entered the app. Proxy-authenticated+ * users leave through the proxy's logout page, as the app shell's sign-out+ * does; there is no app state to clean up beyond the stored credentials.+ */+export const signOutWithoutOrganization = async (): Promise<void> => {+ let destination = '/';+ try {+ const response = await apiFetch('/api/security/status', { skipOrgContext: true });+ const status = await response.json();+ if (typeof status?.proxyAuthLogoutURL === 'string' && status.proxyAuthLogoutURL) {+ destination = status.proxyAuthLogoutURL;+ }+ } catch {+ // Sign out to the app root.+ }+ try {+ await apiFetch('/api/logout', { method: 'POST', skipOrgContext: true, retry: false });+ } catch (error) {+ logger.warn('Sign-out request failed', error);+ }+ clearAuth();+ window.location.assign(destination);+};diff --git a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts b/frontend-modern/src/utils/__tests__/apiClient.org.test.tsindex 1e97870188..4443114350 100644--- a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts+++ b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts@@ -358,6 +358,74 @@ describe('apiClient org context', () => {expect(getOrgID()).toBeNull();});+ it('clears a refused default selection and retries without org context', async () => {+ mockFetch+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ error: 'default_org_access_denied',+ message: 'User is not a member of the default organization',+ }),+ { status: 403, headers: { 'Content-Type': 'application/json' } },+ ),+ )+ .mockResolvedValueOnce(new Response('{}', { status: 200 }));++ setOrgID('default');+ const response = await apiFetch('/api/state/summary');++ expect(response.status).toBe(200);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ const [, firstOptions] = mockFetch.mock.calls[0] as [string, RequestInit];+ expect((firstOptions.headers as Record<string, string>)['X-Pulse-Org-ID']).toBe('default');+ const [, secondOptions] = mockFetch.mock.calls[1] as [string, RequestInit];+ expect((secondOptions.headers as Record<string, string>)['X-Pulse-Org-ID']).toBeUndefined();+ expect(getOrgID()).toBeNull();+ });++ it('does not retarget a write refused in the default organization', async () => {+ mockFetch.mockImplementation(+ async () =>+ new Response(JSON.stringify({ error: 'default_org_access_denied', message: 'denied' }), {+ status: 403,+ headers: { 'Content-Type': 'application/json' },+ }),+ );++ setOrgID('default');+ document.cookie = 'pulse_csrf=synthetic-csrf; Path=/';+ const response = await apiFetch('/api/guests/metadata/vm-1', { method: 'PUT', body: '{}' });++ expect(response.status).toBe(403);+ // The write may be retried once with a refreshed CSRF token, but never+ // without its organization or against the one the server would pick.+ const writes = mockFetch.mock.calls.filter(([url]) => url === '/api/guests/metadata/vm-1');+ expect(writes.length).toBeGreaterThan(0);+ for (const [, options] of writes) {+ expect((options as RequestInit).headers as Record<string, string>).toHaveProperty(+ 'X-Pulse-Org-ID',+ 'default',+ );+ }+ expect(getOrgID()).toBe('default');+ });++ it('keeps the org selection for other 403 responses', async () => {+ mockFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'access_denied', message: 'denied' }), {+ status: 403,+ headers: { 'Content-Type': 'application/json' },+ }),+ );++ setOrgID('tenant-a');+ const response = await apiFetch('/api/state/summary');++ expect(response.status).toBe(403);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(getOrgID()).toBe('tenant-a');+ });+it('honors HTTP-date Retry-After before retrying a 429 response', async () => {vi.useFakeTimers();const retryAfter = new Date(Date.now() + 5000).toUTCString();diff --git a/frontend-modern/src/utils/apiClient.ts b/frontend-modern/src/utils/apiClient.tsindex e9d41e0df7..04c0003bee 100644--- a/frontend-modern/src/utils/apiClient.ts+++ b/frontend-modern/src/utils/apiClient.ts@@ -694,21 +694,33 @@ class ApiClient {});}- // Handle stale/invalid org context by clearing it and retrying once against default org.+ // Handle stale/invalid org context by clearing it and retrying once. The+ // server then resolves the organization: default where the user may use+ // it, otherwise the first organization they belong to. A refused default+ // selection is stale context too: multi-organization mode limits the+ // default organization to instance administrators and its members. Only+ // reads recover that way: retrying a write would silently apply it to the+ // organization the server picks instead of the one the user was viewing.+ const staleOrgStatus =+ (response.status === 400 &&+ !!finalHeaders[ORG_HEADER_NAME] &&+ finalHeaders[ORG_HEADER_NAME] !== 'default') ||+ (response.status === 403 && (method === 'GET' || method === 'HEAD'));if (- response.status === 400 &&+ staleOrgStatus &&retry &&expectedOrgID === undefined &&!skipOrgContext &&- url.startsWith('/api/') &&- finalHeaders[ORG_HEADER_NAME] &&- finalHeaders[ORG_HEADER_NAME] !== 'default'+ url.startsWith('/api/')) {const text = await response.clone().text();let isInvalidOrg = false;try {const parsed = JSON.parse(text);- isInvalidOrg = parsed?.error === 'invalid_org';+ isInvalidOrg =+ response.status === 400+ ? parsed?.error === 'invalid_org'+ : parsed?.error === 'default_org_access_denied';} catch {isInvalidOrg = false;}diff --git a/internal/api/action_authority.go b/internal/api/action_authority.goindex c24060ef4c..7bd9b94921 100644--- a/internal/api/action_authority.go+++ b/internal/api/action_authority.go@@ -126,7 +126,7 @@ func (a actionAuthority) authorizeActor(ctx context.Context, orgID string, actor} else if actor.Kind != unified.ActionActorUser || !strings.EqualFold(strings.TrimSpace(auth.GetUser(ctx)), actor.SubjectID) {return actionlifecycle.ErrApprovalActorNotHuman}- if a.orgChecker == nil || !a.orgChecker.CheckAccess(token, actor.SubjectID, orgID).Allowed {+ if a.orgChecker == nil || !a.orgChecker.CheckAccessContext(ctx, token, actor.SubjectID, orgID).Allowed {return actionlifecycle.ErrActionAuthorizationDenied}return authorizeActionCapability(ctx, a.authorizer, capability)diff --git a/internal/api/agent_events_auth.go b/internal/api/agent_events_auth.goindex 83166c569a..a5ef046843 100644--- a/internal/api/agent_events_auth.go+++ b/internal/api/agent_events_auth.go@@ -17,7 +17,9 @@ func (r *Router) handleAgentEvents(w http.ResponseWriter, req *http.Request) {func agentEventTokenRevalidator(cfg *config.Config, req *http.Request) func() bool {revalidate := monitoringTokenSnapshotRevalidator(cfg, req)if revalidate == nil {- return sessionReadRevalidator(req)+ // A signed-in user's stream also follows the organization access+ // policy, so lost membership or default access ends it.+ return combineAuthorization(sessionReadRevalidator(req), orgAccessRevalidator(req))}admittedContext := req.Context()return func() bool {diff --git a/internal/api/auth.go b/internal/api/auth.goindex 66e00440e0..9ac48801d4 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -1394,8 +1394,8 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantM// Check proxy authif cfg.ProxyAuthSecret != "" {- if valid, username, _ := CheckProxyAuth(cfg, r); valid && username != "" {- return attachUserContext(r, username)+ if valid, username, isAdmin := CheckProxyAuth(cfg, r); valid && username != "" {+ return attachProxyPrincipal(attachUserContext(r, username), username, isAdmin)}}diff --git a/internal/api/authorization.go b/internal/api/authorization.goindex c5b8a57503..4a88a38a76 100644--- a/internal/api/authorization.go+++ b/internal/api/authorization.go@@ -1,7 +1,11 @@package apiimport (+ "context"+ "errors""fmt"+ "os"+ "strings""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -20,10 +24,26 @@ type AuthorizationChecker interface {CheckAccess(token *config.APITokenRecord, userID, orgID string) AuthorizationResult}+// contextAuthorizationChecker is implemented by checkers whose decision depends+// on request-bound authority (a proxy administrator, the dev bypass) and that+// can pick an organization for a request which did not name one.+type contextAuthorizationChecker interface {+ CheckAccessContext(ctx context.Context, token *config.APITokenRecord, userID, orgID string) AuthorizationResult+ LandingOrgID(ctx context.Context, userID string) string+}+// DefaultAuthorizationChecker implements AuthorizationChecker with the default logic.type DefaultAuthorizationChecker struct {// orgLoader is used to load organization data for membership checks.orgLoader OrganizationLoader++ // hostedMode marks a runtime that serves a single hosted tenant. Its+ // default organization is not shared with other tenants.+ hostedMode bool++ // instanceAdmin reports whether the request's user administers the+ // instance. Nil means no user does.+ instanceAdmin func(ctx context.Context, userID string) bool}// OrganizationLoader provides methods to load organization data.@@ -39,6 +59,28 @@ func NewAuthorizationChecker(loader OrganizationLoader) *DefaultAuthorizationChe}}+// SetHostedMode marks the checker as serving a hosted single-tenant runtime.+func (c *DefaultAuthorizationChecker) SetHostedMode(hosted bool) {+ c.hostedMode = hosted+}++// SetInstanceAdminResolver sets the rule deciding who administers the instance.+func (c *DefaultAuthorizationChecker) SetInstanceAdminResolver(resolve func(ctx context.Context, userID string) bool) {+ c.instanceAdmin = resolve+}++// strictOrganizationLoader loads organization metadata without synthesizing+// an empty organization when org.json is missing. Access decisions use it so+// a missing or unreadable file never stands in for real membership data.+type strictOrganizationLoader interface {+ GetOrganizationStrict(orgID string) (*models.Organization, error)+}++// organizationIDLister lists organization IDs without reading their metadata.+type organizationIDLister interface {+ ListOrganizationIDs() ([]string, error)+}+// MultiTenantOrganizationLoader implements OrganizationLoader using MultiTenantPersistence.type MultiTenantOrganizationLoader struct {persistence *config.MultiTenantPersistence@@ -59,6 +101,119 @@ func (l *MultiTenantOrganizationLoader) GetOrganization(orgID string) (*models.Oreturn l.persistence.LoadOrganization(orgID)}+// GetOrganizationStrict loads org.json and fails when it does not exist.+func (l *MultiTenantOrganizationLoader) GetOrganizationStrict(orgID string) (*models.Organization, error) {+ if l.persistence == nil {+ return nil, fmt.Errorf("no persistence configured")+ }+ return l.persistence.LoadOrganizationStrict(orgID)+}++// ListOrganizationIDs lists the persisted organization IDs, default included.+func (l *MultiTenantOrganizationLoader) ListOrganizationIDs() ([]string, error) {+ if l.persistence == nil {+ return nil, fmt.Errorf("no persistence configured")+ }+ return l.persistence.ListOrganizationIDs()+}++// defaultOrgRestricted reports whether the default organization is one tenant+// among several in this process. Self-hosted multi-organization mode shares one+// process between organizations, so the default organization's estate belongs+// to the instance, not to every user who can sign in. Single-tenant and hosted+// runtimes have no other tenant to separate it from.+func (c *DefaultAuthorizationChecker) defaultOrgRestricted() bool {+ return IsMultiTenantEnabled() && !c.hostedMode+}++func (c *DefaultAuthorizationChecker) loadOrganizationForAccess(orgID string) (*models.Organization, error) {+ if c.orgLoader == nil {+ return nil, fmt.Errorf("no organization loader configured")+ }+ if strict, ok := c.orgLoader.(strictOrganizationLoader); ok {+ return strict.GetOrganizationStrict(orgID)+ }+ return c.orgLoader.GetOrganization(orgID)+}++// userDefaultOrgAccess decides default-organization access for a signed-in+// user. In multi-organization mode only instance administrators and explicit+// members of the default organization qualify. Having no other membership is+// not an entitlement: a user's last membership can be removed, and a pending+// invitation is not a membership.+func (c *DefaultAuthorizationChecker) userDefaultOrgAccess(ctx context.Context, userID string) AuthorizationResult {+ if !c.defaultOrgRestricted() {+ return AuthorizationResult{+ Allowed: true,+ Reason: "Default organization is accessible to all authenticated users",+ }+ }+ if c.instanceAdmin != nil && c.instanceAdmin(ctx, userID) {+ return AuthorizationResult{+ Allowed: true,+ Reason: "Instance administrators can access the default organization",+ }+ }+ org, err := c.loadOrganizationForAccess("default")+ if err != nil {+ if !errors.Is(err, os.ErrNotExist) {+ log.Error().+ Err(err).+ Str("user_id", userID).+ Msg("Failed to load default organization for access check")+ }+ return AuthorizationResult{+ Allowed: false,+ Reason: "User is not a member of the default organization",+ }+ }+ // Membership is the entitlement. An owner field on the default+ // organization grants nothing by itself, so removing a member always+ // revokes their access.+ if org != nil && org.HasMemberUserID(userID) {+ return AuthorizationResult{+ Allowed: true,+ Reason: "User is a member of the default organization",+ }+ }+ return AuthorizationResult{+ Allowed: false,+ Reason: "User is not a member of the default organization",+ }+}++// LandingOrgID returns the organization a request that names none should use+// when the user cannot use the default organization: the first organization,+// by ID, the user belongs to. It returns "" when the default organization is+// usable or the user belongs to no organization.+func (c *DefaultAuthorizationChecker) LandingOrgID(ctx context.Context, userID string) string {+ userID = strings.TrimSpace(userID)+ if userID == "" || !c.defaultOrgRestricted() {+ return ""+ }+ if c.userDefaultOrgAccess(ctx, userID).Allowed {+ return ""+ }+ lister, ok := c.orgLoader.(organizationIDLister)+ if !ok {+ return ""+ }+ orgIDs, err := lister.ListOrganizationIDs()+ if err != nil {+ log.Warn().Err(err).Str("user_id", userID).Msg("Failed to list organizations for landing organization")+ return ""+ }+ for _, orgID := range orgIDs {+ if orgID == "default" {+ continue+ }+ if c.UserCanAccessOrg(userID, orgID) {+ return orgID+ }+ }+ return ""+}+// TokenCanAccessOrg checks if an API token is authorized to access the specified organization.func (c *DefaultAuthorizationChecker) TokenCanAccessOrg(token *config.APITokenRecord, orgID string) bool {if token == nil {@@ -87,10 +242,10 @@ func (c *DefaultAuthorizationChecker) UserCanAccessOrg(userID, orgID string) booreturn false}- // The default organization is always accessible to any authenticated user.- // This ensures single-tenant deployments work without org membership data.+ // Single-tenant deployments keep the default organization open to every+ // authenticated user; multi-organization mode limits it.if orgID == "default" {- return true+ return c.userDefaultOrgAccess(context.Background(), userID).Allowed}// Fail closed when membership data cannot be resolved.@@ -102,7 +257,7 @@ func (c *DefaultAuthorizationChecker) UserCanAccessOrg(userID, orgID string) booreturn false}- org, err := c.orgLoader.GetOrganization(orgID)+ org, err := c.loadOrganizationForAccess(orgID)if err != nil {log.Error().Err(err).@@ -141,9 +296,22 @@ type AuthorizationResult struct {}// CheckAccess performs a comprehensive authorization check for a request.+// Prefer CheckAccessContext where a request context exists: request-bound+// authority such as a proxy administrator is only visible there.func (c *DefaultAuthorizationChecker) CheckAccess(token *config.APITokenRecord, userID, orgID string) AuthorizationResult {- // The default organization stays accessible to authenticated users and to- // legacy unbound tokens. A token explicitly bound to organizations is+ return c.CheckAccessContext(context.Background(), token, userID, orgID)+}++// CheckAccessContext is the organization access policy every caller shares:+// HTTP tenant selection, action authority, organization handlers and live+// streams.+func (c *DefaultAuthorizationChecker) CheckAccessContext(ctx context.Context, token *config.APITokenRecord, userID, orgID string) AuthorizationResult {+ if ctx == nil {+ ctx = context.Background()+ }+ // The default organization stays accessible to legacy unbound tokens, and+ // to authenticated users unless multi-organization mode limits it to+ // instance administrators and its members. A token explicitly bound to organizations is// scoped to those organizations only — binding expresses intent to limit,// so it must not implicitly reach the default org's data (bind "default"// explicitly to grant that). Without this, a client-bound MSP token that@@ -159,10 +327,7 @@ func (c *DefaultAuthorizationChecker) CheckAccess(token *config.APITokenRecord,}// Org-bound tokens fall through to the explicit binding check.} else if userID != "" {- return AuthorizationResult{- Allowed: true,- Reason: "Default organization is accessible to all authenticated users",- }+ return c.userDefaultOrgAccess(ctx, userID)}}@@ -214,3 +379,14 @@ func (c *DefaultAuthorizationChecker) CanAccessOrg(userID string, tokenInterfaceresult := c.CheckAccess(token, userID, orgID)return result.Allowed}++// CanAccessOrgContext implements websocket.OrgAuthContextChecker.+func (c *DefaultAuthorizationChecker) CanAccessOrgContext(ctx context.Context, userID string, tokenInterface interface{}, orgID string) bool {+ var token *config.APITokenRecord+ if tokenInterface != nil {+ if t, ok := tokenInterface.(*config.APITokenRecord); ok {+ token = t+ }+ }+ return c.CheckAccessContext(ctx, token, userID, orgID).Allowed+}diff --git a/internal/api/middleware_tenant.go b/internal/api/middleware_tenant.goindex 00712801f9..784f6f7143 100644--- a/internal/api/middleware_tenant.go+++ b/internal/api/middleware_tenant.go@@ -40,7 +40,36 @@ type TenantMiddlewareConfig struct {HostedMode bool}+// resolveTenantOrgID returns the request's organization. Once TenantMiddleware+// has authorized an organization, that decision wins: it may have chosen a+// landing organization for a request that named none, and handlers must act on+// the organization that was authorized, not re-derive one from the request.func resolveTenantOrgID(r *http.Request) string {+ if r != nil {+ // Read the context value directly: GetOrgID reports "default" when+ // TenantMiddleware has not run, which must not mask the request's own+ // selection or its org-bound token.+ if authorized, ok := r.Context().Value(OrgIDContextKey).(string); ok && strings.TrimSpace(authorized) != "" {+ return strings.TrimSpace(authorized)+ }+ }+ return requestedTenantOrgID(r)+}++// requestNamesTenantOrg reports whether the request selected an organization+// with the X-Pulse-Org-ID header or the organization cookie.+func requestNamesTenantOrg(r *http.Request) bool {+ if r == nil {+ return false+ }+ if strings.TrimSpace(r.Header.Get("X-Pulse-Org-ID")) != "" {+ return true+ }+ cookie, err := r.Cookie(CookieNameOrgID)+ return err == nil && strings.TrimSpace(cookie.Value) != ""+}++func requestedTenantOrgID(r *http.Request) string {orgID := ""explicitOrg := false@@ -97,7 +126,23 @@ func (m *TenantMiddleware) Middleware(next http.Handler) http.Handler {// 2. Cookie: pulse_org_id (for browser session)// 3. Fallback: "default" (for backward compatibility)- orgID := resolveTenantOrgID(r)+ orgID := requestedTenantOrgID(r)++ // Shared-process multi-organization mode limits the default+ // organization. A signed-in user who did not name an organization and+ // cannot use the default one lands in the first organization they+ // belong to, so the app shell and bootstrap reads load in their own+ // organization instead of failing.+ policy, _ := m.authChecker.(contextAuthorizationChecker)+ namedOrg := requestNamesTenantOrg(r)+ if policy != nil && !namedOrg && orgID == "default" && !isAdminBypassRequest(r.Context()) &&+ getAPITokenRecordFromRequest(r) == nil {+ if userID := auth.GetUser(r.Context()); userID != "" {+ if landing := policy.LandingOrgID(r.Context(), userID); landing != "" {+ orgID = landing+ }+ }+ }var loadedOrg *models.Organization@@ -183,14 +228,33 @@ func (m *TenantMiddleware) Middleware(next http.Handler) http.Handler {// If no auth context, the route's RequireAuth will handle authentication errorsif token != nil || userID != "" {// Perform authorization check using the interface method- result := m.authChecker.CheckAccess(token, userID, orgID)+ var result AuthorizationResult+ if policy != nil {+ result = policy.CheckAccessContext(r.Context(), token, userID, orgID)+ } else {+ result = m.authChecker.CheckAccess(token, userID, orgID)+ }+ // A signed-in user who cannot use the default organization may+ // still load the app shell, see their sign-in state, list their+ // organizations, handle invitations and sign out, including+ // with a stale default selection. Those routes do not read+ // default-org data.+ if !result.Allowed && policy != nil && orgID == "default" && token == nil && orgNeutralBootstrapRequest(r) {+ result = AuthorizationResult{Allowed: true, Reason: "Organization-neutral route"}+ }if !result.Allowed {log.Warn().Str("org_id", orgID).Str("user_id", userID).Str("reason", result.Reason).Msg("Unauthorized access attempt to organization")- writeJSONError(w, http.StatusForbidden, "access_denied", result.Reason)+ code := "access_denied"+ if orgID == "default" && token == nil {+ // Clients clear a stale default selection on this+ // code and retry, landing in the user's own org.+ code = "default_org_access_denied"+ }+ writeJSONError(w, http.StatusForbidden, code, result.Reason)return}}@@ -198,6 +262,7 @@ func (m *TenantMiddleware) Middleware(next http.Handler) http.Handler {// 5. Inject into Contextctx := context.WithValue(r.Context(), OrgIDContextKey, orgID)+ ctx = withOrgAccessChecker(ctx, policy)org := loadedOrgif org == nil {diff --git a/internal/api/org_access_policy.go b/internal/api/org_access_policy.gonew file mode 100644index 0000000000..8dfb960213--- /dev/null+++ b/internal/api/org_access_policy.go@@ -0,0 +1,329 @@+package api++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+ "github.com/rs/zerolog/log"+)++// proxyPrincipal records how proxy authentication admitted a request. The+// admin role arrives in a request header, so it is bound to the username it+// was presented with and never re-read from the request later.+type proxyPrincipal struct {+ username string+ isAdmin bool+}++type proxyPrincipalContextKey struct{}++func attachProxyPrincipal(r *http.Request, username string, isAdmin bool) *http.Request {+ ctx := context.WithValue(r.Context(), proxyPrincipalContextKey{}, proxyPrincipal{username: username, isAdmin: isAdmin})+ return r.WithContext(ctx)+}++func proxyPrincipalFromContext(ctx context.Context) (proxyPrincipal, bool) {+ if ctx == nil {+ return proxyPrincipal{}, false+ }+ principal, ok := ctx.Value(proxyPrincipalContextKey{}).(proxyPrincipal)+ return principal, ok && principal.username != ""+}++// instanceAdminResolver returns the instance-administrator rule the+// organization access policy applies to signed-in users. A proxy-authenticated+// user is an administrator only when proxy authentication admitted that same+// username with the admin role; session users follow+// sessionUserCarriesAdminPrivileges. API tokens never qualify here: their+// organization access is decided by their bindings.+func instanceAdminResolver(cfg *config.Config) func(ctx context.Context, userID string) bool {+ return func(ctx context.Context, userID string) bool {+ userID = strings.TrimSpace(userID)+ if userID == "" || strings.HasPrefix(userID, "token:") {+ return false+ }+ if ctx != nil && isAdminBypassRequest(ctx) {+ return true+ }+ if principal, ok := proxyPrincipalFromContext(ctx); ok {+ return principal.isAdmin && principal.username == userID+ }+ return sessionUserCarriesAdminPrivileges(cfg, userID)+ }+}++// newOrgAccessChecker builds the organization access policy shared by tenant+// selection, action authority, organization handlers and live streams.+func newOrgAccessChecker(cfg *config.Config, persistence *config.MultiTenantPersistence, hostedMode bool) *DefaultAuthorizationChecker {+ var loader OrganizationLoader+ if persistence != nil {+ loader = NewMultiTenantOrganizationLoader(persistence)+ }+ checker := NewAuthorizationChecker(loader)+ checker.SetHostedMode(hostedMode)+ checker.SetInstanceAdminResolver(instanceAdminResolver(cfg))+ return checker+}++type orgAccessCheckerContextKey struct{}++// withOrgAccessChecker lets long-lived readers admitted by TenantMiddleware+// re-check the same policy after admission.+func withOrgAccessChecker(ctx context.Context, checker contextAuthorizationChecker) context.Context {+ if checker == nil {+ return ctx+ }+ return context.WithValue(ctx, orgAccessCheckerContextKey{}, checker)+}++// orgAccessRecheckInterval bounds how long a stream keeps writing after its+// user loses organization access. Writers call the revalidator before every+// frame, so it caches a granted decision for this long.+var orgAccessRecheckInterval = 10 * time.Second++// orgAccessRevalidator re-applies the organization access policy to a+// signed-in user's long-lived read (WebSocket or SSE). Membership removal,+// default-organization revocation and losing instance administration end the+// stream within orgAccessRecheckInterval. Token readers keep their own+// credential revalidation, which already rechecks organization bindings.+// It returns nil when the request has no user to recheck.+func orgAccessRevalidator(req *http.Request) func() bool {+ if req == nil {+ return nil+ }+ ctx := req.Context()+ checker, ok := ctx.Value(orgAccessCheckerContextKey{}).(contextAuthorizationChecker)+ if !ok || checker == nil {+ return nil+ }+ if getAPITokenRecordFromRequest(req) != nil {+ return nil+ }+ userID := strings.TrimSpace(auth.GetUser(ctx))+ if userID == "" {+ return nil+ }+ orgID := strings.TrimSpace(GetOrgID(ctx))+ if orgID == "" {+ orgID = "default"+ }++ var (+ mu sync.Mutex+ checkedAt time.Time+ denied bool+ )+ return func() bool {+ mu.Lock()+ defer mu.Unlock()+ if denied {+ return false+ }+ if !checkedAt.IsZero() && time.Since(checkedAt) < orgAccessRecheckInterval {+ return true+ }+ if !checker.CheckAccessContext(ctx, nil, userID, orgID).Allowed {+ denied = true+ return false+ }+ checkedAt = time.Now()+ return true+ }+}++// combineAuthorization requires every non-nil check to pass.+func combineAuthorization(checks ...func() bool) func() bool {+ active := make([]func() bool, 0, len(checks))+ for _, check := range checks {+ if check != nil {+ active = append(active, check)+ }+ }+ if len(active) == 0 {+ return nil+ }+ return func() bool {+ for _, check := range active {+ if !check() {+ return false+ }+ }+ return true+ }+}++// orgNeutralBootstrapRequest reports whether a request may run in the default+// organization's context for a user who cannot use it. These+// routes let the user load the app shell, see that they are signed in, find+// and accept invitations, and sign out; none of them reads the default+// organization's monitoring data.+func orgNeutralBootstrapRequest(r *http.Request) bool {+ if r == nil || r.URL == nil {+ return false+ }+ path := r.URL.Path+ switch path {+ case "/api/security/status", "/api/logout", "/api/health":+ // /api/health is public and also issues the CSRF token that+ // accepting an invitation needs.+ return true+ case "/api/orgs":+ return r.Method == http.MethodGet+ case "/ws", "/simple-stats":+ return false+ }+ if path == "/api/org-invitations" || strings.HasPrefix(path, "/api/org-invitations/") {+ return true+ }+ // The single-page app shell and its static assets. Org-scoped non-API+ // routes are excluded above, and API routes are denied by default.+ return !strings.HasPrefix(path, "/api") && path != "/debug" && !strings.HasPrefix(path, "/debug/")+}++// defaultOrgMembershipMu serializes read-modify-write changes to the default+// organization's members. Each change loads and saves the whole org.json, so+// without it an add that overlaps a removal could save its older snapshot and+// restore a revoked entitlement.+var defaultOrgMembershipMu sync.Mutex++// defaultOrgAccessMigrationFile records, in the base data directory, that+// existing users' implicit default-organization access has been converted to+// explicit membership. Its presence stops the migration from running again,+// even if the default organization's metadata is later reset.+const defaultOrgAccessMigrationFile = "default-org-access-migration.json"++// defaultOrgAccessMigrationActor marks memberships the migration created, so+// administrators can tell them from grants they made.+const defaultOrgAccessMigrationActor = "migration:default-org-access"++type defaultOrgAccessMigrationRecord struct {+ MigratedAt time.Time `json:"migratedAt"`+ Seeded []string `json:"seeded"`+}++// migrateDefaultOrgAccess runs once when shared-process multi-organization mode+// starts limiting the default organization. Before, every signed-in user could+// read it. Users with a role assignment in the instance's RBAC store, who+// belong to no other organization and have no pending invitation, were+// evidently using the default organization, so they become its viewer+// members. Everyone else must be granted access by an instance administrator;+// proxy-authenticated users have no stored record to migrate from.+//+// It fails without writing the marker when any organization's metadata or the+// RBAC assignments cannot be read, so a later start retries with complete+// data. A tenant directory without org.json counts as unreadable: its members+// are unknown, and treating them as absent could grant a tenant-only user the+// default organization.+func migrateDefaultOrgAccess(persistence *config.MultiTenantPersistence, manager auth.Manager, cfg *config.Config, hostedMode bool) error {+ if persistence == nil || hostedMode || !IsMultiTenantEnabled() {+ return nil+ }+ defaultOrgMembershipMu.Lock()+ defer defaultOrgMembershipMu.Unlock()+ markerPath := filepath.Join(persistence.BaseDataDir(), defaultOrgAccessMigrationFile)+ if _, err := os.Stat(markerPath); err == nil {+ return nil+ } else if !errors.Is(err, os.ErrNotExist) {+ return fmt.Errorf("check default organization access migration: %w", err)+ }++ orgIDs, err := persistence.ListOrganizationIDs()+ if err != nil {+ return fmt.Errorf("list organizations: %w", err)+ }+ elsewhere := make(map[string]struct{})+ for _, orgID := range orgIDs {+ if orgID == "default" {+ continue+ }+ org, loadErr := persistence.LoadOrganizationStrict(orgID)+ if loadErr != nil {+ return fmt.Errorf("load organization %s: %w", orgID, loadErr)+ }+ if owner := strings.TrimSpace(org.OwnerUserID); owner != "" {+ elsewhere[owner] = struct{}{}+ }+ for _, member := range org.Members {+ elsewhere[strings.TrimSpace(member.UserID)] = struct{}{}+ }+ for _, invitation := range org.PendingInvitations {+ elsewhere[strings.TrimSpace(invitation.UserID)] = struct{}{}+ }+ }++ defaultOrg, err := persistence.LoadOrganizationStrict("default")+ if err != nil {+ if !errors.Is(err, os.ErrNotExist) {+ return fmt.Errorf("load default organization: %w", err)+ }+ defaultOrg = &models.Organization{ID: "default", DisplayName: "default"}+ }++ var assignments []auth.UserRoleAssignment+ if manager != nil {+ if errorAware, ok := manager.(auth.ErrorAwareManager); ok {+ assignments, err = errorAware.GetUserAssignmentsWithError()+ if err != nil {+ return fmt.Errorf("read RBAC assignments: %w", err)+ }+ } else {+ assignments = manager.GetUserAssignments()+ }+ }++ seeded := make([]string, 0)+ if len(assignments) > 0 {+ now := time.Now().UTC()+ for _, assignment := range assignments {+ username := strings.TrimSpace(assignment.Username)+ if username == "" || strings.HasPrefix(username, "token:") || len(assignment.RoleIDs) == 0 {+ continue+ }+ if _, ok := elsewhere[username]; ok {+ continue+ }+ // Administrators reach the default organization by authority.+ if sessionUserCarriesAdminPrivileges(cfg, username) || defaultOrg.CanUserIDAccess(username) {+ continue+ }+ defaultOrg.Members = append(defaultOrg.Members, models.OrganizationMember{+ UserID: username,+ Role: models.OrgRoleViewer,+ AddedAt: now,+ AddedBy: defaultOrgAccessMigrationActor,+ })+ seeded = append(seeded, username)+ }+ }+ sort.Strings(seeded)+ if len(seeded) > 0 {+ if err := persistence.SaveOrganization(defaultOrg); err != nil {+ return fmt.Errorf("save default organization: %w", err)+ }+ }++ record, err := json.MarshalIndent(defaultOrgAccessMigrationRecord{MigratedAt: time.Now().UTC(), Seeded: seeded}, "", " ")+ if err != nil {+ return fmt.Errorf("encode default organization access migration: %w", err)+ }+ if err := os.WriteFile(markerPath, record, 0o600); err != nil {+ return fmt.Errorf("record default organization access migration: %w", err)+ }+ log.Warn().+ Int("seeded_members", len(seeded)).+ Strs("seeded_users", seeded).+ Msg("Default organization access now requires instance administration or default organization membership; existing users without another organization were added as members. Review them under Settings > Organization access.")+ return nil+}diff --git a/internal/api/org_access_policy_test.go b/internal/api/org_access_policy_test.gonew file mode 100644index 0000000000..603dab576d--- /dev/null+++ b/internal/api/org_access_policy_test.go@@ -0,0 +1,570 @@+package api++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++const orgAccessTestAdmin = "admin"++func enableSharedMultiOrgForTest(t *testing.T) {+ t.Helper()+ previous := IsMultiTenantEnabled()+ SetMultiTenantEnabled(true)+ t.Cleanup(func() { SetMultiTenantEnabled(previous) })+}++// newOrgAccessFixture builds persistence with one tenant, "acme": alice owns+// it, bob is a member, and carol only holds a pending invitation.+func newOrgAccessFixture(t *testing.T, hosted bool) (*config.MultiTenantPersistence, *DefaultAuthorizationChecker) {+ t.Helper()+ persistence := config.NewMultiTenantPersistence(t.TempDir())+ acme := &models.Organization{+ ID: "acme",+ DisplayName: "Acme",+ OwnerUserID: "alice",+ Members: []models.OrganizationMember{+ {UserID: "alice", Role: models.OrgRoleOwner},+ {UserID: "bob", Role: models.OrgRoleViewer},+ },+ PendingInvitations: []models.OrganizationInvitation{+ {UserID: "carol", Role: models.OrgRoleViewer},+ },+ }+ if err := persistence.SaveOrganization(acme); err != nil {+ t.Fatalf("save acme: %v", err)+ }+ return persistence, newOrgAccessChecker(&config.Config{AuthUser: orgAccessTestAdmin}, persistence, hosted)+}++func saveDefaultOrgMembers(t *testing.T, persistence *config.MultiTenantPersistence, userIDs ...string) {+ t.Helper()+ org := &models.Organization{ID: "default", DisplayName: "default"}+ for _, userID := range userIDs {+ org.Members = append(org.Members, models.OrganizationMember{UserID: userID, Role: models.OrgRoleViewer})+ }+ if err := persistence.SaveOrganization(org); err != nil {+ t.Fatalf("save default org: %v", err)+ }+}++func TestOrgAccessPolicy_DefaultOrgNeedsAdminOrMembershipInSharedMultiOrgMode(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, checker := newOrgAccessFixture(t, false)++ for _, user := range []string{"bob", "carol", "nobody"} {+ res := checker.CheckAccess(nil, user, "default")+ if res.Allowed {+ t.Fatalf("%s reached the default organization without membership", user)+ }+ if res.Reason != "User is not a member of the default organization" {+ t.Fatalf("unexpected reason for %s: %q", user, res.Reason)+ }+ if checker.UserCanAccessOrg(user, "default") || checker.CanAccessOrg(user, nil, "default") {+ t.Fatalf("%s reached the default organization through another entry point", user)+ }+ }+ if !checker.CheckAccess(nil, orgAccessTestAdmin, "default").Allowed {+ t.Fatal("configured instance administrator must reach the default organization")+ }+ if !checker.CheckAccess(nil, "bob", "acme").Allowed {+ t.Fatal("tenant membership must still grant the tenant")+ }++ saveDefaultOrgMembers(t, persistence, "dave")+ if !checker.CheckAccess(nil, "dave", "default").Allowed {+ t.Fatal("explicit default-organization member must reach it")+ }+ if checker.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("another user's default membership must not grant bob")+ }++ // Token rules are unchanged: unbound tokens keep default access and+ // org-bound tokens need an explicit default binding.+ if !checker.CheckAccess(&config.APITokenRecord{}, "", "default").Allowed {+ t.Fatal("legacy unbound token must keep default-organization access")+ }+ if checker.CheckAccess(&config.APITokenRecord{OrgID: "acme"}, "", "default").Allowed {+ t.Fatal("acme-bound token must not reach the default organization")+ }+}++func TestOrgAccessPolicy_DefaultOrgStaysOpenOutsideSharedMultiOrgMode(t *testing.T) {+ installTestRBACManager(t)++ t.Run("single tenant", func(t *testing.T) {+ previous := IsMultiTenantEnabled()+ SetMultiTenantEnabled(false)+ t.Cleanup(func() { SetMultiTenantEnabled(previous) })+ _, checker := newOrgAccessFixture(t, false)+ if !checker.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("single-tenant default organization must stay open to signed-in users")+ }+ })++ t.Run("hosted", func(t *testing.T) {+ enableSharedMultiOrgForTest(t)+ _, checker := newOrgAccessFixture(t, true)+ if !checker.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("hosted runtimes do not share the default organization with other tenants")+ }+ })+}++func TestOrgAccessPolicy_DefaultOrgMetadataIsReadStrictly(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, checker := newOrgAccessFixture(t, false)++ // Missing org.json is no membership, not a synthesized open organization.+ if checker.CheckAccess(nil, "dave", "default").Allowed {+ t.Fatal("missing default metadata must not grant access")+ }++ saveDefaultOrgMembers(t, persistence, "dave")+ orgFile := filepath.Join(persistence.BaseDataDir(), "org.json")+ if err := os.WriteFile(orgFile, []byte("{not json"), 0o600); err != nil {+ t.Fatalf("corrupt default org metadata: %v", err)+ }+ if checker.CheckAccess(nil, "dave", "default").Allowed {+ t.Fatal("unreadable default metadata must deny members")+ }+ if !checker.CheckAccess(nil, orgAccessTestAdmin, "default").Allowed {+ t.Fatal("instance administrators do not depend on default metadata")+ }+}++func TestOrgAccessPolicy_ProxyAdminAuthorityIsBoundToItsPrincipal(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ _, checker := newOrgAccessFixture(t, false)++ proxyCtx := func(username string, isAdmin bool) context.Context {+ req := httptest.NewRequest(http.MethodGet, "/api/state", nil)+ return attachProxyPrincipal(req, username, isAdmin).Context()+ }++ if !checker.CheckAccessContext(proxyCtx("bob", true), nil, "bob", "default").Allowed {+ t.Fatal("proxy administrator must reach the default organization")+ }+ if checker.CheckAccessContext(proxyCtx("bob", false), nil, "bob", "default").Allowed {+ t.Fatal("proxy non-administrator must not reach the default organization")+ }+ if checker.CheckAccessContext(proxyCtx("mallory", true), nil, "bob", "default").Allowed {+ t.Fatal("proxy admin authority must not transfer to another username")+ }+ // A proxy user named like the local administrator is judged by the+ // proxy's role, not by the local administrator's name.+ if checker.CheckAccessContext(proxyCtx(orgAccessTestAdmin, false), nil, orgAccessTestAdmin, "default").Allowed {+ t.Fatal("proxy non-administrator must not inherit the local administrator's authority")+ }+ // Without a request context the proxy role is unknown, so it never grants.+ if checker.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("proxy admin authority must not apply without its request context")+ }+}++func TestOrgAccessPolicy_LandingOrgForUsersWithoutDefaultAccess(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, checker := newOrgAccessFixture(t, false)+ saveDefaultOrgMembers(t, persistence, "dave")+ if err := persistence.SaveOrganization(&models.Organization{+ ID: "zeta", DisplayName: "Zeta", OwnerUserID: "bob",+ Members: []models.OrganizationMember{{UserID: "bob", Role: models.OrgRoleOwner}},+ }); err != nil {+ t.Fatalf("save zeta: %v", err)+ }++ ctx := context.Background()+ if got := checker.LandingOrgID(ctx, "bob"); got != "acme" {+ t.Fatalf("bob landing org = %q, want first membership acme", got)+ }+ for _, user := range []string{"carol", "nobody", orgAccessTestAdmin, "dave"} {+ if got := checker.LandingOrgID(ctx, user); got != "" {+ t.Fatalf("%s landing org = %q, want none", user, got)+ }+ }+}++func TestMigrateDefaultOrgAccessSeedsExistingDefaultUsersOnce(t *testing.T) {+ manager := installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, checker := newOrgAccessFixture(t, false)+ cfg := &config.Config{AuthUser: orgAccessTestAdmin}++ assign := func(user string, roleIDs ...string) {+ t.Helper()+ if err := manager.UpdateUserRoles(user, roleIDs); err != nil {+ t.Fatalf("assign %s: %v", user, err)+ }+ }+ assign("dave", internalauth.RoleViewer) // default-only user: seeded+ assign("bob", internalauth.RoleViewer) // acme member: not seeded+ assign("carol", internalauth.RoleViewer) // acme invitee: not seeded+ assign("rbac-admin", internalauth.RoleAdmin) // reaches default by authority+ assign("token:abc", internalauth.RoleViewer) // never a person+ assign("empty") // no roles++ if err := migrateDefaultOrgAccess(persistence, manager, cfg, false); err != nil {+ t.Fatalf("migrate: %v", err)+ }+ defaultOrg, err := persistence.LoadOrganizationStrict("default")+ if err != nil {+ t.Fatalf("load default org: %v", err)+ }+ if len(defaultOrg.Members) != 1 || defaultOrg.Members[0].UserID != "dave" ||+ defaultOrg.Members[0].Role != models.OrgRoleViewer ||+ defaultOrg.Members[0].AddedBy != defaultOrgAccessMigrationActor {+ t.Fatalf("unexpected seeded members: %+v", defaultOrg.Members)+ }+ if !checker.CheckAccess(nil, "dave", "default").Allowed {+ t.Fatal("seeded user must keep default-organization access")+ }++ raw, err := os.ReadFile(filepath.Join(persistence.BaseDataDir(), defaultOrgAccessMigrationFile))+ if err != nil {+ t.Fatalf("read migration marker: %v", err)+ }+ var record defaultOrgAccessMigrationRecord+ if err := json.Unmarshal(raw, &record); err != nil || len(record.Seeded) != 1 || record.Seeded[0] != "dave" {+ t.Fatalf("unexpected migration record %s (%v)", raw, err)+ }++ // The marker stops a second run from re-granting a revoked user.+ saveDefaultOrgMembers(t, persistence)+ if err := migrateDefaultOrgAccess(persistence, manager, cfg, false); err != nil {+ t.Fatalf("second migrate: %v", err)+ }+ if checker.CheckAccess(nil, "dave", "default").Allowed {+ t.Fatal("migration must not run twice")+ }+}++func TestMigrateDefaultOrgAccessSkipsOutsideSharedMultiOrgMode(t *testing.T) {+ manager := installTestRBACManager(t)+ previous := IsMultiTenantEnabled()+ SetMultiTenantEnabled(false)+ t.Cleanup(func() { SetMultiTenantEnabled(previous) })+ persistence := config.NewMultiTenantPersistence(t.TempDir())++ if err := migrateDefaultOrgAccess(persistence, manager, &config.Config{}, false); err != nil {+ t.Fatalf("migrate: %v", err)+ }+ if _, err := os.Stat(filepath.Join(persistence.BaseDataDir(), defaultOrgAccessMigrationFile)); !os.IsNotExist(err) {+ t.Fatalf("single-tenant start must not record the migration: %v", err)+ }+}++func TestMigrateDefaultOrgAccessRetriesWhenTenantMetadataIsUnreadable(t *testing.T) {+ manager := installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, _ := newOrgAccessFixture(t, false)+ if err := os.WriteFile(filepath.Join(persistence.BaseDataDir(), "orgs", "acme", "org.json"), []byte("{"), 0o600); err != nil {+ t.Fatalf("corrupt acme metadata: %v", err)+ }+ if err := migrateDefaultOrgAccess(persistence, manager, &config.Config{}, false); err == nil {+ t.Fatal("migration must fail on unreadable tenant metadata")+ }+ // A tenant directory without metadata hides its members just the same.+ if err := os.Remove(filepath.Join(persistence.BaseDataDir(), "orgs", "acme", "org.json")); err != nil {+ t.Fatalf("remove acme metadata: %v", err)+ }+ if err := migrateDefaultOrgAccess(persistence, manager, &config.Config{}, false); err == nil {+ t.Fatal("migration must fail when a tenant's members are unknown")+ }+ if _, err := os.Stat(filepath.Join(persistence.BaseDataDir(), defaultOrgAccessMigrationFile)); !os.IsNotExist(err) {+ t.Fatalf("failed migration must not record completion: %v", err)+ }+}++func orgAccessTestRequest(t *testing.T, method, path, user string, configure func(*http.Request)) *http.Request {+ t.Helper()+ req := httptest.NewRequest(method, path, nil)+ if user != "" {+ req = req.WithContext(internalauth.WithUser(req.Context(), user))+ }+ if configure != nil {+ configure(req)+ }+ return req+}++func TestTenantMiddleware_SharedMultiOrgDefaultAccess(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ t.Setenv("PULSE_DEV", "true")+ persistence, checker := newOrgAccessFixture(t, false)+ mw := NewTenantMiddlewareWithConfig(TenantMiddlewareConfig{Persistence: persistence, AuthChecker: checker})++ serve := func(req *http.Request) (int, string) {+ t.Helper()+ servedOrg := ""+ handler := mw.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ servedOrg = GetOrgID(r.Context())+ if resolved := resolveTenantOrgID(r); resolved != servedOrg {+ t.Fatalf("handler org %q disagrees with the authorized org %q", resolved, servedOrg)+ }+ w.WriteHeader(http.StatusNoContent)+ }))+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)+ return rec.Code, servedOrg+ }++ // The reported proof of concept: an acme-only user selecting default.+ code, _ := serve(orgAccessTestRequest(t, http.MethodGet, "/api/state", "bob", func(r *http.Request) {+ r.Header.Set("X-Pulse-Org-ID", "default")+ }))+ if code != http.StatusForbidden {+ t.Fatalf("explicit default header: status %d, want 403", code)+ }+ code, _ = serve(orgAccessTestRequest(t, http.MethodGet, "/api/state", "bob", func(r *http.Request) {+ r.AddCookie(&http.Cookie{Name: CookieNameOrgID, Value: "default"})+ }))+ if code != http.StatusForbidden {+ t.Fatalf("default org cookie: status %d, want 403", code)+ }++ // Without a selection, bob lands in his own organization.+ for _, path := range []string{"/", "/api/security/status", "/api/orgs", "/api/state"} {+ code, org := serve(orgAccessTestRequest(t, http.MethodGet, path, "bob", nil))+ if code != http.StatusNoContent || org != "acme" {+ t.Fatalf("bob %s: status %d org %q, want acme", path, code, org)+ }+ }++ // A user with no organization keeps only the organization-neutral routes.+ for _, path := range []string{"/", "/settings", "/api/health", "/api/security/status", "/api/logout", "/api/orgs", "/api/org-invitations"} {+ code, org := serve(orgAccessTestRequest(t, http.MethodGet, path, "carol", nil))+ if code != http.StatusNoContent || org != "default" {+ t.Fatalf("carol %s: status %d org %q, want neutral admission", path, code, org)+ }+ }+ for _, path := range []string{"/api/state", "/api/resources", "/ws", "/simple-stats"} {+ if code, _ := serve(orgAccessTestRequest(t, http.MethodGet, path, "carol", nil)); code != http.StatusForbidden {+ t.Fatalf("carol %s: status %d, want 403", path, code)+ }+ }+ if code, _ := serve(orgAccessTestRequest(t, http.MethodPost, "/api/orgs", "carol", nil)); code != http.StatusForbidden {+ t.Fatalf("carol POST /api/orgs: status %d, want 403", code)+ }+ // A stale default selection still loads the shell and the bootstrap+ // routes, and data routes say why they refused so the client can recover.+ for _, path := range []string{"/", "/api/security/status", "/api/orgs"} {+ code, org := serve(orgAccessTestRequest(t, http.MethodGet, path, "bob", func(r *http.Request) {+ r.AddCookie(&http.Cookie{Name: CookieNameOrgID, Value: "default"})+ }))+ if code != http.StatusNoContent || org != "default" {+ t.Fatalf("bob %s with a default cookie: status %d org %q", path, code, org)+ }+ }+ rec := httptest.NewRecorder()+ mw.Middleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {+ t.Fatal("data route must not be served from a refused default selection")+ })).ServeHTTP(rec, orgAccessTestRequest(t, http.MethodGet, "/api/state/summary", "bob", func(r *http.Request) {+ r.Header.Set("X-Pulse-Org-ID", "default")+ }))+ if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), `"default_org_access_denied"`) {+ t.Fatalf("refused default selection: %d %s", rec.Code, rec.Body.String())+ }++ // Instance administrators keep the default organization.+ code, org := serve(orgAccessTestRequest(t, http.MethodGet, "/api/state", orgAccessTestAdmin, nil))+ if code != http.StatusNoContent || org != "default" {+ t.Fatalf("admin: status %d org %q, want default", code, org)+ }+}++func TestOrgAccessRevalidatorEndsStreamsWhenAccessIsRevoked(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, checker := newOrgAccessFixture(t, false)+ saveDefaultOrgMembers(t, persistence, "dave")++ previousInterval := orgAccessRecheckInterval+ orgAccessRecheckInterval = 0+ t.Cleanup(func() { orgAccessRecheckInterval = previousInterval })++ req := orgAccessTestRequest(t, http.MethodGet, "/ws", "dave", nil)+ ctx := context.WithValue(req.Context(), OrgIDContextKey, "default")+ req = req.WithContext(withOrgAccessChecker(ctx, checker))++ allowed := orgAccessRevalidator(req)+ if allowed == nil || !allowed() {+ t.Fatal("member stream must start allowed")+ }+ saveDefaultOrgMembers(t, persistence)+ if allowed() {+ t.Fatal("stream must end once default membership is revoked")+ }+ saveDefaultOrgMembers(t, persistence, "dave")+ if allowed() {+ t.Fatal("an ended stream must stay ended")+ }++ // Token streams keep their own credential revalidation.+ tokenReq := req.WithContext(internalauth.WithAPIToken(req.Context(), &config.APITokenRecord{ID: "t"}))+ if orgAccessRevalidator(tokenReq) != nil {+ t.Fatal("token streams must not get the user revalidator")+ }+}++func TestOrgHandlers_DefaultOrgMembersInSharedMultiOrgMode(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ t.Setenv("PULSE_DEV", "true")+ persistence, checker := newOrgAccessFixture(t, false)+ h := NewOrgHandlers(persistence, nil)+ h.SetAccessPolicy(checker)++ call := func(handler http.HandlerFunc, method, path, user, body string, pathValues map[string]string) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(method, path, strings.NewReader(body))+ req = req.WithContext(internalauth.WithUser(req.Context(), user))+ for key, value := range pathValues {+ req.SetPathValue(key, value)+ }+ rec := httptest.NewRecorder()+ handler(rec, req)+ return rec+ }+ listOrgIDs := func(user string) []string {+ t.Helper()+ rec := call(h.HandleListOrgs, http.MethodGet, "/api/orgs", user, "", nil)+ if rec.Code != http.StatusOK {+ t.Fatalf("list orgs for %s: %d %s", user, rec.Code, rec.Body.String())+ }+ var orgs []models.Organization+ if err := json.Unmarshal(rec.Body.Bytes(), &orgs); err != nil {+ t.Fatalf("decode orgs: %v", err)+ }+ ids := make([]string, 0, len(orgs))+ for _, org := range orgs {+ ids = append(ids, org.ID)+ }+ return ids+ }++ if got := strings.Join(listOrgIDs("bob"), ","); got != "acme" {+ t.Fatalf("bob sees %q, want only acme", got)+ }+ if got := strings.Join(listOrgIDs(orgAccessTestAdmin), ","); got != "default" {+ t.Fatalf("admin sees %q, want default", got)+ }+ defaultPath := map[string]string{"id": "default"}+ if rec := call(h.HandleGetOrg, http.MethodGet, "/api/orgs/default", "bob", "", defaultPath); rec.Code != http.StatusForbidden {+ t.Fatalf("bob GET default: %d, want 403", rec.Code)+ }+ rec := call(h.HandleGetOrg, http.MethodGet, "/api/orgs/default", orgAccessTestAdmin, "", defaultPath)+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"canManageMembers":true`) {+ t.Fatalf("admin GET default: %d %s", rec.Code, rec.Body.String())+ }++ rec = call(h.HandleListInvitations, http.MethodGet, "/api/orgs/default/invitations", orgAccessTestAdmin, "", defaultPath)+ if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != "[]" {+ t.Fatalf("admin listing default invitations: %d %q, want an empty list", rec.Code, rec.Body.String())+ }++ // Only instance administrators manage default members, and only as viewers.+ if rec := call(h.HandleInviteMember, http.MethodPost, "/api/orgs/default/members", "alice", `{"userId":"bob"}`, defaultPath); rec.Code != http.StatusForbidden {+ t.Fatalf("tenant owner adding a default member: %d, want 403", rec.Code)+ }+ if rec := call(h.HandleInviteMember, http.MethodPost, "/api/orgs/default/members", orgAccessTestAdmin, `{"userId":"bob","role":"admin"}`, defaultPath); rec.Code != http.StatusBadRequest {+ t.Fatalf("admin role on default: %d, want 400", rec.Code)+ }+ rec = call(h.HandleInviteMember, http.MethodPost, "/api/orgs/default/members", orgAccessTestAdmin, `{"userId":"bob"}`, defaultPath)+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"kind":"member"`) {+ t.Fatalf("admin adding bob: %d %s", rec.Code, rec.Body.String())+ }+ if !checker.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("added member must reach the default organization")+ }+ if got := strings.Join(listOrgIDs("bob"), ","); got != "acme,default" {+ t.Fatalf("bob sees %q after the grant", got)+ }+ rec = call(h.HandleGetOrg, http.MethodGet, "/api/orgs/default", "bob", "", defaultPath)+ if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "canManageMembers") {+ t.Fatalf("member GET default: %d %s", rec.Code, rec.Body.String())+ }++ removePath := map[string]string{"id": "default", "userId": "bob"}+ if rec := call(h.HandleRemoveMember, http.MethodDelete, "/api/orgs/default/members/bob", "bob", "", removePath); rec.Code != http.StatusForbidden {+ t.Fatalf("member removing themself: %d, want 403", rec.Code)+ }+ if rec := call(h.HandleRemoveMember, http.MethodDelete, "/api/orgs/default/members/bob", orgAccessTestAdmin, "", removePath); rec.Code != http.StatusNoContent {+ t.Fatalf("admin removing bob: %d %s", rec.Code, rec.Body.String())+ }+ if checker.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("removed member must lose the default organization")+ }+}++func TestOrgHandlers_DefaultOrgOwnerIsRevocableAndStaleSavesKeepMembers(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ t.Setenv("PULSE_DEV", "true")+ persistence, checker := newOrgAccessFixture(t, false)+ h := NewOrgHandlers(persistence, nil)+ h.SetAccessPolicy(checker)++ // An owner field alone grants nothing; membership does.+ if err := persistence.SaveOrganization(&models.Organization{ID: "default", DisplayName: "default", OwnerUserID: "olivia"}); err != nil {+ t.Fatalf("save default org: %v", err)+ }+ if checker.CheckAccess(nil, "olivia", "default").Allowed {+ t.Fatal("default ownership without membership must not grant access")+ }++ // Removing a member who also owns the default organization revokes them.+ saveDefaultOrgMembers(t, persistence, "olivia", "dave")+ org, err := persistence.LoadOrganizationStrict("default")+ if err != nil {+ t.Fatalf("load default org: %v", err)+ }+ org.OwnerUserID = "olivia"+ if err := persistence.SaveOrganization(org); err != nil {+ t.Fatalf("save default owner: %v", err)+ }+ req := httptest.NewRequest(http.MethodDelete, "/api/orgs/default/members/olivia", nil)+ req = req.WithContext(internalauth.WithUser(req.Context(), orgAccessTestAdmin))+ req.SetPathValue("id", "default")+ req.SetPathValue("userId", "olivia")+ rec := httptest.NewRecorder()+ h.HandleRemoveMember(rec, req)+ if rec.Code != http.StatusNoContent {+ t.Fatalf("remove owner member: %d %s", rec.Code, rec.Body.String())+ }+ if checker.CheckAccess(nil, "olivia", "default").Allowed {+ t.Fatal("removed default owner kept access")+ }++ // A save from a snapshot taken before dave's removal must not restore him.+ stale, err := persistence.LoadOrganizationStrict("default")+ if err != nil {+ t.Fatalf("load stale snapshot: %v", err)+ }+ saveDefaultOrgMembers(t, persistence)+ stale.SharedResources = append(stale.SharedResources, models.OrganizationShare{ID: "share-1", TargetOrgID: "acme", ResourceType: "vm", ResourceID: "vm-1"})+ if err := h.saveOrganization(stale); err != nil {+ t.Fatalf("save stale snapshot: %v", err)+ }+ if checker.CheckAccess(nil, "dave", "default").Allowed {+ t.Fatal("a stale default snapshot restored a removed member")+ }+ saved, err := persistence.LoadOrganizationStrict("default")+ if err != nil || len(saved.SharedResources) != 1 {+ t.Fatalf("share change was lost: %+v (%v)", saved, err)+ }+}diff --git a/internal/api/org_handlers.go b/internal/api/org_handlers.goindex ca80eca417..69e8d9a514 100644--- a/internal/api/org_handlers.go+++ b/internal/api/org_handlers.go@@ -93,6 +93,7 @@ type OrgHandlers struct {rbacProvider *TenantRBACProvideronDelete func(ctx context.Context, orgID string) errorhostedMode bool+ accessPolicy *DefaultAuthorizationChecker}func NewOrgHandlers(@@ -129,6 +130,24 @@ func (h *OrgHandlers) SetHostedMode(enabled bool) {h.hostedMode = enabled}+// SetAccessPolicy installs the organization access policy shared with tenant+// selection, so the organization routes decide default-organization access the+// same way.+func (h *OrgHandlers) SetAccessPolicy(policy *DefaultAuthorizationChecker) {+ if h == nil {+ return+ }+ h.accessPolicy = policy+}++// organizationResponse adds the caller's capabilities that the client cannot+// derive from membership. Instance administrators manage the default+// organization's members without being members themselves.+type organizationResponse struct {+ *models.Organization+ CanManageMembers bool `json:"canManageMembers,omitempty"`+}+type createOrganizationRequest struct {ID string `json:"id"`DisplayName string `json:"displayName"`@@ -196,7 +215,7 @@ func (h *OrgHandlers) HandleListOrgs(w http.ResponseWriter, r *http.Request) {continue}normalizeOrganization(org)- if h.canAccessOrg(username, token, org) {+ if h.canAccessOrg(r, username, token, org) {filtered = append(filtered, org)}}@@ -266,7 +285,7 @@ func (h *OrgHandlers) HandleCreateOrg(w http.ResponseWriter, r *http.Request) {},}- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "create_failed", "Failed to create organization", nil)return}@@ -292,12 +311,16 @@ func (h *OrgHandlers) HandleGetOrg(w http.ResponseWriter, r *http.Request) {username := auth.GetUser(r.Context())token := getAPITokenRecordFromRequest(r)- if !h.canAccessOrg(username, token, org) {+ if !h.canAccessOrg(r, username, token, org) {writeErrorResponse(w, http.StatusForbidden, "access_denied", "User is not a member of the organization", nil)return}- writeJSON(w, http.StatusOK, org)+ response := organizationResponse{Organization: org}+ if org.ID == "default" && token == nil {+ response.CanManageMembers = h.canManageDefaultOrgMembers(r, username)+ }+ writeJSON(w, http.StatusOK, response)}func (h *OrgHandlers) HandleUpdateOrg(w http.ResponseWriter, r *http.Request) {@@ -346,7 +369,7 @@ func (h *OrgHandlers) HandleUpdateOrg(w http.ResponseWriter, r *http.Request) {}org.DisplayName = req.DisplayName- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "update_failed", "Failed to update organization", nil)return}@@ -441,7 +464,7 @@ func (h *OrgHandlers) HandleListMembers(w http.ResponseWriter, r *http.Request)username := auth.GetUser(r.Context())token := getAPITokenRecordFromRequest(r)- if !h.canAccessOrg(username, token, org) {+ if !h.canAccessOrg(r, username, token, org) {writeErrorResponse(w, http.StatusForbidden, "access_denied", "User is not a member of the organization", nil)return}@@ -460,7 +483,7 @@ func (h *OrgHandlers) HandleInviteMember(w http.ResponseWriter, r *http.Request)orgID := strings.TrimSpace(r.PathValue("id"))if orgID == "default" {- writeErrorResponse(w, http.StatusBadRequest, "default_org_immutable", "Default organization members cannot be managed", nil)+ h.handleAddDefaultOrgMember(w, r)return}@@ -569,7 +592,7 @@ func (h *OrgHandlers) HandleInviteMember(w http.ResponseWriter, r *http.Request)} else {org.PendingInvitations = append(org.PendingInvitations, invitation)}- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "invite_failed", "Failed to update organization members", nil)return}@@ -581,7 +604,7 @@ func (h *OrgHandlers) HandleInviteMember(w http.ResponseWriter, r *http.Request)return}- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "invite_failed", "Failed to update organization members", nil)return}@@ -608,7 +631,7 @@ func (h *OrgHandlers) HandleRemoveMember(w http.ResponseWriter, r *http.Request)return}if orgID == "default" {- writeErrorResponse(w, http.StatusBadRequest, "default_org_immutable", "Default organization members cannot be managed", nil)+ h.handleRemoveDefaultOrgMember(w, r, memberUserID)return}@@ -648,7 +671,7 @@ func (h *OrgHandlers) HandleRemoveMember(w http.ResponseWriter, r *http.Request)}org.Members = nextMembers- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "member_remove_failed", "Failed to update organization members", nil)return}@@ -678,12 +701,22 @@ func (h *OrgHandlers) HandleListInvitations(w http.ResponseWriter, r *http.RequewriteErrorResponse(w, http.StatusForbidden, "session_required", "Session-based user authentication is required", nil)return}- if !org.CanUserIDManage(username) {+ canManage := org.CanUserIDManage(username)+ if org.ID == "default" {+ canManage = h.canManageDefaultOrgMembers(r, username)+ }+ if !canManage {writeErrorResponse(w, http.StatusForbidden, "access_denied", "Admin role required for this organization", nil)return}- writeJSON(w, http.StatusOK, normalizeOrganizationInvitations(org.PendingInvitations, org.Members))+ invitations := normalizeOrganizationInvitations(org.PendingInvitations, org.Members)+ if invitations == nil {+ // An organization with no pending invitations lists none, not null;+ // the access panel rejects a list that is not an array.+ invitations = []models.OrganizationInvitation{}+ }+ writeJSON(w, http.StatusOK, invitations)}func (h *OrgHandlers) HandleRevokeInvitation(w http.ResponseWriter, r *http.Request) {@@ -726,7 +759,7 @@ func (h *OrgHandlers) HandleRevokeInvitation(w http.ResponseWriter, r *http.Requ}org.PendingInvitations = append(org.PendingInvitations[:index], org.PendingInvitations[index+1:]...)- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "invite_failed", "Failed to update organization invitations", nil)return}@@ -818,7 +851,7 @@ func (h *OrgHandlers) HandleAcceptMyInvitation(w http.ResponseWriter, r *http.Reif memberIndex := findOrganizationMemberIndex(org.Members, username); memberIndex >= 0 {if invitationIndex := findOrganizationInvitationIndex(org.PendingInvitations, username); invitationIndex >= 0 {org.PendingInvitations = append(org.PendingInvitations[:invitationIndex], org.PendingInvitations[invitationIndex+1:]...)- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "invite_accept_failed", "Failed to update organization membership", nil)return}@@ -848,7 +881,7 @@ func (h *OrgHandlers) HandleAcceptMyInvitation(w http.ResponseWriter, r *http.ReAddedBy: invitation.InvitedBy,})org.PendingInvitations = append(org.PendingInvitations[:invitationIndex], org.PendingInvitations[invitationIndex+1:]...)- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "invite_accept_failed", "Failed to update organization membership", nil)return}@@ -893,7 +926,7 @@ func (h *OrgHandlers) HandleDeclineMyInvitation(w http.ResponseWriter, r *http.R}org.PendingInvitations = append(org.PendingInvitations[:invitationIndex], org.PendingInvitations[invitationIndex+1:]...)- if err := h.persistence.SaveOrganization(org); err != nil {+ if err := h.saveOrganization(org); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "invite_decline_failed", "Failed to update organization invitations", nil)return}@@ -919,7 +952,7 @@ func (h *OrgHandlers) HandleListShares(w http.ResponseWriter, r *http.Request) {username := auth.GetUser(r.Context())token := getAPITokenRecordFromRequest(r)- if !h.canAccessOrg(username, token, org) {+ if !h.canAccessOrg(r, username, token, org) {writeErrorResponse(w, http.StatusForbidden, "access_denied", "User is not a member of the organization", nil)return}@@ -949,7 +982,7 @@ func (h *OrgHandlers) HandleListIncomingShares(w http.ResponseWriter, r *http.Reusername := auth.GetUser(r.Context())token := getAPITokenRecordFromRequest(r)- if !h.canAccessOrg(username, token, targetOrg) {+ if !h.canAccessOrg(r, username, token, targetOrg) {writeErrorResponse(w, http.StatusForbidden, "access_denied", "User is not a member of the organization", nil)return}@@ -1033,7 +1066,7 @@ func (h *OrgHandlers) HandleAcceptIncomingShare(w http.ResponseWriter, r *http.Rshare.AcceptedBy = usernamesourceOrg.SharedResources[shareIndex] = share- if err := h.persistence.SaveOrganization(sourceOrg); err != nil {+ if err := h.saveOrganization(sourceOrg); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "share_accept_failed", "Failed to accept incoming share", nil)return}@@ -1089,7 +1122,7 @@ func (h *OrgHandlers) HandleDeclineIncomingShare(w http.ResponseWriter, r *http.}sourceOrg.SharedResources = nextShares- if err := h.persistence.SaveOrganization(sourceOrg); err != nil {+ if err := h.saveOrganization(sourceOrg); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "share_decline_failed", "Failed to remove incoming share", nil)return}@@ -1189,7 +1222,7 @@ func (h *OrgHandlers) HandleCreateShare(w http.ResponseWriter, r *http.Request)normalizedShares[i].CreatedBy = username}sourceOrg.SharedResources = normalizedShares- if err := h.persistence.SaveOrganization(sourceOrg); err != nil {+ if err := h.saveOrganization(sourceOrg); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "share_create_failed", "Failed to save organization share", nil)return}@@ -1211,7 +1244,7 @@ func (h *OrgHandlers) HandleCreateShare(w http.ResponseWriter, r *http.Request)}sourceOrg.SharedResources = append(normalizedShares, share)- if err := h.persistence.SaveOrganization(sourceOrg); err != nil {+ if err := h.saveOrganization(sourceOrg); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "share_create_failed", "Failed to save organization share", nil)return}@@ -1268,7 +1301,7 @@ func (h *OrgHandlers) HandleDeleteShare(w http.ResponseWriter, r *http.Request)}sourceOrg.SharedResources = nextShares- if err := h.persistence.SaveOrganization(sourceOrg); err != nil {+ if err := h.saveOrganization(sourceOrg); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "share_delete_failed", "Failed to delete organization share", nil)return}@@ -1330,7 +1363,7 @@ func (h *OrgHandlers) requireMultiTenantGate(w http.ResponseWriter, r *http.Requreturn true}-func (h *OrgHandlers) canAccessOrg(username string, token *config.APITokenRecord, org *models.Organization) bool {+func (h *OrgHandlers) canAccessOrg(r *http.Request, username string, token *config.APITokenRecord, org *models.Organization) bool {if org == nil {return false}@@ -1341,11 +1374,32 @@ func (h *OrgHandlers) canAccessOrg(username string, token *config.APITokenRecordreturn false}if org.ID == "default" {- return true+ if h.accessPolicy == nil {+ return true+ }+ return h.accessPolicy.userDefaultOrgAccess(r.Context(), username).Allowed}return org.CanUserIDAccess(username)}+// defaultOrgMembersManaged reports whether the default organization has a+// member list: only in shared-process multi-organization mode, where the+// default organization is not open to every signed-in user.+func (h *OrgHandlers) defaultOrgMembersManaged() bool {+ return h.accessPolicy != nil && h.accessPolicy.defaultOrgRestricted()+}++// canManageDefaultOrgMembers reports whether the session user may change the+// default organization's members. That is instance administration: a member+// of the default organization, whatever their role, cannot grant access to+// the instance's own estate.+func (h *OrgHandlers) canManageDefaultOrgMembers(r *http.Request, username string) bool {+ if !h.defaultOrgMembersManaged() || h.accessPolicy.instanceAdmin == nil {+ return false+ }+ return h.accessPolicy.instanceAdmin(r.Context(), username)+}+func organizationRoleForUser(org *models.Organization, username string) models.OrganizationRole {if org == nil || strings.TrimSpace(username) == "" {return ""@@ -1576,3 +1630,191 @@ func isValidOrganizationID(orgID string) bool {}return organizationIDPattern.MatchString(orgID)}++// loadDefaultOrganizationMembers strictly loads the default organization's+// metadata for a membership change. A missing org.json starts an empty member+// list; any other failure stops the change rather than overwriting a file+// that could not be read.+func (h *OrgHandlers) loadDefaultOrganizationMembers() (*models.Organization, error) {+ if h.persistence == nil {+ return nil, errors.New("organization persistence is not configured")+ }+ org, err := h.persistence.LoadOrganizationStrict("default")+ if err != nil {+ if !errors.Is(err, os.ErrNotExist) {+ return nil, err+ }+ org = &models.Organization{ID: "default", DisplayName: "default"}+ }+ if org == nil {+ return nil, errOrgNotFound+ }+ org.ID = "default"+ if strings.TrimSpace(org.DisplayName) == "" {+ org.DisplayName = org.ID+ }+ normalizeOrganization(org)+ return org, nil+}++// requireDefaultOrgMemberManager admits an instance administrator to change+// the default organization's members, and only in multi-organization mode.+func (h *OrgHandlers) requireDefaultOrgMemberManager(w http.ResponseWriter, r *http.Request) (string, bool) {+ if !h.defaultOrgMembersManaged() {+ writeErrorResponse(w, http.StatusBadRequest, "default_org_immutable", "Default organization members cannot be managed", nil)+ return "", false+ }+ username := auth.GetUser(r.Context())+ token := getAPITokenRecordFromRequest(r)+ if token != nil || strings.HasPrefix(username, "token:") {+ writeErrorResponse(w, http.StatusForbidden, "session_required", "Session-based user authentication is required", nil)+ return "", false+ }+ if username == "" {+ writeErrorResponse(w, http.StatusUnauthorized, "authentication_required", "Authentication required", nil)+ return "", false+ }+ if !h.canManageDefaultOrgMembers(r, username) {+ writeErrorResponse(w, http.StatusForbidden, "access_denied", "Instance administrator required to manage default organization members", nil)+ return "", false+ }+ return username, true+}++// handleAddDefaultOrgMember grants a user access to the default organization.+// An instance administrator's grant takes effect at once rather than as an+// invitation. Default-organization members are viewers: instance RBAC roles+// govern what they can do, and membership never confers organization+// management.+func (h *OrgHandlers) handleAddDefaultOrgMember(w http.ResponseWriter, r *http.Request) {+ username, ok := h.requireDefaultOrgMemberManager(w, r)+ if !ok {+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, orgRequestBodyLimit)+ var req inviteMemberRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)+ return+ }+ req.UserID = strings.TrimSpace(req.UserID)+ if req.UserID == "" {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_user", "Member user ID is required", nil)+ return+ }+ if req.Role == "" {+ req.Role = models.OrgRoleViewer+ }+ if models.NormalizeOrganizationRole(req.Role) != models.OrgRoleViewer {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_role", "Default organization members are viewers; instance roles control what they can do", nil)+ return+ }++ defaultOrgMembershipMu.Lock()+ defer defaultOrgMembershipMu.Unlock()+ org, err := h.loadDefaultOrganizationMembers()+ if err != nil {+ h.writeLoadOrgError(w, err)+ return+ }+ if findOrganizationMemberIndex(org.Members, req.UserID) >= 0 {+ writeJSON(w, http.StatusOK, organizationAccessMutationResponse{+ Kind: "member",+ Member: organizationMemberPointer(org.Members, req.UserID),+ })+ return+ }+ if enforceUserLimitForMemberAdd(w, r.Context(), org) {+ return+ }++ org.Members = append(org.Members, models.OrganizationMember{+ UserID: req.UserID,+ Role: models.OrgRoleViewer,+ AddedAt: time.Now().UTC(),+ AddedBy: username,+ })+ if index := findOrganizationInvitationIndex(org.PendingInvitations, req.UserID); index >= 0 {+ org.PendingInvitations = append(org.PendingInvitations[:index], org.PendingInvitations[index+1:]...)+ }+ if err := h.persistence.SaveOrganization(org); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "invite_failed", "Failed to update organization members", nil)+ return+ }+ log.Info().+ Str("org_id", "default").+ Str("user_id", req.UserID).+ Str("granted_by", username).+ Msg("Granted default organization access")++ writeJSON(w, http.StatusOK, organizationAccessMutationResponse{+ Kind: "member",+ Member: organizationMemberPointer(org.Members, req.UserID),+ })+}++// handleRemoveDefaultOrgMember revokes a user's default-organization access.+// Open WebSocket and SSE reads re-check the policy and end within+// orgAccessRecheckInterval.+func (h *OrgHandlers) handleRemoveDefaultOrgMember(w http.ResponseWriter, r *http.Request, memberUserID string) {+ username, ok := h.requireDefaultOrgMemberManager(w, r)+ if !ok {+ return+ }++ defaultOrgMembershipMu.Lock()+ defer defaultOrgMembershipMu.Unlock()+ org, err := h.loadDefaultOrganizationMembers()+ if err != nil {+ h.writeLoadOrgError(w, err)+ return+ }+ index := findOrganizationMemberIndex(org.Members, memberUserID)+ if index < 0 {+ writeErrorResponse(w, http.StatusNotFound, "member_not_found", "Member not found", nil)+ return+ }+ org.Members = append(org.Members[:index], org.Members[index+1:]...)+ if org.OwnerUserID == memberUserID {+ // Ownership of the default organization is not an access grant to+ // keep; normalization would otherwise restore the member row.+ org.OwnerUserID = ""+ }+ if err := h.persistence.SaveOrganization(org); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "member_remove_failed", "Failed to update organization members", nil)+ return+ }+ log.Info().+ Str("org_id", "default").+ Str("user_id", memberUserID).+ Str("revoked_by", username).+ Msg("Revoked default organization access")++ w.WriteHeader(http.StatusNoContent)+}++// saveOrganization saves a handler's organization snapshot. The default+// organization's members and owner are an access grant changed only under+// defaultOrgMembershipMu, so a save from an older snapshot, such as a share or+// invitation change, keeps the current members instead of restoring revoked+// ones.+func (h *OrgHandlers) saveOrganization(org *models.Organization) error {+ if org == nil || org.ID != "default" {+ return h.persistence.SaveOrganization(org)+ }+ defaultOrgMembershipMu.Lock()+ defer defaultOrgMembershipMu.Unlock()+ current, err := h.persistence.LoadOrganizationStrict("default")+ switch {+ case err == nil:+ org.Members = current.Members+ org.OwnerUserID = current.OwnerUserID+ case errors.Is(err, os.ErrNotExist):+ org.Members = nil+ org.OwnerUserID = ""+ default:+ return err+ }+ return h.persistence.SaveOrganization(org)+}diff --git a/internal/api/org_handlers_test.go b/internal/api/org_handlers_test.goindex f2d0b11085..303e1b5e41 100644--- a/internal/api/org_handlers_test.go+++ b/internal/api/org_handlers_test.go@@ -1459,3 +1459,31 @@ func acceptIncomingShareForTest(t *testing.T, h *OrgHandlers, orgID, username, s}return share}++// An organization with no pending invitations lists none as an empty array;+// the access panel refuses a list that is not an array.+func TestHandleListInvitationsListsNoneAsEmptyArray(t *testing.T) {+ previous := IsMultiTenantEnabled()+ SetMultiTenantEnabled(true)+ t.Cleanup(func() { SetMultiTenantEnabled(previous) })+ t.Setenv("PULSE_DEV", "true")++ persistence := config.NewMultiTenantPersistence(t.TempDir())+ if err := persistence.SaveOrganization(&models.Organization{+ ID: "quiet", DisplayName: "Quiet", OwnerUserID: "alice",+ Members: []models.OrganizationMember{{UserID: "alice", Role: models.OrgRoleOwner}},+ }); err != nil {+ t.Fatalf("save organization: %v", err)+ }+ h := NewOrgHandlers(persistence, nil)++ req := httptest.NewRequest(http.MethodGet, "/api/orgs/quiet/invitations", nil)+ req = req.WithContext(internalauth.WithUser(req.Context(), "alice"))+ req.SetPathValue("id", "quiet")+ rec := httptest.NewRecorder()+ h.HandleListInvitations(rec, req)++ if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != "[]" {+ t.Fatalf("listing invitations: %d %q, want an empty array", rec.Code, rec.Body.String())+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex b16874978a..795b89d330 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -172,6 +172,7 @@ type Router struct {lifecycleMu sync.MutexlifecycleStopped boolhostedMode bool+ orgAccess *DefaultAuthorizationChecker // organization access policy every caller sharesstripeWebhookHandlers *StripeWebhookHandlerspatrolLifecycleMu sync.MutexstartedPatrolOrgs map[string]bool@@ -262,8 +263,10 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monitstartedPatrolOrgs: make(map[string]bool),}r.ensureChartService()+ r.orgAccess = newOrgAccessChecker(cfg, r.multiTenant, r.hostedMode)if r.wsHub != nil {r.wsHub.SetTrustedProxyChecker(isTrustedProxyIP)+ r.wsHub.SetOrgAuthChecker(r.orgAccess)}if r.hostedMode {// Use defaults: 2000 req/min per org.@@ -289,6 +292,9 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit} else {auth.SetManager(defaultRBACManager)log.Info().Msg("Canonical RBAC store initialized")+ if err := migrateDefaultOrgAccess(r.multiTenant, defaultRBACManager, r.config, r.hostedMode); err != nil {+ log.Error().Err(err).Msg("Default organization access migration failed; it will retry on the next start")+ }}// Initialize SSO service managers@@ -331,14 +337,9 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit// Create tenant middleware with authorization checker.// In hosted mode, tenant routing uses subscription lifecycle checks instead of FeatureMultiTenant.- var orgLoader OrganizationLoader- if r.multiTenant != nil {- orgLoader = NewMultiTenantOrganizationLoader(r.multiTenant)- }- authChecker := NewAuthorizationChecker(orgLoader)tenantMiddleware := NewTenantMiddlewareWithConfig(TenantMiddlewareConfig{Persistence: r.multiTenant,- AuthChecker: authChecker,+ AuthChecker: r.orgAccess,HostedMode: r.hostedMode,})@@ -521,8 +522,7 @@ func (r *Router) setupRoutes() {}reconcile(r.monitor)})- actionOrgChecker := NewAuthorizationChecker(NewMultiTenantOrganizationLoader(r.multiTenant))- actionAuth := actionAuthority{authorizer: r.authorizer, orgChecker: actionOrgChecker}+ actionAuth := actionAuthority{authorizer: r.authorizer, orgChecker: r.orgAccess}r.resourceHandlers.SetActionAuthorizers(actionAuth, actionAuth)r.attentionHandlers.SetActionDependencies(r.resourceHandlers, actionAuth)r.maintenanceSentinel = r.buildMaintenanceVerificationSentinel()@@ -627,6 +627,7 @@ func (r *Router) setupRoutes() {rbacProvider := r.rbacProviderorgHandlers := NewOrgHandlers(r.multiTenant, r.mtMonitor, rbacProvider)orgHandlers.SetHostedMode(r.hostedMode)+ orgHandlers.SetAccessPolicy(r.orgAccess)orgHandlers.SetOnDelete(func(ctx context.Context, orgID string) error {return r.CleanupTenant(ctx, orgID)})diff --git a/internal/api/router_helpers_more_test.go b/internal/api/router_helpers_more_test.goindex 84f218cade..6035802cd7 100644--- a/internal/api/router_helpers_more_test.go+++ b/internal/api/router_helpers_more_test.go@@ -587,3 +587,25 @@ func TestPublicURLTokenCapturePreservesTokenRefusals(t *testing.T) {})}}++// The router builds one organization access policy and shares it with tenant+// selection, action authority, the organization handlers and the WebSocket+// hub, so they cannot disagree about who may use the default organization.+func TestNewRouterSharesOrgAccessPolicy(t *testing.T) {+ previous := IsMultiTenantEnabled()+ SetMultiTenantEnabled(true)+ t.Cleanup(func() { SetMultiTenantEnabled(previous) })+ t.Setenv("PULSE_DEV", "true")++ dataDir := t.TempDir()+ router := newMultiTenantRouter(t, &config.Config{DataPath: dataDir, ConfigPath: dataDir, AuthUser: "admin"})+ if router.orgAccess == nil || router.orgAccess.instanceAdmin == nil {+ t.Fatal("router must build the shared organization access policy")+ }+ if !router.orgAccess.CheckAccess(nil, "admin", "default").Allowed {+ t.Fatal("instance administrator must reach the default organization")+ }+ if router.orgAccess.CheckAccess(nil, "bob", "default").Allowed {+ t.Fatal("a user without membership must not reach the default organization")+ }+}diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.goindex 72a597a078..0b60238692 100644--- a/internal/api/security_setup_fix.go+++ b/internal/api/security_setup_fix.go@@ -1,6 +1,7 @@package apiimport (+ "context""encoding/json""fmt""net/http"@@ -271,10 +272,12 @@ func sessionUserCarriesAdminPrivileges(cfg *config.Config, sessionUser string) breturn false}-// sessionUserHasRBACAdminGrant reports whether the user's effective RBAC-// permissions include an allow of the admin action on all resources — the-// shape of the built-in Administrator role that SSO group role mappings-// assign. A missing manager or empty assignment simply reports false.+// sessionUserHasRBACAdminGrant reports whether the user's RBAC policy allows+// the admin action on all resources — the shape of the built-in Administrator+// role that SSO group role mappings assign. It is the same evaluation route+// authorization uses: inherited roles count, an explicit deny wins, and a+// conditional grant does not apply without its attributes. A missing manager+// or empty assignment simply reports false.func sessionUserHasRBACAdminGrant(username string) bool {username = strings.TrimSpace(username)if username == "" {@@ -284,15 +287,9 @@ func sessionUserHasRBACAdminGrant(username string) bool {if manager == nil {return false}- for _, perm := range manager.GetUserPermissions(username) {- if strings.EqualFold(perm.Effect, internalauth.EffectDeny) {- continue- }- if perm.Action == "admin" && perm.Resource == "*" {- return true- }- }- return false+ ctx := internalauth.WithUser(context.Background(), username)+ allowed, err := internalauth.NewPolicyEvaluator(manager).Authorize(ctx, "admin", "*")+ return err == nil && allowed}// ensureSettingsScope guards instance administration. A token caller needs thediff --git a/internal/api/security_setup_fix_test.go b/internal/api/security_setup_fix_test.goindex c98663149d..23208ace05 100644--- a/internal/api/security_setup_fix_test.go+++ b/internal/api/security_setup_fix_test.go@@ -812,3 +812,52 @@ func TestValidateBcryptHash(t *testing.T) {})}}++// The instance-admin grant uses the same policy evaluation as route+// authorization: inherited roles count, an explicit deny wins, and a+// conditional grant needs its attributes.+func TestSessionUserHasRBACAdminGrantFollowsPolicyEvaluation(t *testing.T) {+ manager, err := internalauth.NewSQLiteManager(internalauth.SQLiteManagerConfig{DataDir: t.TempDir()})+ if err != nil {+ t.Fatalf("new sqlite manager: %v", err)+ }+ t.Cleanup(func() { _ = manager.Close() })+ original := internalauth.GetManager()+ internalauth.SetManager(manager)+ t.Cleanup(func() { internalauth.SetManager(original) })++ roles := []internalauth.Role{+ {ID: "ops-admin", Name: "Ops admin", Permissions: []internalauth.Permission{{Action: "admin", Resource: "*"}}},+ {ID: "ops-lead", Name: "Ops lead", ParentID: "ops-admin"},+ {ID: "no-admin", Name: "No admin", Permissions: []internalauth.Permission{{Action: "admin", Resource: "*", Effect: internalauth.EffectDeny}}},+ {ID: "tagged-admin", Name: "Tagged admin", Permissions: []internalauth.Permission{{Action: "admin", Resource: "*", Conditions: map[string]string{"tag": "lab"}}}},+ }+ for _, role := range roles {+ if err := manager.SaveRole(role); err != nil {+ t.Fatalf("save role %s: %v", role.ID, err)+ }+ }+ assign := func(user string, roleIDs ...string) {+ t.Helper()+ if err := manager.UpdateUserRoles(user, roleIDs); err != nil {+ t.Fatalf("assign %s: %v", user, err)+ }+ }+ assign("direct", "ops-admin")+ assign("inherited", "ops-lead")+ assign("denied", "ops-admin", "no-admin")+ assign("conditional", "tagged-admin")++ if !sessionUserHasRBACAdminGrant("direct") {+ t.Fatal("direct admin grant must count")+ }+ if !sessionUserHasRBACAdminGrant("inherited") {+ t.Fatal("inherited admin grant must count")+ }+ if sessionUserHasRBACAdminGrant("denied") {+ t.Fatal("an explicit admin deny must win over an allow")+ }+ if sessionUserHasRBACAdminGrant("conditional") {+ t.Fatal("a conditional admin grant must not apply without its attributes")+ }+}diff --git a/internal/api/tenant_user_membership_test.go b/internal/api/tenant_user_membership_test.goindex ab62249156..403367b5db 100644--- a/internal/api/tenant_user_membership_test.go+++ b/internal/api/tenant_user_membership_test.go@@ -251,14 +251,19 @@ func TestMultiTenantListOrgsShowsOnlyMemberOrganizations(t *testing.T) {return ids}- if got := listVisibleOrgIDs("alice"); !slices.Equal(got, []string{"default", "org-a", "org-shared"}) {- t.Fatalf("visible orgs for alice = %v, want %v", got, []string{"default", "org-a", "org-shared"})+ // Multi-organization mode limits the default organization to instance+ // administrators and its members, so tenant members do not see it.+ if got := listVisibleOrgIDs("alice"); !slices.Equal(got, []string{"org-a", "org-shared"}) {+ t.Fatalf("visible orgs for alice = %v, want %v", got, []string{"org-a", "org-shared"})}- if got := listVisibleOrgIDs("bob"); !slices.Equal(got, []string{"default", "org-b", "org-shared"}) {- t.Fatalf("visible orgs for bob = %v, want %v", got, []string{"default", "org-b", "org-shared"})+ if got := listVisibleOrgIDs("bob"); !slices.Equal(got, []string{"org-b", "org-shared"}) {+ t.Fatalf("visible orgs for bob = %v, want %v", got, []string{"org-b", "org-shared"})}- if got := listVisibleOrgIDs("charlie"); !slices.Equal(got, []string{"default"}) {- t.Fatalf("visible orgs for charlie = %v, want %v", got, []string{"default"})+ if got := listVisibleOrgIDs("charlie"); len(got) != 0 {+ t.Fatalf("visible orgs for charlie = %v, want none", got)+ }+ if got := listVisibleOrgIDs("admin"); !slices.Equal(got, []string{"default"}) {+ t.Fatalf("visible orgs for admin = %v, want %v", got, []string{"default"})}}diff --git a/internal/api/token_stream_lifetime.go b/internal/api/token_stream_lifetime.goindex bd93cf3ae9..66943be635 100644--- a/internal/api/token_stream_lifetime.go+++ b/internal/api/token_stream_lifetime.go@@ -23,11 +23,12 @@ func retainTokenStreamAuthority(cfg *config.Config, scope string, instanceAdminfunc retainTokenStreamAuthorityForScopes(cfg *config.Config, scopes []string, instanceAdmin bool, next http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {revalidate := tokenStreamSnapshotRevalidator(cfg, r, scopes...)- sessionAllowed := sessionReadRevalidator(r)+ sessionAllowed := combineAuthorization(sessionReadRevalidator(r), orgAccessRevalidator(r))allowed := func() bool {if revalidate == nil {// Proxy/basic/bypass admission stays with the route. A- // session read retains its exact admitted session instance.+ // session read retains its exact admitted session instance,+ // and a signed-in user keeps the organization access policy.return sessionAllowed == nil || sessionAllowed()}current, ok := revalidate()diff --git a/internal/api/token_stream_lifetime_test.go b/internal/api/token_stream_lifetime_test.goindex 6c4d621d9f..0991306de5 100644--- a/internal/api/token_stream_lifetime_test.go+++ b/internal/api/token_stream_lifetime_test.go@@ -610,3 +610,32 @@ func TestTokenStreamWriterPreservesDeadlineControlWithoutEscape(t *testing.T) {t.Fatal("withdrawn control reached transport or retained live request")}}++// A signed-in user's stream follows the organization access policy: a user who+// cannot use the request's organization is refused before anything streams.+func TestRetainTokenStreamAuthorityAppliesOrgAccessPolicy(t *testing.T) {+ installTestRBACManager(t)+ enableSharedMultiOrgForTest(t)+ persistence, checker := newOrgAccessFixture(t, false)+ saveDefaultOrgMembers(t, persistence, "dave")++ streamed := 0+ handler := retainTokenStreamAuthority(&config.Config{}, config.ScopeMonitoringRead, false, func(w http.ResponseWriter, r *http.Request) {+ streamed+++ w.WriteHeader(http.StatusOK)+ })+ serve := func(user string) int {+ req := httptest.NewRequest(http.MethodGet, "/api/agent/events", nil)+ ctx := context.WithValue(internalauth.WithUser(req.Context(), user), OrgIDContextKey, "default")+ rec := httptest.NewRecorder()+ handler(rec, req.WithContext(withOrgAccessChecker(ctx, checker)))+ return rec.Code+ }++ if code := serve("dave"); code != http.StatusOK || streamed != 1 {+ t.Fatalf("default member stream: status %d, streamed %d", code, streamed)+ }+ if code := serve("bob"); code != http.StatusUnauthorized || streamed != 1 {+ t.Fatalf("tenant-only user stream: status %d, streamed %d, want refusal", code, streamed)+ }+}diff --git a/internal/api/websocket_auth.go b/internal/api/websocket_auth.goindex 16fbcd6010..a679415046 100644--- a/internal/api/websocket_auth.go+++ b/internal/api/websocket_auth.go@@ -10,11 +10,14 @@ func monitoringWebSocketAuthorization(cfg *config.Config, req *http.Request) fun// The socket writer outlives this HTTP request. Give it an immutable// request copy, not one its returning middleware may still be observing.revalidate := monitoringTokenSnapshotRevalidator(cfg, req.Clone(req.Context()))+ // A signed-in user's socket also follows the organization access policy,+ // so membership removal or lost default-organization access ends it.+ orgAccess := orgAccessRevalidator(req)if revalidate == nil {- return sessionReadRevalidator(req)+ return combineAuthorization(sessionReadRevalidator(req), orgAccess)}- return func() bool {+ return combineAuthorization(func() bool {_, ok := revalidate()return ok- }+ }, orgAccess)}diff --git a/internal/websocket/hub.go b/internal/websocket/hub.goindex fb839b0a93..20800aa328 100644--- a/internal/websocket/hub.go+++ b/internal/websocket/hub.go@@ -595,6 +595,12 @@ type OrgAuthChecker interface {CanAccessOrg(userID string, token interface{}, orgID string) bool}+// OrgAuthContextChecker is an OrgAuthChecker whose decision can depend on+// request-bound authority, such as a proxy-authenticated administrator.+type OrgAuthContextChecker interface {+ CanAccessOrgContext(ctx context.Context, userID string, token interface{}, orgID string) bool+}+// MultiTenantCheckResult contains the result of a multi-tenant check.type MultiTenantCheckResult struct {Allowed bool@@ -1105,30 +1111,38 @@ func (h *Hub) HandleWebSocketWithAuthorization(w http.ResponseWriter, r *http.Rereturn}}+ }- // Authorization check - auth context should already be set by AuthContextMiddleware- if authChecker != nil {- // Get user and token from context (set by AuthContextMiddleware)- userID := getUserFromContext(r.Context())- token := getAPITokenFromContext(r.Context())-- if !authChecker.CanAccessOrg(userID, token, orgID) {- audit.Log(- "websocket_org_access_denied",- userID,- extractPeerIP(r.RemoteAddr),- r.URL.Path,- false,- fmt.Sprintf("org_id=%s", orgID),- )-- log.Warn().- Str("org_id", orgID).- Str("user_id", userID).- Msg("WebSocket connection denied - unauthorized org access")- http.Error(w, "Unauthorized to access organization", http.StatusForbidden)- return- }+ // Authorization check - auth context should already be set by+ // AuthContextMiddleware. Non-default organizations always require it. The+ // default organization is checked whenever a principal is present: in+ // multi-organization mode it is not open to every signed-in user, while an+ // installation without authentication has no principal to check.+ userID := getUserFromContext(r.Context())+ token := getAPITokenFromContext(r.Context())+ if authChecker != nil && (orgID != "default" || userID != "" || token != nil) {+ allowed := false+ if contextChecker, ok := authChecker.(OrgAuthContextChecker); ok {+ allowed = contextChecker.CanAccessOrgContext(r.Context(), userID, token, orgID)+ } else {+ allowed = authChecker.CanAccessOrg(userID, token, orgID)+ }+ if !allowed {+ audit.Log(+ "websocket_org_access_denied",+ userID,+ extractPeerIP(r.RemoteAddr),+ r.URL.Path,+ false,+ fmt.Sprintf("org_id=%s", orgID),+ )++ log.Warn().+ Str("org_id", orgID).+ Str("user_id", userID).+ Msg("WebSocket connection denied - unauthorized org access")+ http.Error(w, "Unauthorized to access organization", http.StatusForbidden)+ return}}diff --git a/internal/websocket/hub_test.go b/internal/websocket/hub_test.goindex 6e38d1b0aa..f33ca70e27 100644--- a/internal/websocket/hub_test.go+++ b/internal/websocket/hub_test.go@@ -1,6 +1,7 @@package websocketimport (+ "context""encoding/json""errors""math"@@ -15,6 +16,7 @@ import (gorillawebsocket "github.com/gorilla/websocket""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth")func TestNormalClientCloseIsNotAnError(t *testing.T) {@@ -1556,3 +1558,64 @@ func TestClientWriterRevalidatesIdleConnection(t *testing.T) {t.Fatalf("idle authorization calls = %d, want 1", calls.Load())}}++type contextOrgAuthChecker struct {+ allow bool+ calls int+ lastOrg string+ lastUser string+ sawCtx bool+}++func (c *contextOrgAuthChecker) CanAccessOrg(string, interface{}, string) bool {+ panic("the hub must prefer the context-aware check")+}++func (c *contextOrgAuthChecker) CanAccessOrgContext(ctx context.Context, userID string, _ interface{}, orgID string) bool {+ c.calls+++ c.lastOrg = orgID+ c.lastUser = userID+ c.sawCtx = ctx != nil && auth.GetUser(ctx) == userID+ return c.allow+}++// In multi-organization mode the default organization is not open to every+// signed-in user, so the hub checks it like any other organization.+func TestHandleWebSocket_ChecksDefaultOrgForSignedInUsers(t *testing.T) {+ setAuditLogger(t, &testAuditLogger{})+ hub := NewHub(nil)+ checker := &contextOrgAuthChecker{allow: false}+ hub.SetOrgAuthChecker(checker)++ req := httptest.NewRequest(http.MethodGet, "http://example.com/ws", nil)+ req.Header.Set("X-Pulse-Org-ID", "default")+ req = req.WithContext(auth.WithUser(req.Context(), "bob"))+ rec := httptest.NewRecorder()+ hub.HandleWebSocket(rec, req)++ if rec.Code != http.StatusForbidden {+ t.Fatalf("status %d, want 403", rec.Code)+ }+ if checker.calls != 1 || checker.lastOrg != "default" || checker.lastUser != "bob" || !checker.sawCtx {+ t.Fatalf("unexpected check: %+v", checker)+ }+}++// An installation without authentication has no principal to check.+func TestHandleWebSocket_SkipsDefaultOrgCheckWithoutPrincipal(t *testing.T) {+ hub := NewHub(nil)+ checker := &contextOrgAuthChecker{allow: false}+ hub.SetOrgAuthChecker(checker)++ req := httptest.NewRequest(http.MethodGet, "http://example.com/ws", nil)+ req.Header.Set("X-Pulse-Org-ID", "default")+ rec := httptest.NewRecorder()+ hub.HandleWebSocket(rec, req)++ if checker.calls != 0 {+ t.Fatalf("default org without a principal must not be checked, got %d calls", checker.calls)+ }+ if rec.Code == http.StatusForbidden {+ t.Fatal("unauthenticated installation must not be refused by the org check")+ }+}