Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Require target-organization approval for org shares

rcourtmanc0ac25131697
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8180e88ebc..9b689fa17a 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -197,6 +197,14 @@ an add-only capacity posture.
6. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.
The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.
The same shared-helper rule now covers SSO outbound discovery and metadata fetches plus credential-file loads in `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`: lifecycle-adjacent setup or auth work may depend on that shared trust boundary, but it must not fork a second HTTP client, redirect policy, or file-read rule inside lifecycle-local flows.
+ The same shared-helper rule also covers organization membership and
+ cross-organization sharing transport in `internal/api/org_handlers.go` plus
+ adjacent route wiring. Lifecycle surfaces may coexist on the same settings
+ shell, but they must not reinterpret pending-versus-accepted org-share
+ state as install authority, monitored-system admission truth, or enroll-time
+ access control; target-org approval remains organization-settings plus
+ security/privacy ownership even when the implementation moves through the
+ shared backend API tree.
6. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
7. Add or change the unified agent CLI entrypoint, version/help exit semantics, or startup argument/error routing through `cmd/pulse-agent/main.go`.
8. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index b330c8a814..da7ac256f4 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -203,6 +203,15 @@ the canonical monitored-system blocked payload.
and the Patrol runtime-remediation destination shared with `/api/settings/ai`, so summary actions and runtime-finding actions may reuse the governed provider-settings route while still presenting that destination to Patrol operators as Patrol provider configuration instead of generic `AI Settings` copy
and the Patrol route-shell destination itself, so the thin page shell at `frontend-modern/src/pages/AIIntelligence.tsx` may continue to bridge the shared AI-runtime payload boundary while exposing `/patrol` as the canonical product route and preserving `/ai` only as a compatibility redirect
9. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`
+ That same shared org-management client boundary now owns target-consent
+ sharing semantics across `frontend-modern/src/api/orgs.ts`,
+ `internal/api/org_handlers.go`, and the shared org route wiring. Cross-org
+ share creation must remain a pending request until the target organization
+ accepts it, the payload must preserve `status`, `acceptedAt`, and
+ `acceptedBy`, and widening an accepted share's requested role must reset the
+ share back to `pending`. Downstream settings surfaces must not infer live
+ access from share creation alone or recreate manager-only pending-share
+ visibility rules locally.
10. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, and `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`
That same shared token contract also owns audit scope separation: audit event, verification, summary, export, and unified action/export audit reads must require the dedicated `audit:read` scope instead of reusing broader monitoring or settings-read token grants.
11. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install state owner, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and install presentation through `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`. Phase 9 retired the InfrastructureOperationsController shell and the useInfrastructureReportingState reporting path; they must not be reintroduced, and aggregator-backed reporting reads are owned by `frontend-modern/src/components/Settings/useConnectionsLedger.ts` under the frontend-primitives contract.
@@ -2867,6 +2876,20 @@ semantics at the API boundary: `/api/orgs/{id}/shares/incoming` must hide
shares whose `accessRole` exceeds the caller's effective role in the target
organization instead of leaking share metadata that the caller cannot
legitimately accept or use.
+That same inbound-sharing contract now also carries explicit target-org
+consent semantics. `POST /api/orgs/{id}/shares` must create pending share
+requests rather than granting live access immediately, target-org owners or
+admins must accept or decline those requests through
+`POST /api/orgs/{id}/shares/incoming/{shareId}/accept` and
+`DELETE /api/orgs/{id}/shares/incoming/{shareId}`, and
+`/api/orgs/{id}/shares/incoming` must expose pending requests only to those
+target-org managers. Once accepted, the payload must preserve `status`,
+`acceptedAt`, and `acceptedBy`, and accepted shares may remain visible only to
+members whose effective role satisfies the share's `accessRole`.
+Updating an already accepted share must also preserve that consent boundary:
+changing the requested `accessRole` resets the share to `pending` and clears
+the acceptance metadata so a source org cannot silently widen an approved
+grant without a new target-side approval.
Organization membership and authorization payloads now also follow an explicit
live-role contract: `/api/orgs` must list only organizations the caller
currently belongs to, and org-management endpoints must reflect member
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index f36d3ea7ce..903a1be9aa 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -190,6 +190,14 @@ work extends shared components instead of creating new local variants.
canonical settings-shell tests must not bounce an allowed organization
route back to `Infrastructure` just because nav filtering has not yet
surfaced that tab.
+ That same settings-shell boundary also owns authenticated operator identity
+ propagation into organization panels.
+ `frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx`
+ must derive the effective username from the resolved security status
+ (`proxyAuthUsername`, then `ssoSessionUsername`, then `authUsername`) and
+ pass that identity into the organization overview, access, and sharing
+ panels so deep-linked organization routes do not collapse into anonymous
+ read-only shells under proxy-auth, SSO, or local-auth sessions.
That same shared session-presentation boundary also owns alerts read-only
posture: `/alerts` may continue exposing reporting tabs such as overview and
history, but activation controls plus configuration routes must collapse out
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index 6c4ab547c8..5a716238cd 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -9,7 +9,7 @@
"contract_file": "docs/release-control/v6/internal/subsystems/organization-settings.md",
"status_file": "docs/release-control/v6/internal/status.json",
"registry_file": "docs/release-control/v6/internal/subsystems/registry.json",
- "dependency_subsystem_ids": []
+ "dependency_subsystem_ids": ["frontend-primitives"]
}
```
@@ -17,7 +17,7 @@
Own organization role/share semantics and the canonical settings surfaces that
let users review organization metadata, manage membership, assign roles, and
-create cross-organization shares.
+create, review, and approve cross-organization shares.
## Canonical Files
@@ -40,22 +40,23 @@ create cross-organization shares.
17. `frontend-modern/src/components/Settings/RBACFeatureGateSection.tsx`
18. `frontend-modern/src/components/Settings/RolesEditorDialog.tsx`
19. `frontend-modern/src/components/Settings/RolesPanel.tsx`
-20. `frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts`
-21. `frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts`
-22. `frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts`
-23. `frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx`
-24. `frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx`
-25. `frontend-modern/src/components/Settings/useRBACFeatureGateState.ts`
-26. `frontend-modern/src/components/Settings/useRolesPanelState.ts`
-27. `frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts`
-28. `frontend-modern/src/utils/organizationRolePresentation.ts`
-29. `frontend-modern/src/utils/organizationSettingsPresentation.ts`
-30. `frontend-modern/src/utils/orgUtils.ts`
-31. `internal/api/access_control_handlers.go`
-32. `internal/api/enterprise_extension_rbac_admin.go`
-33. `internal/api/org_handlers.go`
-34. `internal/api/org_lifecycle_handlers.go`
-35. `internal/models/organization.go`
+20. `frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx`
+21. `frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts`
+22. `frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts`
+23. `frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts`
+24. `frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx`
+25. `frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx`
+26. `frontend-modern/src/components/Settings/useRBACFeatureGateState.ts`
+27. `frontend-modern/src/components/Settings/useRolesPanelState.ts`
+28. `frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts`
+29. `frontend-modern/src/utils/organizationRolePresentation.ts`
+30. `frontend-modern/src/utils/organizationSettingsPresentation.ts`
+31. `frontend-modern/src/utils/orgUtils.ts`
+32. `internal/api/access_control_handlers.go`
+33. `internal/api/enterprise_extension_rbac_admin.go`
+34. `internal/api/org_handlers.go`
+35. `internal/api/org_lifecycle_handlers.go`
+36. `internal/models/organization.go`
## Shared Boundaries
@@ -69,7 +70,7 @@ create cross-organization shares.
## Extension Points
1. Add or change organization role and share semantics through `internal/models/organization.go`
-2. Add or change organization access, overview, sharing, RBAC feature-gating, role-management, or user-assignment presentation through `frontend-modern/src/components/Settings/OrganizationAccessPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessLoadingState.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessInvitationsSection.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewLoadingState.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewDetailsSection.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewMembersSection.tsx`, `frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx`, `frontend-modern/src/components/Settings/OrganizationSharingLoadingState.tsx`, `frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx`, `frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx`, `frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts`, `frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts`, `frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts`, `frontend-modern/src/components/Settings/RBACFeatureGateSection.tsx`, `frontend-modern/src/components/Settings/RolesPanel.tsx`, `frontend-modern/src/components/Settings/RolesEditorDialog.tsx`, `frontend-modern/src/components/Settings/useRBACFeatureGateState.ts`, `frontend-modern/src/components/Settings/useRolesPanelState.ts`, `frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx`, `frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx`, and `frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts`
+2. Add or change organization access, overview, sharing, RBAC feature-gating, role-management, or user-assignment presentation through `frontend-modern/src/components/Settings/OrganizationAccessPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessLoadingState.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessManagementSection.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessInvitationsSection.tsx`, `frontend-modern/src/components/Settings/OrganizationAccessMembersSection.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewLoadingState.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewDetailsSection.tsx`, `frontend-modern/src/components/Settings/OrganizationOverviewMembersSection.tsx`, `frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx`, `frontend-modern/src/components/Settings/OrganizationSharingLoadingState.tsx`, `frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx`, `frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx`, `frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx`, `frontend-modern/src/components/Settings/useOrganizationAccessPanelState.ts`, `frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts`, `frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts`, `frontend-modern/src/components/Settings/RBACFeatureGateSection.tsx`, `frontend-modern/src/components/Settings/RolesPanel.tsx`, `frontend-modern/src/components/Settings/RolesEditorDialog.tsx`, `frontend-modern/src/components/Settings/useRBACFeatureGateState.ts`, `frontend-modern/src/components/Settings/useRolesPanelState.ts`, `frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx`, `frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx`, and `frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts`
3. Route organization and RBAC frontend transport changes through `frontend-modern/src/api/orgs.ts` and `frontend-modern/src/api/rbac.ts`
4. Keep backend organization management and lifecycle handlers aligned through `internal/api/org_handlers.go` and `internal/api/org_lifecycle_handlers.go`
5. Keep RBAC role, assignment, and admin recovery transport aligned through `internal/api/access_control_handlers.go` and `internal/api/enterprise_extension_rbac_admin.go`
@@ -132,6 +133,17 @@ Incoming share visibility is part of that same boundary as well: a recipient
must only see inbound shares whose requested `accessRole` is satisfied by the
user's effective membership role in the target organization, using the shared
role comparator instead of handler-local owner/admin shortcuts.
+Cross-organization sharing itself now follows an explicit target-consent
+contract instead of unilateral source-side grant semantics. Creating a share
+from one organization must persist a `pending` request, not live access, until
+an owner or admin in the target organization accepts it through the canonical
+incoming-share transport. Pending incoming shares remain visible only to those
+target-org managers, while accepted shares remain visible to members whose
+effective role satisfies the share's `accessRole`.
+That same contract also governs share mutations after acceptance. Changing an
+accepted share's requested `accessRole` must clear the old acceptance metadata
+and move the share back to `pending`, so a source org cannot silently widen a
+previously approved grant without renewed target-org consent.
Hosted organization membership and billing routes now also follow this owned
semantics boundary: for hosted tenant orgs, `internal/api/org_handlers.go`
must authorize organization operations from the seeded org membership and the
@@ -183,6 +195,12 @@ The sharing surface now follows the same extracted-owner pattern: the panel is
the shell, `useOrganizationSharingPanelState.ts` owns the API-backed runtime,
and the loading, create, outgoing, and incoming views each live in dedicated
section owners instead of staying collapsed into one file.
+That same shell contract now also depends on the shared settings panel registry
+context. `frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx`
+must pass the effective authenticated username from `SecurityStatus` into the
+organization overview, access, and sharing panels so membership-derived owner
+and admin actions render consistently for local auth, proxy-auth, and SSO
+sessions.
The RBAC settings area now follows the same extracted-owner pattern as the
other modernized settings surfaces: `RBACFeatureGateSection.tsx` owns the
shared paywall CTA rendering, `useRBACFeatureGateState.ts` owns the shared
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 44f9b522c1..8c32aa9f8c 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -74,6 +74,12 @@ querying, and the operator-facing storage health presentation layer.
provider-backed recovery: storage and recovery must treat `truenas_disabled`
as an explicit platform opt-out, not as the baseline onboarding state for a
supported platform.
+ That same adjacent API boundary also owns organization-share target-consent
+ semantics. When `internal/api/org_handlers.go` and adjacent route wiring
+ evolve cross-organization sharing, storage and recovery may consume the
+ resulting org-scoped access only after the canonical target organization has
+ accepted the share; they must not treat pending share requests as live
+ recovery access or invent storage-local approval bypasses.
That same adjacent API boundary also owns signed release-asset download
continuity when shared helpers serve installer or unified-agent assets:
storage- and recovery-adjacent callers may reuse the shared
diff --git a/frontend-modern/src/api/__tests__/orgs.test.ts b/frontend-modern/src/api/__tests__/orgs.test.ts
index 7aaa38b4e0..c36573d510 100644
--- a/frontend-modern/src/api/__tests__/orgs.test.ts
+++ b/frontend-modern/src/api/__tests__/orgs.test.ts
@@ -260,6 +260,34 @@ describe('OrgsAPI', () => {
});
});
+ describe('acceptIncomingShare', () => {
+ it('accepts a pending incoming share', async () => {
+ const mockShare = { id: 'share-1', status: 'accepted' };
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockShare);
+
+ const result = await OrgsAPI.acceptIncomingShare('org-1', 'share-1');
+
+ expect(apiFetchJSON).toHaveBeenCalledWith(
+ '/api/orgs/org-1/shares/incoming/share-1/accept',
+ expect.objectContaining({ method: 'POST', skipOrgContext: true }),
+ );
+ expect(result).toEqual(mockShare);
+ });
+ });
+
+ describe('declineIncomingShare', () => {
+ it('declines or removes an incoming share', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(undefined);
+
+ await OrgsAPI.declineIncomingShare('org-1', 'share-1');
+
+ expect(apiFetchJSON).toHaveBeenCalledWith(
+ '/api/orgs/org-1/shares/incoming/share-1',
+ expect.objectContaining({ method: 'DELETE', skipOrgContext: true }),
+ );
+ });
+ });
+
describe('deleteShare', () => {
it('deletes a resource share', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce(undefined);
diff --git a/frontend-modern/src/api/orgs.ts b/frontend-modern/src/api/orgs.ts
index 33118d0312..e1eae11e7c 100644
--- a/frontend-modern/src/api/orgs.ts
+++ b/frontend-modern/src/api/orgs.ts
@@ -1,6 +1,7 @@
import { apiFetchJSON } from '@/utils/apiClient';
export type OrganizationRole = 'owner' | 'admin' | 'editor' | 'viewer';
+export type OrganizationShareStatus = 'pending' | 'accepted';
export interface OrganizationMember {
userId: string;
@@ -42,8 +43,11 @@ export interface OrganizationShare {
resourceId: string;
resourceName?: string;
accessRole: Exclude<OrganizationRole, 'owner'> | 'viewer';
+ status: OrganizationShareStatus;
createdAt: string;
createdBy: string;
+ acceptedAt?: string;
+ acceptedBy?: string;
}
export interface IncomingOrganizationShare extends OrganizationShare {
@@ -88,12 +92,9 @@ export const OrgsAPI = {
}),
listPendingInvitations: (id: string) =>
- apiFetchJSON<OrganizationInvitation[]>(
- `/api/orgs/${encodeURIComponent(id)}/invitations`,
- {
- skipOrgContext: true,
- },
- ),
+ apiFetchJSON<OrganizationInvitation[]>(`/api/orgs/${encodeURIComponent(id)}/invitations`, {
+ skipOrgContext: true,
+ }),
listMyInvitations: () =>
apiFetchJSON<UserOrganizationInvitation[]>('/api/org-invitations', {
@@ -101,14 +102,11 @@ export const OrgsAPI = {
}),
inviteMember: (id: string, payload: { userId: string; role: OrganizationRole }) =>
- apiFetchJSON<OrganizationAccessMutationResult>(
- `/api/orgs/${encodeURIComponent(id)}/members`,
- {
- method: 'POST',
- body: JSON.stringify(payload),
- skipOrgContext: true,
- },
- ),
+ apiFetchJSON<OrganizationAccessMutationResult>(`/api/orgs/${encodeURIComponent(id)}/members`, {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ skipOrgContext: true,
+ }),
acceptMyInvitation: (id: string) =>
apiFetchJSON<OrganizationAccessMutationResult>(
@@ -126,14 +124,11 @@ export const OrgsAPI = {
}),
updateMemberRole: (id: string, payload: { userId: string; role: OrganizationRole }) =>
- apiFetchJSON<OrganizationAccessMutationResult>(
- `/api/orgs/${encodeURIComponent(id)}/members`,
- {
- method: 'POST',
- body: JSON.stringify(payload),
- skipOrgContext: true,
- },
- ),
+ apiFetchJSON<OrganizationAccessMutationResult>(`/api/orgs/${encodeURIComponent(id)}/members`, {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ skipOrgContext: true,
+ }),
revokeInvitation: (id: string, userId: string) =>
apiFetchJSON<void>(
@@ -166,6 +161,24 @@ export const OrgsAPI = {
},
),
+ acceptIncomingShare: (id: string, shareId: string) =>
+ apiFetchJSON<OrganizationShare>(
+ `/api/orgs/${encodeURIComponent(id)}/shares/incoming/${encodeURIComponent(shareId)}/accept`,
+ {
+ method: 'POST',
+ skipOrgContext: true,
+ },
+ ),
+
+ declineIncomingShare: (id: string, shareId: string) =>
+ apiFetchJSON<void>(
+ `/api/orgs/${encodeURIComponent(id)}/shares/incoming/${encodeURIComponent(shareId)}`,
+ {
+ method: 'DELETE',
+ skipOrgContext: true,
+ },
+ ),
+
createShare: (
id: string,
payload: {
diff --git a/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx b/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx
index 5e69a03be1..6f10f3a599 100644
--- a/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx
+++ b/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx
@@ -1,8 +1,12 @@
-import { Component } from 'solid-js';
+import { Component, Show } from 'solid-js';
import { PulseDataGrid } from '@/components/shared/PulseDataGrid';
import { normalizeOrganizationShareRole } from '@/utils/organizationRolePresentation';
import { formatOrgDate, roleBadgeClass } from '@/utils/orgUtils';
-import { getOrganizationIncomingSharesEmptyState } from '@/utils/organizationSettingsPresentation';
+import {
+ getOrganizationIncomingSharesEmptyState,
+ getOrganizationShareStatusDescription,
+ getOrganizationShareStatusLabel,
+} from '@/utils/organizationSettingsPresentation';
import type { useOrganizationSharingPanelState } from './useOrganizationSharingPanelState';
interface OrganizationIncomingSharesSectionProps {
@@ -11,57 +15,117 @@ interface OrganizationIncomingSharesSectionProps {
export const OrganizationIncomingSharesSection: Component<
OrganizationIncomingSharesSectionProps
-> = (props) => (
- <div class="space-y-2 p-4 sm:p-6">
- <h4 class="text-sm font-semibold text-base-content">Incoming Shares</h4>
- <div class="mt-4 -mx-4 sm:mx-0 overflow-x-auto w-full">
- <PulseDataGrid
- data={props.state.incomingShares()}
- columns={[
- {
- key: 'sourceOrg',
- label: 'Source Org',
- render: (share) => (
- <span class="text-base-content">{share.sourceOrgName || share.sourceOrgId}</span>
- ),
- },
- {
- key: 'resource',
- label: 'Resource',
- render: (share) => (
- <div class="flex flex-col">
- <span class="text-base-content">{share.resourceName || share.resourceId}</span>
- <span class="text-xs text-muted">
- {share.resourceType}:{share.resourceId}
- </span>
- </div>
- ),
- },
- {
- key: 'accessRole',
- label: 'Access',
- render: (share) => {
- const role = normalizeOrganizationShareRole(share.accessRole);
- return (
- <span
- class={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${roleBadgeClass(role)}`}
- >
- {role}
- </span>
- );
+> = (props) => {
+ const statusBadgeClass = (status: 'pending' | 'accepted') =>
+ status === 'pending'
+ ? 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200'
+ : 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200';
+
+ return (
+ <div class="space-y-2 p-4 sm:p-6">
+ <h4 class="text-sm font-semibold text-base-content">Incoming Shares</h4>
+ <div class="mt-4 -mx-4 sm:mx-0 overflow-x-auto w-full">
+ <PulseDataGrid
+ data={props.state.incomingShares()}
+ columns={[
+ {
+ key: 'sourceOrg',
+ label: 'Source Org',
+ render: (share) => (
+ <span class="text-base-content">{share.sourceOrgName || share.sourceOrgId}</span>
+ ),
+ },
+ {
+ key: 'resource',
+ label: 'Resource',
+ render: (share) => (
+ <div class="flex flex-col">
+ <span class="text-base-content">{share.resourceName || share.resourceId}</span>
+ <span class="text-xs text-muted">
+ {share.resourceType}:{share.resourceId}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: 'accessRole',
+ label: 'Access',
+ render: (share) => {
+ const role = normalizeOrganizationShareRole(share.accessRole);
+ return (
+ <span
+ class={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${roleBadgeClass(role)}`}
+ >
+ {role}
+ </span>
+ );
+ },
+ },
+ {
+ key: 'status',
+ label: 'Status',
+ render: (share) => (
+ <div class="flex flex-col gap-1">
+ <span
+ class={`inline-flex w-fit rounded-full px-2 py-0.5 text-xs font-medium ${statusBadgeClass(share.status)}`}
+ >
+ {getOrganizationShareStatusLabel(share.status)}
+ </span>
+ <span class="text-xs text-muted">
+ {getOrganizationShareStatusDescription(
+ share.status,
+ share.acceptedAt,
+ share.acceptedBy,
+ )}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: 'createdAt',
+ label: 'Requested',
+ render: (share) => <span class="text-muted">{formatOrgDate(share.createdAt)}</span>,
+ },
+ {
+ key: 'actions',
+ label: 'Actions',
+ align: 'right',
+ render: (share) => (
+ <Show when={props.state.canManageCurrentOrg()}>
+ <div class="flex items-center justify-end gap-2">
+ <Show when={share.status === 'pending'}>
+ <button
+ type="button"
+ onClick={() => {
+ void props.state.acceptIncomingShare(share);
+ }}
+ disabled={props.state.saving()}
+ class="inline-flex items-center rounded-md px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-50 dark:text-emerald-300 dark:hover:bg-emerald-900 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ Accept
+ </button>
+ </Show>
+ <button
+ type="button"
+ onClick={() => {
+ void props.state.declineIncomingShare(share);
+ }}
+ disabled={props.state.saving()}
+ class="inline-flex items-center rounded-md px-2 py-1 text-xs font-medium text-red-600 hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {share.status === 'pending' ? 'Decline' : 'Remove'}
+ </button>
+ </div>
+ </Show>
+ ),
},
- },
- {
- key: 'createdAt',
- label: 'Shared',
- render: (share) => <span class="text-muted">{formatOrgDate(share.createdAt)}</span>,
- },
- ]}
- keyExtractor={(share) => share.id}
- emptyState={getOrganizationIncomingSharesEmptyState()}
- desktopMinWidth="620px"
- class="border-x-0 sm:border-x sm:border-t sm:border-b sm:rounded-md border-y border-border"
- />
+ ]}
+ keyExtractor={(share) => share.id}
+ emptyState={getOrganizationIncomingSharesEmptyState()}
+ desktopMinWidth="980px"
+ class="border-x-0 sm:border-x sm:border-t sm:border-b sm:rounded-md border-y border-border"
+ />
+ </div>
</div>
- </div>
-);
+ );
+};
diff --git a/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx b/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx
index 0a3e525df7..ceb548d8d3 100644
--- a/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx
+++ b/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx
@@ -2,7 +2,11 @@ import { Component, Show } from 'solid-js';
import { PulseDataGrid } from '@/components/shared/PulseDataGrid';
import { normalizeOrganizationShareRole } from '@/utils/organizationRolePresentation';
import { formatOrgDate, roleBadgeClass } from '@/utils/orgUtils';
-import { getOrganizationOutgoingSharesEmptyState } from '@/utils/organizationSettingsPresentation';
+import {
+ getOrganizationOutgoingSharesEmptyState,
+ getOrganizationShareStatusDescription,
+ getOrganizationShareStatusLabel,
+} from '@/utils/organizationSettingsPresentation';
import Trash2 from 'lucide-solid/icons/trash-2';
import type { useOrganizationSharingPanelState } from './useOrganizationSharingPanelState';
@@ -12,79 +16,106 @@ interface OrganizationOutgoingSharesSectionProps {
export const OrganizationOutgoingSharesSection: Component<
OrganizationOutgoingSharesSectionProps
-> = (props) => (
- <div class="space-y-2 p-4 sm:p-6">
- <h4 class="text-sm font-semibold text-base-content">Outgoing Shares</h4>
- <div class="mt-4 -mx-4 sm:mx-0 overflow-x-auto w-full">
- <PulseDataGrid
- data={props.state.outgoingShares()}
- columns={[
- {
- key: 'resourceName',
- label: 'Resource',
- render: (share) => (
- <div class="flex flex-col">
- <span class="text-base-content">{share.resourceName || share.resourceId}</span>
- <span class="text-xs text-muted">
- {share.resourceType}:{share.resourceId}
- </span>
- </div>
- ),
- },
- {
- key: 'targetOrgId',
- label: 'Target Org',
- render: (share) => (
- <span class="text-base-content">
- {props.state.orgNameById().get(share.targetOrgId) || share.targetOrgId}
- </span>
- ),
- },
- {
- key: 'accessRole',
- label: 'Access',
- render: (share) => {
- const role = normalizeOrganizationShareRole(share.accessRole);
- return (
- <span
- class={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${roleBadgeClass(role)}`}
- >
- {role}
+> = (props) => {
+ const statusBadgeClass = (status: 'pending' | 'accepted') =>
+ status === 'pending'
+ ? 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200'
+ : 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200';
+
+ return (
+ <div class="space-y-2 p-4 sm:p-6">
+ <h4 class="text-sm font-semibold text-base-content">Outgoing Shares</h4>
+ <div class="mt-4 -mx-4 sm:mx-0 overflow-x-auto w-full">
+ <PulseDataGrid
+ data={props.state.outgoingShares()}
+ columns={[
+ {
+ key: 'resourceName',
+ label: 'Resource',
+ render: (share) => (
+ <div class="flex flex-col">
+ <span class="text-base-content">{share.resourceName || share.resourceId}</span>
+ <span class="text-xs text-muted">
+ {share.resourceType}:{share.resourceId}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: 'targetOrgId',
+ label: 'Target Org',
+ render: (share) => (
+ <span class="text-base-content">
+ {props.state.orgNameById().get(share.targetOrgId) || share.targetOrgId}
</span>
- );
+ ),
+ },
+ {
+ key: 'accessRole',
+ label: 'Access',
+ render: (share) => {
+ const role = normalizeOrganizationShareRole(share.accessRole);
+ return (
+ <span
+ class={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${roleBadgeClass(role)}`}
+ >
+ {role}
+ </span>
+ );
+ },
+ },
+ {
+ key: 'status',
+ label: 'Status',
+ render: (share) => (
+ <div class="flex flex-col gap-1">
+ <span
+ class={`inline-flex w-fit rounded-full px-2 py-0.5 text-xs font-medium ${statusBadgeClass(share.status)}`}
+ >
+ {getOrganizationShareStatusLabel(share.status)}
+ </span>
+ <span class="text-xs text-muted">
+ {getOrganizationShareStatusDescription(
+ share.status,
+ share.acceptedAt,
+ share.acceptedBy,
+ )}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: 'createdAt',
+ label: 'Requested',
+ render: (share) => <span class="text-muted">{formatOrgDate(share.createdAt)}</span>,
+ },
+ {
+ key: 'actions',
+ label: 'Actions',
+ align: 'right',
+ render: (share) => (
+ <Show when={props.state.canManageCurrentOrg()}>
+ <button
+ type="button"
+ onClick={() => {
+ void props.state.deleteShare(share);
+ }}
+ disabled={props.state.saving()}
+ class="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-red-600 hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <Trash2 class="w-3.5 h-3.5" />
+ Remove
+ </button>
+ </Show>
+ ),
},
- },
- {
- key: 'createdAt',
- label: 'Created',
- render: (share) => <span class="text-muted">{formatOrgDate(share.createdAt)}</span>,
- },
- {
- key: 'actions',
- label: 'Actions',
- align: 'right',
- render: (share) => (
- <Show when={props.state.canManageCurrentOrg()}>
- <button
- type="button"
- onClick={() => {
- void props.state.deleteShare(share);
- }}
- disabled={props.state.saving()}
- class="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-red-600 hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900 disabled:cursor-not-allowed disabled:opacity-60"
- >
- <Trash2 class="w-3.5 h-3.5" />
- Remove
- </button>
- </Show>
- ),
- },
- ]}
- keyExtractor={(share) => share.id}
- emptyState={getOrganizationOutgoingSharesEmptyState()}
- desktopMinWidth="760px"
- class="border-x-0 sm:border-x sm:border-t sm:border-b sm:rounded-md border-y border-border"
- />
+ ]}
+ keyExtractor={(share) => share.id}
+ emptyState={getOrganizationOutgoingSharesEmptyState()}
+ desktopMinWidth="980px"
+ class="border-x-0 sm:border-x sm:border-t sm:border-b sm:rounded-md border-y border-border"
+ />
+ </div>
</div>
- </div>
-);
+ );
+};
diff --git a/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx b/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx
index bb33323085..8ecade94bf 100644
--- a/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx
+++ b/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx
@@ -34,7 +34,7 @@ export const OrganizationSharingPanel: Component<OrganizationSharingPanelProps>
<div class="space-y-6">
<SettingsPanel
title="Organization Sharing"
- description="Share views and resources across organizations with explicit role-based access."
+ description="Share views and resources across organizations with explicit role-based access and target-organization approval."
icon={<Share2 class="w-5 h-5" />}
noPadding
bodyClass="divide-y divide-border"
diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx
index 8720fe6581..c7010e2e1f 100644
--- a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx
@@ -11,6 +11,8 @@ const listMembersMock = vi.fn();
const listOrgsMock = vi.fn();
const listSharesMock = vi.fn();
const listIncomingSharesMock = vi.fn();
+const acceptIncomingShareMock = vi.fn();
+const declineIncomingShareMock = vi.fn();
const createShareMock = vi.fn();
const deleteShareMock = vi.fn();
const isMultiTenantEnabledMock = vi.fn();
@@ -27,6 +29,8 @@ vi.mock('@/api/orgs', () => ({
list: (...args: unknown[]) => listOrgsMock(...args),
listShares: (...args: unknown[]) => listSharesMock(...args),
listIncomingShares: (...args: unknown[]) => listIncomingSharesMock(...args),
+ acceptIncomingShare: (...args: unknown[]) => acceptIncomingShareMock(...args),
+ declineIncomingShare: (...args: unknown[]) => declineIncomingShareMock(...args),
createShare: (...args: unknown[]) => createShareMock(...args),
deleteShare: (...args: unknown[]) => deleteShareMock(...args),
},
@@ -108,6 +112,8 @@ beforeEach(() => {
listOrgsMock.mockReset();
listSharesMock.mockReset();
listIncomingSharesMock.mockReset();
+ acceptIncomingShareMock.mockReset();
+ declineIncomingShareMock.mockReset();
createShareMock.mockReset();
deleteShareMock.mockReset();
isMultiTenantEnabledMock.mockReset();
@@ -127,12 +133,21 @@ beforeEach(() => {
isMultiTenantEnabledMock.mockReturnValue(true);
getOrgIDMock.mockReturnValue('org-a');
eventBusOnMock.mockReturnValue(() => undefined);
+ vi.stubGlobal(
+ 'confirm',
+ vi.fn(() => true),
+ );
orgGetMock.mockResolvedValue(baseOrg);
listMembersMock.mockResolvedValue([]);
listOrgsMock.mockResolvedValue([baseOrg, targetOrg]);
listSharesMock.mockResolvedValue([]);
listIncomingSharesMock.mockResolvedValue([]);
+ acceptIncomingShareMock.mockResolvedValue({
+ id: 'incoming-share-1',
+ status: 'accepted',
+ });
+ declineIncomingShareMock.mockResolvedValue(undefined);
createShareMock.mockResolvedValue({
id: 'share-1',
targetOrgId: 'org-b',
@@ -140,6 +155,7 @@ beforeEach(() => {
resourceId: 'vm-100',
resourceName: 'Alpha VM',
accessRole: 'viewer',
+ status: 'pending',
createdAt: new Date().toISOString(),
createdBy: 'user-1',
});
@@ -148,6 +164,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
+ vi.unstubAllGlobals();
});
describe('OrganizationSharingPanel', () => {
@@ -304,6 +321,61 @@ describe('OrganizationSharingPanel', () => {
});
});
+ it('renders share status and lets target managers accept or decline incoming shares', async () => {
+ listSharesMock.mockResolvedValue([
+ {
+ id: 'share-out-1',
+ targetOrgId: 'org-b',
+ resourceType: 'vm',
+ resourceId: 'vm-100',
+ resourceName: 'Alpha VM',
+ accessRole: 'viewer',
+ status: 'pending',
+ createdAt: '2026-04-20T10:00:00Z',
+ createdBy: 'user-1',
+ },
+ ]);
+ listIncomingSharesMock.mockResolvedValue([
+ {
+ id: 'share-in-1',
+ sourceOrgId: 'org-b',
+ sourceOrgName: 'Organization B',
+ targetOrgId: 'org-a',
+ resourceType: 'view',
+ resourceId: 'alerts-high-cpu',
+ resourceName: 'High CPU',
+ accessRole: 'viewer',
+ status: 'pending',
+ createdAt: '2026-04-20T10:00:00Z',
+ createdBy: 'user-2',
+ },
+ ]);
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(screen.getAllByText('Pending approval').length).toBeGreaterThanOrEqual(2);
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Accept' }));
+
+ await waitFor(() => {
+ expect(acceptIncomingShareMock).toHaveBeenCalledWith('org-a', 'share-in-1');
+ });
+
+ await waitFor(() => {
+ expect((screen.getByRole('button', { name: 'Decline' }) as HTMLButtonElement).disabled).toBe(
+ false,
+ );
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Decline' }));
+
+ await waitFor(() => {
+ expect(declineIncomingShareMock).toHaveBeenCalledWith('org-a', 'share-in-1');
+ });
+ });
+
it('normalizes org scope through the shared helper', () => {
expect(organizationSharingStateSource).toContain('normalizeOrgScope(getOrgID())');
expect(organizationSharingStateSource).not.toContain("getOrgID() || 'default'");
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 16884ad494..b957125849 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -4,6 +4,7 @@ import settingsDialogsSource from '../SettingsDialogs.tsx?raw';
import settingsPageShellSource from '../SettingsPageShell.tsx?raw';
import settingsHeaderMetaSource from '../settingsHeaderMeta.ts?raw';
import settingsNavigationHookSource from '../useSettingsNavigation.ts?raw';
+import settingsPanelRegistryContextSource from '../settingsPanelRegistryContext.tsx?raw';
import infrastructureWorkspaceSource from '../InfrastructureWorkspace.tsx?raw';
import infrastructureWorkspaceModelSource from '../infrastructureWorkspaceModel.ts?raw';
import connectionEditorSource from '../ConnectionEditor/ConnectionEditor.tsx?raw';
@@ -68,6 +69,18 @@ describe('settings architecture guardrails', () => {
expect(settingsSource).toContain('const activeSettingsPanelEntry = createMemo(() => {');
expect(settingsSource).toContain('if (!flatTabs().some((tab) => tab.id === currentTab)) {');
expect(settingsSource).toContain('return settingsPanelRegistry()[currentTab];');
+ expect(settingsPanelRegistryContextSource).toContain(
+ 'params.securityStatus()?.proxyAuthUsername',
+ );
+ expect(settingsPanelRegistryContextSource).toContain(
+ '|| params.securityStatus()?.ssoSessionUsername',
+ );
+ expect(settingsPanelRegistryContextSource).toContain(
+ '|| params.securityStatus()?.authUsername;',
+ );
+ expect(settingsPanelRegistryContextSource).toContain('getOrganizationOverviewPanelProps');
+ expect(settingsPanelRegistryContextSource).toContain('getOrganizationAccessPanelProps');
+ expect(settingsPanelRegistryContextSource).toContain('getOrganizationSharingPanelProps');
});
it('keeps the infrastructure add flow inline on ConnectionEditor instead of retired overlays', () => {
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
new file mode 100644
index 0000000000..aabbb3a48e
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Setter } from 'solid-js';
+import type { SecurityStatus } from '@/types/config';
+import type { SettingsSystemPanels } from '../useSettingsSystemPanels';
+import {
+ buildSettingsPanelRegistryContext,
+ type UseSettingsPanelRegistryParams,
+} from '../settingsPanelRegistryContext';
+
+const noopSetter: Setter<boolean> = () => false;
+
+const systemPanels: SettingsSystemPanels = {
+ systemGeneralPanel: () => null,
+ getNetworkPanelProps: () => ({} as ReturnType<SettingsSystemPanels['getNetworkPanelProps']>),
+ getRecoveryPanelProps: () => ({} as ReturnType<SettingsSystemPanels['getRecoveryPanelProps']>),
+ getUpdatesPanelProps: () => ({} as ReturnType<SettingsSystemPanels['getUpdatesPanelProps']>),
+};
+
+function buildParams(
+ securityStatus: SecurityStatus | null,
+): UseSettingsPanelRegistryParams {
+ return {
+ securityStatus: () => securityStatus,
+ securityStatusLoading: () => false,
+ organizationMonitoredSystemUsage: () => 0,
+ organizationGuestUsage: () => 0,
+ loadSecurityStatus: vi.fn(async () => undefined),
+ showQuickSecuritySetup: () => false,
+ setShowQuickSecuritySetup: noopSetter,
+ showQuickSecurityWizard: () => false,
+ setShowQuickSecurityWizard: noopSetter,
+ showPasswordModal: () => false,
+ setShowPasswordModal: noopSetter,
+ hideLocalLogin: () => false,
+ hideLocalLoginLocked: () => false,
+ savingHideLocalLogin: () => false,
+ handleHideLocalLoginChange: vi.fn(async () => undefined),
+ versionInfo: () => null,
+ getInfrastructurePanelProps: () => ({}),
+ systemPanels,
+ };
+}
+
+describe('buildSettingsPanelRegistryContext', () => {
+ it('passes the effective current user into organization panels', () => {
+ const context = buildSettingsPanelRegistryContext(buildParams({
+ hasAuthentication: true,
+ apiTokenConfigured: false,
+ apiTokenHint: '',
+ requiresAuth: true,
+ credentialsEncrypted: true,
+ exportProtected: true,
+ hasAuditLogging: false,
+ configuredButPendingRestart: false,
+ authUsername: 'local-admin',
+ ssoSessionUsername: 'sso-admin',
+ proxyAuthUsername: 'proxy-admin',
+ }));
+
+ expect(context.getOrganizationOverviewPanelProps()).toMatchObject({ currentUser: 'proxy-admin' });
+ expect(context.getOrganizationAccessPanelProps()).toMatchObject({ currentUser: 'proxy-admin' });
+ expect(context.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: 'proxy-admin' });
+ });
+
+ it('falls back from proxy auth to sso session to local auth username', () => {
+ const ssoContext = buildSettingsPanelRegistryContext(buildParams({
+ hasAuthentication: true,
+ apiTokenConfigured: false,
+ apiTokenHint: '',
+ requiresAuth: true,
+ credentialsEncrypted: true,
+ exportProtected: true,
+ hasAuditLogging: false,
+ configuredButPendingRestart: false,
+ authUsername: 'local-admin',
+ ssoSessionUsername: 'sso-admin',
+ }));
+
+ const localContext = buildSettingsPanelRegistryContext(buildParams({
+ hasAuthentication: true,
+ apiTokenConfigured: false,
+ apiTokenHint: '',
+ requiresAuth: true,
+ credentialsEncrypted: true,
+ exportProtected: true,
+ hasAuditLogging: false,
+ configuredButPendingRestart: false,
+ authUsername: 'local-admin',
+ }));
+
+ expect(ssoContext.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: 'sso-admin' });
+ expect(localContext.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: 'local-admin' });
+ });
+
+ it('leaves currentUser undefined when no authenticated username is available', () => {
+ const context = buildSettingsPanelRegistryContext(buildParams({
+ hasAuthentication: true,
+ apiTokenConfigured: false,
+ apiTokenHint: '',
+ requiresAuth: true,
+ credentialsEncrypted: true,
+ exportProtected: true,
+ hasAuditLogging: false,
+ configuredButPendingRestart: false,
+ }));
+
+ expect(context.getOrganizationOverviewPanelProps()).toMatchObject({ currentUser: undefined });
+ expect(context.getOrganizationAccessPanelProps()).toMatchObject({ currentUser: undefined });
+ expect(context.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: undefined });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index 65204db191..662619255e 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -34,6 +34,10 @@ export function buildSettingsPanelRegistryContext(
params: UseSettingsPanelRegistryParams,
): SettingsPanelRegistryContext {
const settingsCapabilities = () => params.securityStatus()?.settingsCapabilities ?? null;
+ const currentUser = () =>
+ params.securityStatus()?.proxyAuthUsername
+ || params.securityStatus()?.ssoSessionUsername
+ || params.securityStatus()?.authUsername;
const systemAiPanel: Component = () => (
<div class="space-y-6">
@@ -66,9 +70,15 @@ export function buildSettingsPanelRegistryContext(
getNetworkPanelProps: params.systemPanels.getNetworkPanelProps,
getUpdatesPanelProps: params.systemPanels.getUpdatesPanelProps,
getRecoveryPanelProps: params.systemPanels.getRecoveryPanelProps,
- getOrganizationOverviewPanelProps: () => ({}),
- getOrganizationAccessPanelProps: () => ({}),
- getOrganizationSharingPanelProps: () => ({}),
+ getOrganizationOverviewPanelProps: () => ({
+ currentUser: currentUser(),
+ }),
+ getOrganizationAccessPanelProps: () => ({
+ currentUser: currentUser(),
+ }),
+ getOrganizationSharingPanelProps: () => ({
+ currentUser: currentUser(),
+ }),
getOrganizationBillingPanelProps: () => ({
nodeUsage: params.organizationMonitoredSystemUsage(),
guestUsage: params.organizationGuestUsage(),
diff --git a/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts b/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts
index 3ffff2a445..db264069de 100644
--- a/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts
+++ b/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts
@@ -21,6 +21,11 @@ import { normalizeOrgScope } from '@/utils/orgScope';
import { getPreferredResourceDisplayName } from '@/utils/resourceIdentity';
import type { ShareAccessRole } from '@/utils/organizationRolePresentation';
import {
+ getOrganizationIncomingShareAcceptErrorMessage,
+ getOrganizationIncomingShareAcceptSuccessMessage,
+ getOrganizationIncomingShareDeclineConfirmMessage,
+ getOrganizationIncomingShareDeclineErrorMessage,
+ getOrganizationIncomingShareDeclineSuccessMessage,
getOrganizationShareCreateErrorMessage,
getOrganizationShareCreateSuccessMessage,
getOrganizationShareDeleteErrorMessage,
@@ -105,6 +110,17 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel
return map;
});
+ const getShareLabel = (share: {
+ resourceId: string;
+ resourceName?: string;
+ resourceType: string;
+ }): string => {
+ const resourceName = share.resourceName?.trim();
+ if (resourceName) return resourceName;
+ if (share.resourceId.trim() !== '') return share.resourceId;
+ return `${share.resourceType}:${share.resourceId}`;
+ };
+
createEffect(() => {
if (unifiedResourceOptions().length > 0) return;
setManualEntryExpanded(true);
@@ -215,9 +231,7 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel
const hasValidManualType = isCanonicalResourceType(nextResourceType);
const hasValidManualResourceId = nextResourceId !== '';
- setTargetOrgError(
- nextTargetOrgId === '' ? getOrganizationShareTargetOrgRequiredMessage() : '',
- );
+ setTargetOrgError(nextTargetOrgId === '' ? getOrganizationShareTargetOrgRequiredMessage() : '');
if (hasQuickPick) {
setResourceTypeError('');
setResourceIdError('');
@@ -282,6 +296,57 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel
}
};
+ const acceptIncomingShare = async (share: IncomingOrganizationShare) => {
+ const currentOrg = org();
+ if (!currentOrg) return;
+
+ setSaving(true);
+ try {
+ await OrgsAPI.acceptIncomingShare(currentOrg.id, share.id);
+ notificationStore.success(
+ getOrganizationIncomingShareAcceptSuccessMessage(getShareLabel(share)),
+ );
+ await loadShares(currentOrg.id);
+ } catch (error) {
+ logger.error('Failed to accept incoming organization share', error);
+ notificationStore.error(
+ getOrganizationIncomingShareAcceptErrorMessage(
+ error instanceof Error ? error.message : undefined,
+ ),
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const declineIncomingShare = async (share: IncomingOrganizationShare) => {
+ const currentOrg = org();
+ if (!currentOrg) return;
+
+ const shareLabel = getShareLabel(share);
+ if (!confirm(getOrganizationIncomingShareDeclineConfirmMessage(shareLabel, share.status))) {
+ return;
+ }
+
+ setSaving(true);
+ try {
+ await OrgsAPI.declineIncomingShare(currentOrg.id, share.id);
+ notificationStore.success(
+ getOrganizationIncomingShareDeclineSuccessMessage(shareLabel, share.status),
+ );
+ await loadShares(currentOrg.id);
+ } catch (error) {
+ logger.error('Failed to remove incoming organization share', error);
+ notificationStore.error(
+ getOrganizationIncomingShareDeclineErrorMessage(
+ error instanceof Error ? error.message : undefined,
+ ),
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+
onMount(() => {
if (!isMultiTenantEnabled() || presentationPolicyHidesOrganizationSurfaces()) {
setLoading(false);
@@ -297,10 +362,12 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel
return {
accessRole,
+ acceptIncomingShare,
applyResourceQuickPick,
canCreateShare,
canManageCurrentOrg,
createShare,
+ declineIncomingShare,
deleteShare,
incomingShares,
loading,
diff --git a/frontend-modern/src/utils/__tests__/organizationSettingsPresentation.test.ts b/frontend-modern/src/utils/__tests__/organizationSettingsPresentation.test.ts
index 2a6435d563..6cc68a7e3a 100644
--- a/frontend-modern/src/utils/__tests__/organizationSettingsPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/organizationSettingsPresentation.test.ts
@@ -9,6 +9,11 @@ import {
getOrganizationDisplayNameRequiredMessage,
getOrganizationDisplayNameUpdateErrorMessage,
getOrganizationDisplayNameUpdatedMessage,
+ getOrganizationIncomingShareAcceptErrorMessage,
+ getOrganizationIncomingShareAcceptSuccessMessage,
+ getOrganizationIncomingShareDeclineConfirmMessage,
+ getOrganizationIncomingShareDeclineErrorMessage,
+ getOrganizationIncomingShareDeclineSuccessMessage,
getOrganizationIncomingSharesEmptyState,
getOrganizationMemberRemoveConfirmMessage,
getOrganizationMemberRoleUpdateErrorMessage,
@@ -24,6 +29,8 @@ import {
getOrganizationShareDeleteSuccessMessage,
getOrganizationShareInvalidResourceMessage,
getOrganizationShareResourceIdRequiredMessage,
+ getOrganizationShareStatusDescription,
+ getOrganizationShareStatusLabel,
getOrganizationShareTargetOrgDifferentMessage,
getOrganizationShareTargetOrgRequiredMessage,
getOrganizationSettingsLoadErrorMessage,
@@ -80,9 +87,7 @@ describe('organizationSettingsPresentation', () => {
'Unable to update the organization name.',
);
expect(getOrganizationDisplayNameUpdateErrorMessage('bad request')).toBe('bad request');
- expect(getOrganizationDisplayNameUpdatedMessage()).toBe(
- 'Organization name has been updated.',
- );
+ expect(getOrganizationDisplayNameUpdatedMessage()).toBe('Organization name has been updated.');
expect(getOrganizationOverviewManageRequiredMessage()).toBe(
'Admin or owner role required to update organization details.',
);
@@ -96,9 +101,7 @@ describe('organizationSettingsPresentation', () => {
expect(getOrganizationAccessRoleUpdatedMessage('alice', 'admin')).toBe(
'Updated alice to the admin role.',
);
- expect(getOrganizationMemberRoleUpdateErrorMessage()).toBe(
- 'Unable to update the member role.',
- );
+ expect(getOrganizationMemberRoleUpdateErrorMessage()).toBe('Unable to update the member role.');
expect(getOrganizationMemberRoleUpdateErrorMessage('conflict')).toBe('conflict');
expect(getOrganizationAccessMemberAddedMessage('alice', 'viewer')).toBe(
'Added alice as viewer.',
@@ -124,9 +127,43 @@ describe('organizationSettingsPresentation', () => {
expect(getOrganizationShareTargetOrgDifferentMessage()).toBe(
'Target organization must differ from the current organization',
);
- expect(getOrganizationShareCreateSuccessMessage()).toBe('Resource has been shared.');
+ expect(getOrganizationShareCreateSuccessMessage()).toBe(
+ 'Share request sent. A target organization admin must accept it before access becomes active.',
+ );
expect(getOrganizationShareCreateErrorMessage()).toBe('Unable to create the share.');
expect(getOrganizationShareCreateErrorMessage('duplicate')).toBe('duplicate');
+ expect(getOrganizationShareStatusLabel('pending')).toBe('Pending approval');
+ expect(getOrganizationShareStatusLabel('accepted')).toBe('Active');
+ expect(getOrganizationShareStatusDescription('pending')).toBe(
+ 'Waiting for a target organization admin to accept.',
+ );
+ expect(
+ getOrganizationShareStatusDescription('accepted', '2026-04-22T10:30:00Z', 'alice'),
+ ).toContain('Accepted');
+ expect(
+ getOrganizationShareStatusDescription('accepted', '2026-04-22T10:30:00Z', 'alice'),
+ ).toContain('alice');
+ expect(getOrganizationIncomingShareAcceptSuccessMessage('High CPU')).toBe(
+ 'Accepted shared access to High CPU.',
+ );
+ expect(getOrganizationIncomingShareAcceptErrorMessage()).toBe(
+ 'Unable to accept the incoming share.',
+ );
+ expect(getOrganizationIncomingShareDeclineConfirmMessage('High CPU', 'pending')).toBe(
+ 'Decline the share request for High CPU?',
+ );
+ expect(getOrganizationIncomingShareDeclineConfirmMessage('High CPU', 'accepted')).toBe(
+ 'Remove shared access to High CPU?',
+ );
+ expect(getOrganizationIncomingShareDeclineSuccessMessage('High CPU', 'pending')).toBe(
+ 'Declined the share request for High CPU.',
+ );
+ expect(getOrganizationIncomingShareDeclineSuccessMessage('High CPU', 'accepted')).toBe(
+ 'Removed shared access to High CPU.',
+ );
+ expect(getOrganizationIncomingShareDeclineErrorMessage()).toBe(
+ 'Unable to remove the incoming share.',
+ );
expect(getOrganizationShareDeleteSuccessMessage()).toBe('Share has been removed.');
expect(getOrganizationShareDeleteErrorMessage()).toBe('Unable to remove the share.');
expect(getOrganizationShareDeleteErrorMessage('forbidden')).toBe('forbidden');
diff --git a/frontend-modern/src/utils/organizationSettingsPresentation.ts b/frontend-modern/src/utils/organizationSettingsPresentation.ts
index f5d11f6649..659c2a589e 100644
--- a/frontend-modern/src/utils/organizationSettingsPresentation.ts
+++ b/frontend-modern/src/utils/organizationSettingsPresentation.ts
@@ -1,4 +1,5 @@
-import type { OrganizationRole } from '@/api/orgs';
+import type { OrganizationRole, OrganizationShareStatus } from '@/api/orgs';
+import { formatOrgDate } from '@/utils/orgUtils';
export const ORGANIZATION_SETTINGS_UNAVAILABLE_MESSAGE =
'Organization settings are not available on this server.';
@@ -165,13 +166,67 @@ export function getOrganizationShareTargetOrgDifferentMessage(): string {
}
export function getOrganizationShareCreateSuccessMessage(): string {
- return 'Resource has been shared.';
+ return 'Share request sent. A target organization admin must accept it before access becomes active.';
}
export function getOrganizationShareCreateErrorMessage(message?: string): string {
return message || 'Unable to create the share.';
}
+export function getOrganizationShareStatusLabel(status: OrganizationShareStatus): string {
+ return status === 'pending' ? 'Pending approval' : 'Active';
+}
+
+export function getOrganizationShareStatusDescription(
+ status: OrganizationShareStatus,
+ acceptedAt?: string,
+ acceptedBy?: string,
+): string {
+ if (status === 'pending') {
+ return 'Waiting for a target organization admin to accept.';
+ }
+
+ let message = acceptedAt
+ ? `Accepted ${formatOrgDate(acceptedAt)}`
+ : 'Accepted by the target organization';
+ if (acceptedBy) {
+ message += ` by ${acceptedBy}`;
+ }
+ return `${message}.`;
+}
+
+export function getOrganizationIncomingShareAcceptSuccessMessage(resourceLabel: string): string {
+ return `Accepted shared access to ${resourceLabel}.`;
+}
+
+export function getOrganizationIncomingShareAcceptErrorMessage(message?: string): string {
+ return message || 'Unable to accept the incoming share.';
+}
+
+export function getOrganizationIncomingShareDeclineConfirmMessage(
+ resourceLabel: string,
+ status: OrganizationShareStatus,
+): string {
+ if (status === 'pending') {
+ return `Decline the share request for ${resourceLabel}?`;
+ }
+ return `Remove shared access to ${resourceLabel}?`;
+}
+
+export function getOrganizationIncomingShareDeclineSuccessMessage(
+ resourceLabel: string,
+ status: OrganizationShareStatus,
+): string {
+ if (status === 'pending') {
+ return `Declined the share request for ${resourceLabel}.`;
+ }
+ return `Removed shared access to ${resourceLabel}.`;
+}
+
+export function getOrganizationIncomingShareDeclineErrorMessage(message?: string): string {
+ return message || 'Unable to remove the incoming share.';
+}
+
export function getOrganizationShareDeleteSuccessMessage(): string {
return 'Share has been removed.';
}
diff --git a/internal/api/org_handlers.go b/internal/api/org_handlers.go
index d8d39f5ffb..4cd3430a4a 100644
--- a/internal/api/org_handlers.go
+++ b/internal/api/org_handlers.go
@@ -912,6 +912,7 @@ func (h *OrgHandlers) HandleListIncomingShares(w http.ResponseWriter, r *http.Re
return
}
targetRole := organizationRoleForUser(targetOrg, username)
+ canManageTargetOrg := targetOrg.CanUserManage(username)
orgs, err := h.persistence.ListOrganizations()
if err != nil {
@@ -928,7 +929,11 @@ func (h *OrgHandlers) HandleListIncomingShares(w http.ResponseWriter, r *http.Re
if share.TargetOrgID != targetOrgID {
continue
}
- if !models.OrganizationRoleAtLeast(targetRole, share.AccessRole) {
+ if share.Status == models.OrganizationShareStatusPending {
+ if !canManageTargetOrg {
+ continue
+ }
+ } else if !models.OrganizationRoleAtLeast(targetRole, share.AccessRole) {
continue
}
incoming = append(incoming, incomingOrganizationShare{
@@ -942,6 +947,114 @@ func (h *OrgHandlers) HandleListIncomingShares(w http.ResponseWriter, r *http.Re
writeJSON(w, http.StatusOK, incoming)
}
+func (h *OrgHandlers) HandleAcceptIncomingShare(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if !h.requireMultiTenantGate(w, r) {
+ return
+ }
+
+ targetOrgID := strings.TrimSpace(r.PathValue("id"))
+ shareID := strings.TrimSpace(r.PathValue("shareId"))
+ if shareID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_share", "Share ID is required", nil)
+ return
+ }
+
+ targetOrg, err := h.loadOrganization(targetOrgID)
+ if err != nil {
+ h.writeLoadOrgError(w, err)
+ return
+ }
+
+ 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
+ }
+ if !targetOrg.CanUserManage(username) {
+ writeErrorResponse(w, http.StatusForbidden, "access_denied", "Admin role required for the target organization", nil)
+ return
+ }
+
+ sourceOrg, shareIndex, share, err := h.findIncomingShare(targetOrgID, shareID)
+ if err != nil {
+ h.writeLoadOrgError(w, err)
+ return
+ }
+
+ share.Status = models.OrganizationShareStatusAccepted
+ share.AcceptedAt = time.Now().UTC()
+ share.AcceptedBy = username
+ sourceOrg.SharedResources[shareIndex] = share
+
+ if err := h.persistence.SaveOrganization(sourceOrg); err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "share_accept_failed", "Failed to accept incoming share", nil)
+ return
+ }
+
+ writeJSON(w, http.StatusOK, share)
+}
+
+func (h *OrgHandlers) HandleDeclineIncomingShare(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodDelete {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if !h.requireMultiTenantGate(w, r) {
+ return
+ }
+
+ targetOrgID := strings.TrimSpace(r.PathValue("id"))
+ shareID := strings.TrimSpace(r.PathValue("shareId"))
+ if shareID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_share", "Share ID is required", nil)
+ return
+ }
+
+ targetOrg, err := h.loadOrganization(targetOrgID)
+ if err != nil {
+ h.writeLoadOrgError(w, err)
+ return
+ }
+
+ 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
+ }
+ if !targetOrg.CanUserManage(username) {
+ writeErrorResponse(w, http.StatusForbidden, "access_denied", "Admin role required for the target organization", nil)
+ return
+ }
+
+ sourceOrg, shareIndex, _, err := h.findIncomingShare(targetOrgID, shareID)
+ if err != nil {
+ h.writeLoadOrgError(w, err)
+ return
+ }
+
+ nextShares := make([]models.OrganizationShare, 0, len(sourceOrg.SharedResources)-1)
+ for i, share := range normalizeOrganizationShares(sourceOrg.SharedResources) {
+ if i == shareIndex {
+ continue
+ }
+ nextShares = append(nextShares, share)
+ }
+ sourceOrg.SharedResources = nextShares
+
+ if err := h.persistence.SaveOrganization(sourceOrg); err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "share_decline_failed", "Failed to remove incoming share", nil)
+ return
+ }
+
+ w.WriteHeader(http.StatusNoContent)
+}
+
func (h *OrgHandlers) HandleCreateShare(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -1016,11 +1129,22 @@ func (h *OrgHandlers) HandleCreateShare(w http.ResponseWriter, r *http.Request)
if normalizedShares[i].TargetOrgID == req.TargetOrgID &&
normalizedShares[i].ResourceType == req.ResourceType &&
normalizedShares[i].ResourceID == req.ResourceID {
+ now := time.Now().UTC()
+ acceptedUnchanged := normalizedShares[i].Status == models.OrganizationShareStatusAccepted &&
+ normalizedShares[i].AccessRole == req.AccessRole
normalizedShares[i].AccessRole = req.AccessRole
normalizedShares[i].ResourceName = req.ResourceName
- normalizedShares[i].CreatedBy = username
- if normalizedShares[i].CreatedAt.IsZero() {
- normalizedShares[i].CreatedAt = time.Now().UTC()
+ if !acceptedUnchanged {
+ normalizedShares[i].Status = models.OrganizationShareStatusPending
+ normalizedShares[i].AcceptedAt = time.Time{}
+ normalizedShares[i].AcceptedBy = ""
+ normalizedShares[i].CreatedBy = username
+ normalizedShares[i].CreatedAt = now
+ } else if normalizedShares[i].CreatedAt.IsZero() {
+ normalizedShares[i].CreatedAt = now
+ }
+ if normalizedShares[i].CreatedBy == "" {
+ normalizedShares[i].CreatedBy = username
}
sourceOrg.SharedResources = normalizedShares
if err := h.persistence.SaveOrganization(sourceOrg); err != nil {
@@ -1039,6 +1163,7 @@ func (h *OrgHandlers) HandleCreateShare(w http.ResponseWriter, r *http.Request)
ResourceID: req.ResourceID,
ResourceName: req.ResourceName,
AccessRole: req.AccessRole,
+ Status: models.OrganizationShareStatusPending,
CreatedAt: time.Now().UTC(),
CreatedBy: username,
}
@@ -1108,7 +1233,10 @@ func (h *OrgHandlers) HandleDeleteShare(w http.ResponseWriter, r *http.Request)
w.WriteHeader(http.StatusNoContent)
}
-var errOrgNotFound = errors.New("organization not found")
+var (
+ errOrgNotFound = errors.New("organization not found")
+ errShareNotFound = errors.New("organization share not found")
+)
func (h *OrgHandlers) loadOrganization(orgID string) (*models.Organization, error) {
if !isValidOrganizationID(orgID) {
@@ -1190,6 +1318,8 @@ func (h *OrgHandlers) writeLoadOrgError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, errOrgNotFound):
writeErrorResponse(w, http.StatusNotFound, "not_found", "Organization not found", nil)
+ case errors.Is(err, errShareNotFound):
+ writeErrorResponse(w, http.StatusNotFound, "share_not_found", "Organization share not found", nil)
default:
writeErrorResponse(w, http.StatusInternalServerError, "org_load_failed", "Failed to load organization", nil)
}
@@ -1284,6 +1414,15 @@ func normalizeOrganizationShares(shares []models.OrganizationShare) []models.Org
if share.AccessRole == models.OrgRoleOwner || !models.IsValidOrganizationRole(share.AccessRole) {
share.AccessRole = models.OrgRoleViewer
}
+ share.Status = models.NormalizeOrganizationShareStatus(share.Status)
+ if !models.IsValidOrganizationShareStatus(share.Status) {
+ share.Status = models.OrganizationShareStatusAccepted
+ }
+ share.AcceptedBy = strings.TrimSpace(share.AcceptedBy)
+ if share.Status != models.OrganizationShareStatusAccepted {
+ share.AcceptedAt = time.Time{}
+ share.AcceptedBy = ""
+ }
if share.TargetOrgID == "" || share.ResourceType == "" || share.ResourceID == "" {
continue
}
@@ -1296,6 +1435,31 @@ func normalizeOrganizationShares(shares []models.OrganizationShare) []models.Org
return normalized
}
+func (h *OrgHandlers) findIncomingShare(targetOrgID, shareID string) (*models.Organization, int, models.OrganizationShare, error) {
+ if h.persistence == nil {
+ return nil, -1, models.OrganizationShare{}, errors.New("organization persistence is not configured")
+ }
+
+ orgs, err := h.persistence.ListOrganizations()
+ if err != nil {
+ return nil, -1, models.OrganizationShare{}, err
+ }
+
+ for _, sourceOrg := range orgs {
+ if sourceOrg == nil || sourceOrg.ID == targetOrgID {
+ continue
+ }
+ normalizeOrganization(sourceOrg)
+ for i, share := range sourceOrg.SharedResources {
+ if share.ID == shareID && share.TargetOrgID == targetOrgID {
+ return sourceOrg, i, share, nil
+ }
+ }
+ }
+
+ return nil, -1, models.OrganizationShare{}, errShareNotFound
+}
+
func findOrganizationMemberIndex(members []models.OrganizationMember, userID string) int {
for i := range members {
if members[i].UserID == userID {
diff --git a/internal/api/org_handlers_test.go b/internal/api/org_handlers_test.go
index 0dbca5f793..602dc9c063 100644
--- a/internal/api/org_handlers_test.go
+++ b/internal/api/org_handlers_test.go
@@ -620,7 +620,7 @@ func TestOrgHandlersShareLifecycle(t *testing.T) {
createTargetReq := withUser(
httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"beta","displayName":"Beta"}`)),
- "alice",
+ "bob",
)
createTargetRec := httptest.NewRecorder()
h.HandleCreateOrg(createTargetRec, createTargetReq)
@@ -645,8 +645,17 @@ func TestOrgHandlersShareLifecycle(t *testing.T) {
if share.ID == "" {
t.Fatalf("expected share id")
}
+ if share.Status != models.OrganizationShareStatusPending {
+ t.Fatalf("share status=%q, want %q", share.Status, models.OrganizationShareStatusPending)
+ }
+ if !share.AcceptedAt.IsZero() {
+ t.Fatalf("expected pending share accepted_at to be empty, got %s", share.AcceptedAt)
+ }
+ if share.AcceptedBy != "" {
+ t.Fatalf("expected pending share accepted_by to be empty, got %q", share.AcceptedBy)
+ }
- incomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "alice")
+ incomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "bob")
incomingReq.SetPathValue("id", "beta")
incomingRec := httptest.NewRecorder()
h.HandleListIncomingShares(incomingRec, incomingReq)
@@ -660,6 +669,20 @@ func TestOrgHandlersShareLifecycle(t *testing.T) {
if len(incoming) != 1 || incoming[0].SourceOrgID != "acme" {
t.Fatalf("unexpected incoming shares: %+v", incoming)
}
+ if incoming[0].Status != models.OrganizationShareStatusPending {
+ t.Fatalf("incoming status=%q, want %q", incoming[0].Status, models.OrganizationShareStatusPending)
+ }
+
+ accepted := acceptIncomingShareForTest(t, h, "beta", "bob", share.ID)
+ if accepted.Status != models.OrganizationShareStatusAccepted {
+ t.Fatalf("accepted share status=%q, want %q", accepted.Status, models.OrganizationShareStatusAccepted)
+ }
+ if accepted.AcceptedBy != "bob" {
+ t.Fatalf("accepted share accepted_by=%q, want %q", accepted.AcceptedBy, "bob")
+ }
+ if accepted.AcceptedAt.IsZero() {
+ t.Fatalf("accepted share missing accepted_at")
+ }
deleteShareReq := withUser(httptest.NewRequest(http.MethodDelete, "/api/orgs/acme/shares/"+share.ID, nil), "alice")
deleteShareReq.SetPathValue("id", "acme")
@@ -698,6 +721,8 @@ func TestOrgHandlersIncomingSharesPreserveAccessRole(t *testing.T) {
if createTargetRec.Code != http.StatusCreated {
t.Fatalf("create target failed: %d %s", createTargetRec.Code, createTargetRec.Body.String())
}
+ inviteMemberForTest(t, h, "beta", "bob", "charlie", "editor", http.StatusAccepted)
+ acceptInvitationForTest(t, h, "beta", "charlie")
createShareReq := withUser(
httptest.NewRequest(http.MethodPost, "/api/orgs/acme/shares", bytes.NewBufferString(`{"targetOrgId":"beta","resourceType":"view","resourceId":"shared-view","resourceName":"Shared View","accessRole":"editor"}`)),
@@ -717,8 +742,28 @@ func TestOrgHandlersIncomingSharesPreserveAccessRole(t *testing.T) {
if share.AccessRole != models.OrgRoleEditor {
t.Fatalf("share access_role=%q, want %q", share.AccessRole, models.OrgRoleEditor)
}
+ if share.Status != models.OrganizationShareStatusPending {
+ t.Fatalf("share status=%q, want %q", share.Status, models.OrganizationShareStatusPending)
+ }
- incomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "bob")
+ pendingIncomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "charlie")
+ pendingIncomingReq.SetPathValue("id", "beta")
+ pendingIncomingRec := httptest.NewRecorder()
+ h.HandleListIncomingShares(pendingIncomingRec, pendingIncomingReq)
+ if pendingIncomingRec.Code != http.StatusOK {
+ t.Fatalf("list pending incoming failed: %d %s", pendingIncomingRec.Code, pendingIncomingRec.Body.String())
+ }
+ var pendingIncoming []incomingOrganizationShare
+ if err := json.Unmarshal(pendingIncomingRec.Body.Bytes(), &pendingIncoming); err != nil {
+ t.Fatalf("decode pending incoming: %v", err)
+ }
+ if len(pendingIncoming) != 0 {
+ t.Fatalf("expected pending share to stay hidden from non-managers, got %+v", pendingIncoming)
+ }
+
+ acceptIncomingShareForTest(t, h, "beta", "bob", share.ID)
+
+ incomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "charlie")
incomingReq.SetPathValue("id", "beta")
incomingRec := httptest.NewRecorder()
h.HandleListIncomingShares(incomingRec, incomingReq)
@@ -739,6 +784,9 @@ func TestOrgHandlersIncomingSharesPreserveAccessRole(t *testing.T) {
if incoming[0].AccessRole != models.OrgRoleEditor {
t.Fatalf("incoming access_role=%q, want %q", incoming[0].AccessRole, models.OrgRoleEditor)
}
+ if incoming[0].Status != models.OrganizationShareStatusAccepted {
+ t.Fatalf("incoming status=%q, want %q", incoming[0].Status, models.OrganizationShareStatusAccepted)
+ }
}
func TestOrgHandlersCrossOrgIsolation(t *testing.T) {
@@ -821,6 +869,8 @@ func TestOrgHandlersShareIsolationAcrossOrganizations(t *testing.T) {
if createBetaRec.Code != http.StatusCreated {
t.Fatalf("create beta failed: %d %s", createBetaRec.Code, createBetaRec.Body.String())
}
+ inviteMemberForTest(t, h, "beta", "bob", "charlie", "viewer", http.StatusAccepted)
+ acceptInvitationForTest(t, h, "beta", "charlie")
createShareReq := withUser(
httptest.NewRequest(http.MethodPost, "/api/orgs/acme/shares", bytes.NewBufferString(`{"targetOrgId":"beta","resourceType":"view","resourceId":"r-1","resourceName":"Shared View","accessRole":"viewer"}`)),
@@ -832,20 +882,24 @@ func TestOrgHandlersShareIsolationAcrossOrganizations(t *testing.T) {
if createShareRec.Code != http.StatusCreated {
t.Fatalf("create share failed: %d %s", createShareRec.Code, createShareRec.Body.String())
}
+ var share models.OrganizationShare
+ if err := json.Unmarshal(createShareRec.Body.Bytes(), &share); err != nil {
+ t.Fatalf("decode share: %v", err)
+ }
- bobIncomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "bob")
- bobIncomingReq.SetPathValue("id", "beta")
- bobIncomingRec := httptest.NewRecorder()
- h.HandleListIncomingShares(bobIncomingRec, bobIncomingReq)
- if bobIncomingRec.Code != http.StatusOK {
- t.Fatalf("expected 200 for incoming shares in target org, got %d: %s", bobIncomingRec.Code, bobIncomingRec.Body.String())
+ charlieIncomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "charlie")
+ charlieIncomingReq.SetPathValue("id", "beta")
+ charlieIncomingRec := httptest.NewRecorder()
+ h.HandleListIncomingShares(charlieIncomingRec, charlieIncomingReq)
+ if charlieIncomingRec.Code != http.StatusOK {
+ t.Fatalf("expected 200 for incoming shares in target org, got %d: %s", charlieIncomingRec.Code, charlieIncomingRec.Body.String())
}
var incoming []incomingOrganizationShare
- if err := json.Unmarshal(bobIncomingRec.Body.Bytes(), &incoming); err != nil {
+ if err := json.Unmarshal(charlieIncomingRec.Body.Bytes(), &incoming); err != nil {
t.Fatalf("decode incoming: %v", err)
}
- if len(incoming) != 1 || incoming[0].SourceOrgID != "acme" {
- t.Fatalf("unexpected incoming shares payload: %+v", incoming)
+ if len(incoming) != 0 {
+ t.Fatalf("expected pending incoming shares to stay hidden from non-managers, got %+v", incoming)
}
bobSourceSharesReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/acme/shares", nil), "bob")
@@ -856,12 +910,90 @@ func TestOrgHandlersShareIsolationAcrossOrganizations(t *testing.T) {
t.Fatalf("expected 403 when target org user lists source org shares, got %d: %s", bobSourceSharesRec.Code, bobSourceSharesRec.Body.String())
}
- charlieIncomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "charlie")
- charlieIncomingReq.SetPathValue("id", "beta")
- charlieIncomingRec := httptest.NewRecorder()
- h.HandleListIncomingShares(charlieIncomingRec, charlieIncomingReq)
- if charlieIncomingRec.Code != http.StatusForbidden {
- t.Fatalf("expected 403 when non-member lists incoming shares, got %d: %s", charlieIncomingRec.Code, charlieIncomingRec.Body.String())
+ danaIncomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "dana")
+ danaIncomingReq.SetPathValue("id", "beta")
+ danaIncomingRec := httptest.NewRecorder()
+ h.HandleListIncomingShares(danaIncomingRec, danaIncomingReq)
+ if danaIncomingRec.Code != http.StatusForbidden {
+ t.Fatalf("expected 403 when non-member lists incoming shares, got %d: %s", danaIncomingRec.Code, danaIncomingRec.Body.String())
+ }
+
+ acceptIncomingShareForTest(t, h, "beta", "bob", share.ID)
+
+ acceptedIncomingReq := withUser(httptest.NewRequest(http.MethodGet, "/api/orgs/beta/shares/incoming", nil), "charlie")
+ acceptedIncomingReq.SetPathValue("id", "beta")
+ acceptedIncomingRec := httptest.NewRecorder()
+ h.HandleListIncomingShares(acceptedIncomingRec, acceptedIncomingReq)
+ if acceptedIncomingRec.Code != http.StatusOK {
+ t.Fatalf("expected 200 after share acceptance, got %d: %s", acceptedIncomingRec.Code, acceptedIncomingRec.Body.String())
+ }
+ if err := json.Unmarshal(acceptedIncomingRec.Body.Bytes(), &incoming); err != nil {
+ t.Fatalf("decode accepted incoming: %v", err)
+ }
+ if len(incoming) != 1 || incoming[0].SourceOrgID != "acme" {
+ t.Fatalf("unexpected accepted incoming shares payload: %+v", incoming)
+ }
+}
+
+func TestOrgHandlersDeclineIncomingShareRemovesPendingRequest(t *testing.T) {
+ t.Setenv("PULSE_DEV", "true")
+ defer SetMultiTenantEnabled(false)
+ SetMultiTenantEnabled(true)
+
+ persistence := config.NewMultiTenantPersistence(t.TempDir())
+ h := NewOrgHandlers(persistence, nil)
+
+ createSourceReq := withUser(
+ httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"acme","displayName":"Acme"}`)),
+ "alice",
+ )
+ createSourceRec := httptest.NewRecorder()
+ h.HandleCreateOrg(createSourceRec, createSourceReq)
+ if createSourceRec.Code != http.StatusCreated {
+ t.Fatalf("create source failed: %d %s", createSourceRec.Code, createSourceRec.Body.String())
+ }
+
+ createTargetReq := withUser(
+ httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"beta","displayName":"Beta"}`)),
+ "bob",
+ )
+ createTargetRec := httptest.NewRecorder()
+ h.HandleCreateOrg(createTargetRec, createTargetReq)
+ if createTargetRec.Code != http.StatusCreated {
+ t.Fatalf("create target failed: %d %s", createTargetRec.Code, createTargetRec.Body.String())
+ }
+
+ createShareReq := withUser(
+ httptest.NewRequest(http.MethodPost, "/api/orgs/acme/shares", bytes.NewBufferString(`{"targetOrgId":"beta","resourceType":"view","resourceId":"pending-view","resourceName":"Pending View","accessRole":"viewer"}`)),
+ "alice",
+ )
+ createShareReq.SetPathValue("id", "acme")
+ createShareRec := httptest.NewRecorder()
+ h.HandleCreateShare(createShareRec, createShareReq)
+ if createShareRec.Code != http.StatusCreated {
+ t.Fatalf("create share failed: %d %s", createShareRec.Code, createShareRec.Body.String())
+ }
+
+ var share models.OrganizationShare
+ if err := json.Unmarshal(createShareRec.Body.Bytes(), &share); err != nil {
+ t.Fatalf("decode share: %v", err)
+ }
+
+ req := withUser(httptest.NewRequest(http.MethodDelete, "/api/orgs/beta/shares/incoming/"+share.ID, nil), "bob")
+ req.SetPathValue("id", "beta")
+ req.SetPathValue("shareId", share.ID)
+ rec := httptest.NewRecorder()
+ h.HandleDeclineIncomingShare(rec, req)
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf("decline incoming share failed: %d %s", rec.Code, rec.Body.String())
+ }
+
+ sourceOrg, err := h.loadOrganization("acme")
+ if err != nil {
+ t.Fatalf("load source org: %v", err)
+ }
+ if len(sourceOrg.SharedResources) != 0 {
+ t.Fatalf("expected declined share to be removed from source org, got %+v", sourceOrg.SharedResources)
}
}
@@ -1155,3 +1287,21 @@ func acceptInvitationForTest(t *testing.T, h *OrgHandlers, orgID, username strin
}
return rec
}
+
+func acceptIncomingShareForTest(t *testing.T, h *OrgHandlers, orgID, username, shareID string) models.OrganizationShare {
+ t.Helper()
+ req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs/"+orgID+"/shares/incoming/"+shareID+"/accept", nil), username)
+ req.SetPathValue("id", orgID)
+ req.SetPathValue("shareId", shareID)
+ rec := httptest.NewRecorder()
+ h.HandleAcceptIncomingShare(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("accept incoming share %s for %s returned %d: %s", shareID, username, rec.Code, rec.Body.String())
+ }
+
+ var share models.OrganizationShare
+ if err := json.Unmarshal(rec.Body.Bytes(), &share); err != nil {
+ t.Fatalf("decode accepted share: %v", err)
+ }
+ return share
+}
diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.go
index 27a7b6058e..a097f41f68 100644
--- a/internal/api/router_routes_licensing.go
+++ b/internal/api/router_routes_licensing.go
@@ -80,6 +80,8 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHan
r.mux.HandleFunc("DELETE /api/org-invitations/{id}", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, orgHandlers.HandleDeclineMyInvitation)))
r.mux.HandleFunc("GET /api/orgs/{id}/shares", RequireAuth(r.config, RequireScope(config.ScopeSettingsRead, orgHandlers.HandleListShares)))
r.mux.HandleFunc("GET /api/orgs/{id}/shares/incoming", RequireAuth(r.config, RequireScope(config.ScopeSettingsRead, orgHandlers.HandleListIncomingShares)))
+ r.mux.HandleFunc("POST /api/orgs/{id}/shares/incoming/{shareId}/accept", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, orgHandlers.HandleAcceptIncomingShare)))
+ r.mux.HandleFunc("DELETE /api/orgs/{id}/shares/incoming/{shareId}", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, orgHandlers.HandleDeclineIncomingShare)))
r.mux.HandleFunc("POST /api/orgs/{id}/shares", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, orgHandlers.HandleCreateShare)))
r.mux.HandleFunc("DELETE /api/orgs/{id}/shares/{shareId}", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, orgHandlers.HandleDeleteShare)))
diff --git a/internal/models/organization.go b/internal/models/organization.go
index 6f4c77169e..5c693843fa 100644
--- a/internal/models/organization.go
+++ b/internal/models/organization.go
@@ -28,6 +28,18 @@ const (
OrgStatusPendingDeletion OrgStatus = "pending_deletion"
)
+// OrganizationShareStatus represents the lifecycle state of a cross-org share.
+type OrganizationShareStatus string
+
+const (
+ // OrganizationShareStatusPending requires explicit target-org acceptance
+ // before the share becomes active.
+ OrganizationShareStatusPending OrganizationShareStatus = "pending"
+ // OrganizationShareStatusAccepted is an active share that target-org admins
+ // have already accepted. Empty legacy status values normalize here.
+ OrganizationShareStatusAccepted OrganizationShareStatus = "accepted"
+)
+
// NormalizeOrgStatus canonicalizes lifecycle status values.
// Empty status is treated as active for backward compatibility.
func NormalizeOrgStatus(status OrgStatus) OrgStatus {
@@ -43,6 +55,29 @@ func NormalizeOrgStatus(status OrgStatus) OrgStatus {
}
}
+// NormalizeOrganizationShareStatus canonicalizes share lifecycle values.
+// Empty status is treated as accepted for backward compatibility.
+func NormalizeOrganizationShareStatus(status OrganizationShareStatus) OrganizationShareStatus {
+ switch strings.ToLower(strings.TrimSpace(string(status))) {
+ case "", string(OrganizationShareStatusAccepted):
+ return OrganizationShareStatusAccepted
+ case string(OrganizationShareStatusPending):
+ return OrganizationShareStatusPending
+ default:
+ return OrganizationShareStatus(strings.ToLower(strings.TrimSpace(string(status))))
+ }
+}
+
+// IsValidOrganizationShareStatus reports whether the share status is known.
+func IsValidOrganizationShareStatus(status OrganizationShareStatus) bool {
+ switch NormalizeOrganizationShareStatus(status) {
+ case OrganizationShareStatusPending, OrganizationShareStatusAccepted:
+ return true
+ default:
+ return false
+ }
+}
+
// NormalizeOrganizationRole canonicalizes role values.
func NormalizeOrganizationRole(role OrganizationRole) OrganizationRole {
switch strings.ToLower(strings.TrimSpace(string(role))) {
@@ -145,11 +180,20 @@ type OrganizationShare struct {
// AccessRole defines the access level granted to the target organization.
AccessRole OrganizationRole `json:"accessRole"`
+ // Status tracks whether the target organization has accepted the share.
+ Status OrganizationShareStatus `json:"status"`
+
// CreatedAt is when the share was created.
CreatedAt time.Time `json:"createdAt"`
// CreatedBy is the user ID that created the share.
CreatedBy string `json:"createdBy"`
+
+ // AcceptedAt is when the target organization accepted the share.
+ AcceptedAt time.Time `json:"acceptedAt,omitempty"`
+
+ // AcceptedBy is the target-org admin who accepted the share.
+ AcceptedBy string `json:"acceptedBy,omitempty"`
}
// Organization represents a distinct tenant in the system.
diff --git a/internal/models/organization_additional_test.go b/internal/models/organization_additional_test.go
index 2be72e2ce7..4e3f014250 100644
--- a/internal/models/organization_additional_test.go
+++ b/internal/models/organization_additional_test.go
@@ -124,3 +124,49 @@ func TestNormalizeOrgStatus(t *testing.T) {
})
}
}
+
+func TestNormalizeOrganizationShareStatus(t *testing.T) {
+ testCases := []struct {
+ name string
+ input OrganizationShareStatus
+ output OrganizationShareStatus
+ valid bool
+ }{
+ {
+ name: "empty defaults to accepted",
+ input: "",
+ output: OrganizationShareStatusAccepted,
+ valid: true,
+ },
+ {
+ name: "pending case-insensitive",
+ input: "PENDING",
+ output: OrganizationShareStatusPending,
+ valid: true,
+ },
+ {
+ name: "accepted case-insensitive",
+ input: "Accepted",
+ output: OrganizationShareStatusAccepted,
+ valid: true,
+ },
+ {
+ name: "unknown trimmed and lowered",
+ input: " custom ",
+ output: "custom",
+ valid: false,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := NormalizeOrganizationShareStatus(tc.input)
+ if got != tc.output {
+ t.Fatalf("NormalizeOrganizationShareStatus(%q) = %q, want %q", tc.input, got, tc.output)
+ }
+ if valid := IsValidOrganizationShareStatus(tc.input); valid != tc.valid {
+ t.Fatalf("IsValidOrganizationShareStatus(%q) = %v, want %v", tc.input, valid, tc.valid)
+ }
+ })
+ }
+}
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 2a7e709cb8..b76a748709 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3602,14 +3602,14 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "frontend-modern/src/api/orgs.ts",
- "line": 62,
- "heading_line": 60,
+ "line": 63,
+ "heading_line": 61,
},
{
"heading": "## Extension Points",
"path": "frontend-modern/src/api/orgs.ts",
- "line": 73,
- "heading_line": 69,
+ "line": 74,
+ "heading_line": 70,
},
],
)
@@ -3672,20 +3672,20 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Canonical Files",
"path": "internal/api/access_control_handlers.go",
- "line": 54,
+ "line": 55,
"heading_line": 22,
},
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 64,
- "heading_line": 60,
+ "line": 65,
+ "heading_line": 61,
},
{
"heading": "## Extension Points",
"path": "internal/api/access_control_handlers.go",
- "line": 75,
- "heading_line": 69,
+ "line": 76,
+ "heading_line": 70,
},
],
)
diff --git a/tests/integration/tests/03-multi-tenant.spec.ts b/tests/integration/tests/03-multi-tenant.spec.ts
index 7ed0d28399..2844196580 100644
--- a/tests/integration/tests/03-multi-tenant.spec.ts
+++ b/tests/integration/tests/03-multi-tenant.spec.ts
@@ -6,6 +6,7 @@ import {
ensureAuthenticated,
E2E_CREDENTIALS,
isMultiTenantEnabled,
+ switchOrg,
} from './helpers';
type Organization = {
@@ -39,9 +40,13 @@ type OutgoingShare = {
resourceId: string;
resourceName?: string;
accessRole: string;
+ status?: string;
+ acceptedAt?: string;
+ acceptedBy?: string;
};
type IncomingShare = {
+ id?: string;
sourceOrgId?: string;
sourceOrgID?: string;
sourceOrgName?: string;
@@ -49,6 +54,9 @@ type IncomingShare = {
resourceId: string;
resourceName?: string;
accessRole: string;
+ status?: string;
+ acceptedAt?: string;
+ acceptedBy?: string;
};
type Permission = {
@@ -245,7 +253,7 @@ test.describe('Multi-tenant E2E flows', () => {
expect(payload.code).toBe('self_modification_denied');
});
- test('Scenario 6: cross-org share preserves intended access role', async ({ page }) => {
+ test('Scenario 6: cross-org share preserves intended access role and requires target acceptance', async ({ page }) => {
await ensureAuthenticated(page);
const mtEnabled = await isMultiTenantEnabled(page);
@@ -253,6 +261,8 @@ test.describe('Multi-tenant E2E flows', () => {
const orgA = await createOrg(page, `E2E Share Source ${Date.now()}`);
const orgB = await createOrg(page, `E2E Share Target ${Date.now()}`);
+ const outboundResourceName = `Shared View Outbound ${Date.now()}`;
+ const inboundResourceName = `Shared View Inbound ${Date.now()}`;
try {
const createShareRes = await apiRequest(page, `/api/orgs/${encodeURIComponent(orgA.id)}/shares`, {
@@ -261,7 +271,7 @@ test.describe('Multi-tenant E2E flows', () => {
targetOrgId: orgB.id,
resourceType: 'view',
resourceId: `shared-view-${Date.now()}`,
- resourceName: 'Shared View',
+ resourceName: outboundResourceName,
accessRole: 'editor',
},
headers: { 'Content-Type': 'application/json' },
@@ -271,12 +281,33 @@ test.describe('Multi-tenant E2E flows', () => {
const createdShare = (await createShareRes.json()) as OutgoingShare;
expect(createdShare.targetOrgId).toBe(orgB.id);
expect(createdShare.accessRole).toBe('editor');
+ expect(createdShare.status).toBe('pending');
+
+ const createIncomingShareRes = await apiRequest(
+ page,
+ `/api/orgs/${encodeURIComponent(orgB.id)}/shares`,
+ {
+ method: 'POST',
+ data: {
+ targetOrgId: orgA.id,
+ resourceType: 'view',
+ resourceId: `shared-view-inbound-${Date.now()}`,
+ resourceName: inboundResourceName,
+ accessRole: 'viewer',
+ },
+ headers: { 'Content-Type': 'application/json' },
+ },
+ );
+ expect(createIncomingShareRes.status()).toBe(201);
+ const createdIncomingShare = (await createIncomingShareRes.json()) as OutgoingShare;
+ expect(createdIncomingShare.status).toBe('pending');
const outgoingRes = await apiRequest(page, `/api/orgs/${encodeURIComponent(orgA.id)}/shares`);
expect(outgoingRes.ok()).toBeTruthy();
const outgoingShares = (await outgoingRes.json()) as OutgoingShare[];
const outgoingMatch = outgoingShares.find((share) => share.id === createdShare.id);
expect(outgoingMatch?.accessRole).toBe('editor');
+ expect(outgoingMatch?.status).toBe('pending');
const incomingRes = await apiRequest(
page,
@@ -289,6 +320,37 @@ test.describe('Multi-tenant E2E flows', () => {
share.resourceId === createdShare.resourceId,
);
expect(incomingMatch?.accessRole).toBe('editor');
+ expect(incomingMatch?.status).toBe('pending');
+
+ await switchOrg(page, orgA.id);
+ await page.goto('/settings/organization/sharing', { waitUntil: 'domcontentloaded' });
+ await page.waitForURL(/\/settings\/organization\/sharing/, { timeout: 15_000 });
+
+ await expect(page.getByRole('heading', { level: 1, name: 'Organization Sharing' })).toBeVisible();
+ await expect(page.getByText(outboundResourceName, { exact: true })).toBeVisible();
+ await expect(page.getByText(inboundResourceName, { exact: true })).toBeVisible();
+ await expect(page.getByText('Pending approval')).toHaveCount(2);
+
+ const incomingRow = page.locator('tr').filter({ hasText: inboundResourceName }).first();
+ await expect(incomingRow.getByRole('button', { name: 'Accept' })).toBeVisible();
+ await expect(incomingRow.getByRole('button', { name: 'Decline' })).toBeVisible();
+
+ await incomingRow.getByRole('button', { name: 'Accept' }).click();
+ await expect(incomingRow.getByText('Active')).toBeVisible();
+ await expect(incomingRow.getByRole('button', { name: 'Accept' })).toHaveCount(0);
+ await expect(incomingRow.getByRole('button', { name: 'Remove' })).toBeVisible();
+
+ const acceptedIncomingRes = await apiRequest(
+ page,
+ `/api/orgs/${encodeURIComponent(orgA.id)}/shares/incoming`,
+ );
+ expect(acceptedIncomingRes.ok()).toBeTruthy();
+ const acceptedIncomingShares = (await acceptedIncomingRes.json()) as IncomingShare[];
+ const acceptedIncomingMatch = acceptedIncomingShares.find(
+ (share) => share.resourceId === createdIncomingShare.resourceId,
+ );
+ expect(acceptedIncomingMatch?.status).toBe('accepted');
+ expect(acceptedIncomingMatch?.accessRole).toBe('viewer');
} finally {
await deleteOrg(page, orgB.id);
await deleteOrg(page, orgA.id);
diff --git a/tests/integration/tests/66-organization-sharing-approval-ui.spec.ts b/tests/integration/tests/66-organization-sharing-approval-ui.spec.ts
new file mode 100644
index 0000000000..356daade7c
--- /dev/null
+++ b/tests/integration/tests/66-organization-sharing-approval-ui.spec.ts
@@ -0,0 +1,171 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { expect, test as base } from '@playwright/test';
+import { createAuthenticatedStorageState } from './helpers';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+type WorkerFixtures = {
+ authStorageStatePath: string;
+};
+
+const test = base.extend<{}, WorkerFixtures>({
+ storageState: async ({ authStorageStatePath }, use) => {
+ await use(authStorageStatePath);
+ },
+ authStorageStatePath: [async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'tmp',
+ 'playwright-auth',
+ `organization-sharing-approval-ui-${workerInfo.project.name}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ }, { scope: 'worker' }],
+});
+
+const jsonResponse = (body: unknown) => ({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(body),
+});
+
+test.describe('Organization sharing approval UI', () => {
+ test('renders pending shares and promotes accepted incoming shares in-browser', async ({ page }) => {
+ const currentUser = 'admin';
+ const currentOrg = {
+ id: 'default',
+ displayName: 'Default Organization',
+ ownerUserId: currentUser,
+ };
+ const peerOrg = {
+ id: 'org-b',
+ displayName: 'Organization B',
+ ownerUserId: currentUser,
+ };
+ const resourceTimestamp = '2026-04-22T10:30:00Z';
+ const outgoingShare = {
+ id: 'share-out-1',
+ targetOrgId: peerOrg.id,
+ resourceType: 'view',
+ resourceId: 'alerts-outbound',
+ resourceName: 'Outbound Shared View',
+ accessRole: 'editor',
+ status: 'pending',
+ createdAt: resourceTimestamp,
+ createdBy: currentUser,
+ };
+ const incomingShare = {
+ id: 'share-in-1',
+ targetOrgId: currentOrg.id,
+ sourceOrgId: peerOrg.id,
+ sourceOrgName: peerOrg.displayName,
+ resourceType: 'view',
+ resourceId: 'alerts-inbound',
+ resourceName: 'Inbound Shared View',
+ accessRole: 'viewer',
+ status: 'pending',
+ createdAt: resourceTimestamp,
+ createdBy: currentUser,
+ acceptedAt: '',
+ acceptedBy: '',
+ };
+
+ await page.addInitScript((orgId) => {
+ localStorage.setItem('pulse_whats_new_v2_shown', 'true');
+ sessionStorage.setItem('pulse_org_id', orgId);
+ localStorage.setItem('pulse_org_id', orgId);
+ document.cookie = `pulse_org_id=${encodeURIComponent(orgId)}; Path=/; SameSite=Lax`;
+ }, currentOrg.id);
+
+ await page.route(/\/api\/license\/runtime-capabilities(?:\?.*)?$/, async (route) => {
+ await route.fulfill(jsonResponse({
+ capabilities: ['multi_tenant', 'rbac', 'relay'],
+ limits: [],
+ hosted_mode: false,
+ max_history_days: 30,
+ }));
+ });
+
+ await page.route(/\/api\/orgs(?:\?.*)?$/, async (route) => {
+ await route.fulfill(jsonResponse([currentOrg, peerOrg]));
+ });
+
+ await page.route(new RegExp(`/api/orgs/${currentOrg.id}(?:\\?.*)?$`), async (route) => {
+ await route.fulfill(jsonResponse(currentOrg));
+ });
+
+ await page.route(new RegExp(`/api/orgs/${currentOrg.id}/members(?:\\?.*)?$`), async (route) => {
+ await route.fulfill(jsonResponse([]));
+ });
+
+ await page.route(
+ new RegExp(`/api/orgs/${currentOrg.id}/shares/incoming/${incomingShare.id}/accept(?:\\?.*)?$`),
+ async (route) => {
+ incomingShare.status = 'accepted';
+ incomingShare.acceptedAt = resourceTimestamp;
+ incomingShare.acceptedBy = currentUser;
+ await route.fulfill(jsonResponse(incomingShare));
+ },
+ );
+
+ await page.route(new RegExp(`/api/orgs/${currentOrg.id}/shares/incoming(?:\\?.*)?$`), async (route) => {
+ await route.fulfill(jsonResponse([incomingShare]));
+ });
+
+ await page.route(new RegExp(`/api/orgs/${currentOrg.id}/shares(?:\\?.*)?$`), async (route) => {
+ await route.fulfill(jsonResponse([outgoingShare]));
+ });
+
+ await page.route(/\/api\/resources(?:\?.*)?$/, async (route) => {
+ await route.fulfill(jsonResponse([
+ {
+ id: 'vm-100',
+ type: 'vm',
+ name: 'Alpha VM',
+ displayName: 'Alpha VM',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'running',
+ lastSeen: 1713781800000,
+ },
+ ]));
+ });
+
+ await page.goto('/settings/organization/sharing', { waitUntil: 'domcontentloaded' });
+ await page.waitForURL(/\/settings\/organization\/sharing/, { timeout: 15_000 });
+ await page.waitForFunction(() => {
+ const root = document.getElementById('root');
+ return root !== null && root.childElementCount > 0;
+ });
+
+ await expect(page.getByRole('heading', { level: 1, name: 'Organization Sharing' })).toBeVisible();
+ await expect(page.getByText('Outbound Shared View', { exact: true })).toBeVisible();
+ await expect(page.getByText('Inbound Shared View', { exact: true })).toBeVisible();
+ await expect(page.getByText('Pending approval')).toHaveCount(2);
+
+ const outgoingRow = page.locator('tr').filter({ hasText: 'Outbound Shared View' }).first();
+ await expect(outgoingRow.getByText('Pending approval')).toBeVisible();
+
+ const incomingRow = page.locator('tr').filter({ hasText: 'Inbound Shared View' }).first();
+ await expect(incomingRow.getByRole('button', { name: 'Accept' })).toBeVisible();
+ await expect(incomingRow.getByRole('button', { name: 'Decline' })).toBeVisible();
+ await expect(incomingRow.getByText('Waiting for a target organization admin to accept.')).toBeVisible();
+
+ await incomingRow.getByRole('button', { name: 'Accept' }).click();
+
+ await expect(incomingRow.getByText('Active')).toBeVisible();
+ await expect(incomingRow.getByRole('button', { name: 'Accept' })).toHaveCount(0);
+ await expect(incomingRow.getByRole('button', { name: 'Remove' })).toBeVisible();
+ await expect(incomingRow.getByText('Accepted')).toBeVisible();
+ });
+});