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.

Scope report metrics to the requesting organization

rcourtman3f511a5270a8
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 0695639e1e..3e0912a430 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4436,6 +4436,12 @@ agent profiles and fleet diagnostics) declare that authority explicitly with
`RequireOrgAdmin`. `RequireAdmin` now admits instance administrators only, so
an agent route that does not opt in is closed to organization owners.
+The same owner can also build reports on the hosts and agents that organization
+enrolled: the `/api/admin/reports/*` routes use `ensureOrgAdminSession`, and a
+report or schedule on an agent resource reads only that organization's
+inventory and metrics store. An agent ID enrolled in another organization is
+refused as not found rather than read from another store.
+
### Auto-register preserves the operator's stored TLS choice
Re-registering an existing Proxmox node through the canonical auto-register
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 1775dace6c..34d4912b1e 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7857,6 +7857,16 @@ remain available for report generation but are not invoked by `pulse_summarize`.
`TestMetricEvidenceRetainsObservedCoverageAcrossRestart` verifies retained
coordinates, sparse timestamps, statistics, empty results and query failures.
+Retained metric evidence is organization-scoped. Every `pulse_summarize`
+request carries the executor's organization as `MetricReportRequest.OrgID`, and
+the server's report engine resolves that organization's own metrics store
+(`EngineConfig.MetricsStoreForOrg`), refusing a request without one
+(`ErrReportOrgRequired`) rather than reading the default organization's store.
+A tenant's Assistant therefore summarizes only its own organization's history,
+even for a resource ID that also exists in another organization.
+`TestSummarizeToolReadsOnlyItsOrganizationsMetrics` and
+`TestReportEngineReadsOnlyTheRequestOrganizationsMetrics` hold this.
+
The same canonical AI runtime now also records user-chat token
usage to the cost ledger. `chat.Service.ExecuteStream` was a
long-standing gap: the agentic loop accumulated token counts via
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2601b2a973..cff38113b2 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -5050,13 +5050,24 @@ auto-register mutation boundary.
which also admit a manager (owner or admin) of that organization through
`sessionUserHasSettingsAdminPrivileges`: agents, nodes, connections,
availability, TrueNAS and VMware, agent profiles, install commands, deploy
- status, configuration transfer and the org-bound relay mobile token. The
- default is instance administration, so a route that does not opt in fails
- closed. The snapshot records the org rule as `sessionManagesOrg`, never as
- `sessionIsAdmin`, and it widens only `infrastructureRead` and
- `availabilityRead`. Reporting stays instance administration because report
- generation reads the instance's default metrics store. Every other
- capability, `detailLevel` and `authUsername` stay instance administration.
+ status, configuration transfer, the org-bound relay mobile token, and the
+ `/api/admin/reports/*` routes (catalog, single and multi-resource
+ generation, VM inventory export, schedules). The default is instance
+ administration, so a route that does not opt in fails closed. The snapshot
+ records the org rule as `sessionManagesOrg`, never as `sessionIsAdmin`, and
+ it widens only `infrastructureRead`, `availabilityRead` and `reportingRead`;
+ `reportingRead` still requires the authorizer's `read` on `nodes`.
+ Reporting is org-bound because the report engine resolves the metrics store
+ of the request's `OrgID` (`EngineConfig.MetricsStoreForOrg`) and refuses a
+ request without one, and the handlers reject any resource that is not in
+ the request organization's inventory; scheduled runs resolve their scope
+ against their owning organization's inventory, and Pulse Assistant's
+ `pulse_summarize` reads its executor's organization.
+ `internal/api/reporting_org_scope_test.go`,
+ `TestReportingScheduledRunReadsOnlyItsOwningOrganizationsMetrics` and
+ `pkg/reporting/engine_org_scope_test.go` prove one organization cannot read
+ another's metrics through any report path. Every other capability,
+ `detailLevel` and `authUsername` stay instance administration.
`internal/api/org_admin_session_authority_test.go` holds the session matrix. Before this, a provider opening a client
workspace from the Pulse Account portal arrived as the org owner with every
capability `false`, so Settings hid the Infrastructure and Reporting pages
@@ -11668,8 +11679,9 @@ routes on mount:
and `/api/logs/download`;
- `pulseIntelligenceRead` combines the handler's settings-admin/scope check
with `RequirePermission(read, settings)` from `/api/settings/ai`;
-- `reportingRead` combines `ensureAdminSession` (instance administrators
- only), `settings:read`, and `RequirePermission(read, nodes)` from
+- `reportingRead` combines `ensureOrgAdminSession` (instance administrators
+ and, on an org-scoped request, managers of that organization),
+ `settings:read`, and `RequirePermission(read, nodes)` from
`/api/admin/reports/catalog`.
Those last two must not collapse to `canReadSettings`: a custom authorizer can
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 7184dd069c..374de536ee 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -7705,6 +7705,30 @@
"frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts"
]
},
+ {
+ "id": "server-runtime-wiring",
+ "label": "server runtime wiring proof",
+ "match_prefixes": [],
+ "match_files": [
+ "pkg/server/server.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "frontend-modern/src/stores/__tests__/systemSettings.test.ts",
+ "internal/api/system_settings_telemetry_test.go",
+ "internal/api/telemetry_history_reads_test.go",
+ "internal/config/history_read_activity_test.go",
+ "internal/telemetry/service_health_test.go",
+ "internal/telemetry/telemetry_test.go",
+ "pkg/server/reporting_engine_test.go",
+ "pkg/server/service_health_test.go",
+ "pkg/server/telemetry_licensed_features_test.go",
+ "pkg/server/telemetry_pulse_intelligence_test.go",
+ "scripts/tests/test_telemetry_adoption_report.py",
+ "tests/integration/tests/19-telemetry-disclosure.spec.ts"
+ ]
+ },
{
"id": "privacy-docs-and-telemetry",
"label": "privacy docs and telemetry proof",
@@ -7715,7 +7739,6 @@
"internal/config/history_read_activity.go",
"internal/telemetry/service_health.go",
"internal/telemetry/telemetry.go",
- "pkg/server/server.go",
"pkg/server/service_health.go",
"pkg/server/telemetry_licensed_features.go",
"pkg/server/telemetry_pulse_intelligence.go",
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 5007376842..c73d7f1f5f 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -30,6 +30,22 @@ the same provider VM ID. Historical storage reads preserve source labels and
requested time bounds. These read paths add no credential, execution or approval
authority.
+### Reports and metric summaries read only the requesting organization
+
+The server's report engine (`pkg/server/server.go`) resolves the metrics store
+of each request's organization through the multi-tenant monitor
+(`EngineConfig.MetricsStoreForOrg`) and refuses a request that names no
+organization, so no report path falls back to the default organization's
+store. Report handlers also reject a resource that is not in the requesting
+organization's inventory, scheduled runs resolve their scope against their
+owning organization's inventory, and Pulse Assistant's `pulse_summarize`
+reads its executor's organization. A resource ID that exists in two
+organizations yields each organization only its own history.
+`internal/api/reporting_org_scope_test.go`,
+`TestReportingScheduledRunReadsOnlyItsOwningOrganizationsMetrics`,
+`pkg/reporting/engine_org_scope_test.go` and
+`TestSummarizeToolReadsOnlyItsOrganizationsMetrics` hold this boundary.
+
### Patrol maintenance coverage widens no authority
Patrol inherits only maintenance from an ancestor window scoped
@@ -467,7 +483,7 @@ administrator or settings-scope checks, expose queue contents to new callers, or
change tenant selection. Missing owners fail with 503 rather than dereferencing
nil.
-The authenticated security-status currentUsername is the validated caller principal, not an administrator configuration disclosure. Public responses omit it. An organisation-scoped local session may receive its own identity while authUsername and instance-settings capabilities remain withheld; clients must not interpret identity availability as privilege. A manager of that organisation additionally receives the org-bound infrastructureRead and availabilityRead capabilities, because their routes admit org managers through RequireOrgAdmin / ensureOrgAdminSession and read only that organisation's state; this never extends to reporting, authentication, SSO, API tokens, users, roles, audit, relay, system, updates, logs, diagnostics or billing surfaces, whose routes use ensureAdminSession and admit instance administrators only.
+The authenticated security-status currentUsername is the validated caller principal, not an administrator configuration disclosure. Public responses omit it. An organisation-scoped local session may receive its own identity while authUsername and instance-settings capabilities remain withheld; clients must not interpret identity availability as privilege. A manager of that organisation additionally receives the org-bound infrastructureRead, availabilityRead and reportingRead capabilities, because their routes admit org managers through RequireOrgAdmin / ensureOrgAdminSession and read only that organisation's state (reports read only its inventory and metrics store, and reportingRead still requires read:nodes); this never extends to authentication, SSO, API tokens, users, roles, audit, relay, system, updates, logs, diagnostics or billing surfaces, whose routes use ensureAdminSession and admit instance administrators only.
API token scope copy must match runtime authority. `ai:chat` covers Assistant
conversation, model selection, sessions, and knowledge reads only. Knowledge
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 73ad034320..6d8b65b6bc 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -3250,11 +3250,12 @@ withheld from every org-scoped session, so an org manager is not offered
instance recovery or configuration transfer. See the api-contracts contract,
rule 35.
-Superseded in part: `reportingRead` is no longer granted to org managers.
-Report generation reads the instance's default metrics store, so reporting
-routes stay instance administration until reporting is scoped to the
-organization's own metrics. Org managers keep `infrastructureRead` and
-`availabilityRead`.
+Superseded in part: `reportingRead` was briefly withheld from org managers
+while report generation read the instance's default metrics store. Reports now
+read only the request organization's metrics store and refuse resources outside
+its inventory, so org managers again hold `reportingRead` alongside
+`infrastructureRead` and `availabilityRead`, and the reporting routes use
+`ensureOrgAdminSession`.
### TLS verification preference survives node re-registration
diff --git a/internal/ai/tools/tools_summarize.go b/internal/ai/tools/tools_summarize.go
index b9a7b4ef78..f9bcb76fff 100644
--- a/internal/ai/tools/tools_summarize.go
+++ b/internal/ai/tools/tools_summarize.go
@@ -189,6 +189,8 @@ func (e *PulseToolExecutor) summarizeResource(
}
req.Start = start
req.End = end
+ // Read only this executor's organization's retained metrics.
+ req.OrgID = e.orgID
evidence, err := engine.MetricEvidenceFor(ctx, req)
if err != nil {
return NewErrorResult(fmt.Errorf("metric evidence query failed: %w", err)), nil
@@ -516,6 +518,7 @@ func (e *PulseToolExecutor) summarizeFleet(
evidence := make([]*reporting.MetricEvidence, 0, len(resources))
for _, req := range resources {
req.Start, req.End = start, end
+ req.OrgID = e.orgID
item, err := engine.MetricEvidenceFor(ctx, req)
if err != nil {
return NewErrorResult(fmt.Errorf("metric evidence query failed for %s: %w", req.ResourceID, err)), nil
diff --git a/internal/ai/tools/tools_summarize_test.go b/internal/ai/tools/tools_summarize_test.go
index ae0bdebb2a..5ce612f545 100644
--- a/internal/ai/tools/tools_summarize_test.go
+++ b/internal/ai/tools/tools_summarize_test.go
@@ -664,3 +664,47 @@ func TestSummarizeToolReturnsHighUtilizationAsEvidenceWithoutDiagnosis(t *testin
}
}
}
+
+func TestSummarizeToolReadsOnlyItsOrganizationsMetrics(t *testing.T) {
+ at := time.Now().Add(-time.Hour).Truncate(time.Minute)
+ stores := map[string]*metrics.Store{}
+ for orgID, value := range map[string]float64{"default": 13, "org-b": 71} {
+ store, err := metrics.NewStore(metrics.DefaultConfig(t.TempDir()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+ // The same metrics ID exists in both organizations.
+ store.Write("node", "delly-node-id", "memory", value, at)
+ store.Flush()
+ stores[orgID] = store
+ }
+ previous := reporting.GetEngine()
+ reporting.SetEngine(reporting.NewReportEngine(reporting.EngineConfig{
+ MetricsStoreForOrg: func(orgID string) (*metrics.Store, error) {
+ store, ok := stores[orgID]
+ if !ok {
+ return nil, fmt.Errorf("organization %q is not provisioned", orgID)
+ }
+ return store, nil
+ },
+ }))
+ defer reporting.SetEngine(previous)
+
+ exec := NewPulseToolExecutor(ExecutorConfig{OrgID: "org-b"})
+ exec.SetUnifiedResourceProvider(newSummarizeStubProvider())
+ for _, args := range []map[string]interface{}{
+ {"action": "resource", "resource_id": "delly", "range": "24h"},
+ {"action": "resource", "resource_type": "node", "resource_id": "delly-node-id", "range": "24h"},
+ {"action": "fleet", "resource_ids": "delly", "range": "24h"},
+ } {
+ result, err := exec.executeSummarize(context.Background(), args)
+ if err != nil || result.IsError {
+ t.Fatalf("summarize %v = %+v, %v", args, result, err)
+ }
+ text := result.Content[0].Text
+ if !strings.Contains(text, `"mean":71`) || strings.Contains(text, `"mean":13`) {
+ t.Fatalf("summarize %v for org-b must read only org-b's metrics: %s", args, text)
+ }
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 2142b3c46d..87da635d4e 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -5449,7 +5449,7 @@ func TestContract_PerformanceReportTransportUsesCatalogDefinition(t *testing.T)
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
req := httptest.NewRequest(
http.MethodGet,
"/api/reporting?resourceType=node&resourceId=node-1&metricType=+cpu+&title=+Node+report+",
@@ -5528,7 +5528,7 @@ func TestContract_SingleReportAINarrationRequiresPOST(t *testing.T) {
// tenant AI service; GET must use only the existing-service findings path.
narrator := &countingReportNarrator{}
var narratorResolves, findingsResolves atomic.Int32
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
handler.SetNarratorResolver(func(context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider) {
narratorResolves.Add(1)
return narrator, nil, nil
@@ -5602,7 +5602,7 @@ func TestContract_SingleReportGETDoesNotConstructTenantAIService(t *testing.T) {
router := &Router{
aiSettingsHandler: NewAISettingsHandler(config.NewMultiTenantPersistence(t.TempDir()), nil, nil),
- reportingHandlers: NewReportingHandlers(nil, nil),
+ reportingHandlers: newReportingHandlersWithInventoryForTest(t, "tenant-1", "node-1"),
}
router.wireReportingAIResolvers()
t.Cleanup(router.aiSettingsHandler.StopServices)
@@ -5778,7 +5778,7 @@ func TestContract_ReportingRequestCarriesEntitledReportBranding(t *testing.T) {
t.Cleanup(func() { SetLicenseServiceProvider(nil) })
t.Setenv("PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME", "Provider Default")
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
handler.SetSystemSettingsStore(reportBrandSettingsStore{settings: &config.SystemSettings{
ReportBranding: &config.ReportBrandSettings{DisplayName: "Client One"},
}})
@@ -5940,7 +5940,7 @@ func TestContract_PerformanceReportTransportUsesCatalogDefaultRange(t *testing.T
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
end := time.Date(2026, 3, 25, 15, 0, 0, 0, time.UTC)
req := httptest.NewRequest(
http.MethodGet,
@@ -26481,9 +26481,11 @@ func orgScopedSessionRequest(t *testing.T, user string, org *models.Organization
// its owner. ensureOrgAdminSession lets an org manager through the org-bound
// settings routes, but the security status snapshot reported every settings
// capability as false for any org-scoped session, so the settings navigation
-// hid Infrastructure and the owner had no way to connect a single system.
-// Those org-bound capabilities must follow the route rule, while instance
-// administration, reporting included, stays closed to org-scoped sessions.
+// hid Infrastructure and Reporting and the owner had no way to connect a
+// single system or build its reports. Those org-bound capabilities must follow
+// the route rule, while instance administration stays closed to org-scoped
+// sessions. Reporting is org-bound because every report reads only the request
+// organization's inventory and metrics store.
func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {
prev := authpkg.GetAuthorizer()
authpkg.SetAuthorizer(&authpkg.DefaultAuthorizer{})
@@ -26524,6 +26526,7 @@ func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {
orgBound := map[string]bool{
"infrastructureRead": caps.InfrastructureRead,
"availabilityRead": caps.AvailabilityRead,
+ "reportingRead": caps.ReportingRead,
}
for name, got := range orgBound {
if got != tc.manager {
@@ -26532,7 +26535,6 @@ func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {
}
instanceWide := map[string]bool{
- "reportingRead": caps.ReportingRead,
"systemSettingsRead": caps.SystemSettingsRead,
"diagnosticsRead": caps.DiagnosticsRead,
"systemLogsRead": caps.SystemLogsRead,
diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.go
index dfdbcf2ea9..5ad7074d9a 100644
--- a/internal/api/metrics_reporting_handlers.go
+++ b/internal/api/metrics_reporting_handlers.go
@@ -726,7 +726,9 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.
return
}
+ orgID := GetOrgID(r.Context())
req := reporting.MetricReportRequest{
+ OrgID: orgID,
ResourceType: resourceType,
ResourceID: resourceID,
MetricType: metricType,
@@ -737,11 +739,18 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.
Branding: h.resolveReportBranding(r.Context()),
}
- // Enrich with resource data if monitor is available
- orgID := GetOrgID(r.Context())
- if snapshot, ok := h.getReportingEnrichmentSnapshot(r.Context(), orgID); ok {
- h.enrichReportRequest(r.Context(), orgID, &req, snapshot, start, end)
+ // The resource must belong to the requesting organization; the engine
+ // then reads only that organization's metrics store.
+ snapshot, ok := h.getReportingEnrichmentSnapshot(r.Context(), orgID)
+ if !ok {
+ writeErrorResponse(w, http.StatusServiceUnavailable, "inventory_unavailable", "Resource inventory for this organization is not available", nil)
+ return
}
+ if !reportSubjectInInventory(resourceID, snapshot) {
+ writeErrorResponse(w, http.StatusNotFound, "resource_not_found", "Resource not found in this organization", nil)
+ return
+ }
+ h.enrichReportRequest(r.Context(), orgID, &req, snapshot, start, end)
// Wire the per-tenant AI narrator and Patrol findings provider when
// configured. Both are nil-safe at the engine layer; absence falls
@@ -878,6 +887,38 @@ func (h *ReportingHandlers) resolveReportSubject(orgID string, req *reporting.Me
}
}
+// reportSubjectInInventory reports whether resourceID names a resource in an
+// organization's inventory snapshot: a canonical unified resource ID, or the
+// legacy state-model ID of one of its nodes, VMs or containers, which the
+// report enrichment also accepts. A report is only generated for a resource
+// the requesting organization owns.
+func reportSubjectInInventory(resourceID string, snapshot reportingEnrichmentSnapshot) bool {
+ if resourceID == "" {
+ return false
+ }
+ for i := range snapshot.Resources {
+ if snapshot.Resources[i].ID == resourceID {
+ return true
+ }
+ }
+ for i := range snapshot.Nodes {
+ if snapshot.Nodes[i].ID == resourceID {
+ return true
+ }
+ }
+ for i := range snapshot.VMs {
+ if snapshot.VMs[i].ID == resourceID {
+ return true
+ }
+ }
+ for i := range snapshot.Containers {
+ if snapshot.Containers[i].ID == resourceID {
+ return true
+ }
+ }
+ return false
+}
+
// reportSubjectIDMatches reports whether a legacy state-model ID refers to
// the report subject. Legacy snapshots (and the alerts raised on them) are
// keyed by the metrics-target ID, while the request carries the canonical
@@ -1186,7 +1227,9 @@ func (h *ReportingHandlers) generateMultiReportFromBody(ctx context.Context, bod
return generatedMultiReport{}, &reportingRequestError{status: http.StatusBadRequest, code: "invalid_time_range", message: err.Error()}
}
+ orgID := GetOrgID(ctx)
multiReq := reporting.MultiReportRequest{
+ OrgID: orgID,
Format: format,
Start: start,
End: end,
@@ -1195,8 +1238,14 @@ func (h *ReportingHandlers) generateMultiReportFromBody(ctx context.Context, bod
Branding: h.resolveReportBranding(ctx),
}
- orgID := GetOrgID(ctx)
snapshot, hasSnapshot := h.getReportingEnrichmentSnapshot(ctx, orgID)
+ if !hasSnapshot {
+ return generatedMultiReport{}, &reportingRequestError{
+ status: http.StatusServiceUnavailable,
+ code: "inventory_unavailable",
+ message: "Resource inventory for this organization is not available",
+ }
+ }
for _, res := range body.Resources {
if !validResourceID.MatchString(res.ResourceType) || len(res.ResourceType) > 64 {
return generatedMultiReport{}, &reportingRequestError{
@@ -1217,7 +1266,16 @@ func (h *ReportingHandlers) generateMultiReportFromBody(ctx context.Context, bod
return generatedMultiReport{}, &reportingRequestError{status: http.StatusBadRequest, code: "invalid_resource_type", message: err.Error()}
}
+ if !reportSubjectInInventory(res.ResourceID, snapshot) {
+ return generatedMultiReport{}, &reportingRequestError{
+ status: http.StatusNotFound,
+ code: "resource_not_found",
+ message: fmt.Sprintf("Resource not found in this organization: %s", res.ResourceID),
+ }
+ }
+
req := reporting.MetricReportRequest{
+ OrgID: orgID,
ResourceType: resourceType,
ResourceID: res.ResourceID,
MetricType: metricType,
@@ -1227,9 +1285,7 @@ func (h *ReportingHandlers) generateMultiReportFromBody(ctx context.Context, bod
Title: title,
Branding: multiReq.Branding,
}
- if hasSnapshot {
- h.enrichReportRequest(ctx, orgID, &req, snapshot, start, end)
- }
+ h.enrichReportRequest(ctx, orgID, &req, snapshot, start, end)
multiReq.Resources = append(multiReq.Resources, req)
}
diff --git a/internal/api/report_ai_narration_scope_test.go b/internal/api/report_ai_narration_scope_test.go
index 6b8f7f83b5..c0c17270ba 100644
--- a/internal/api/report_ai_narration_scope_test.go
+++ b/internal/api/report_ai_narration_scope_test.go
@@ -56,7 +56,7 @@ func TestSingleReportAINarrationNeedsAIExecuteForTokens(t *testing.T) {
narrator := &countingReportNarrator{}
var narratorResolves, findingsResolves atomic.Int32
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
handler.SetNarratorResolver(func(context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider) {
narratorResolves.Add(1)
return narrator, nil, nil
@@ -116,7 +116,7 @@ func TestSingleReportGETNeverUsesAIRegardlessOfTokenScopes(t *testing.T) {
narrator := &countingReportNarrator{}
var narratorResolves, findingsResolves atomic.Int32
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
handler.SetNarratorResolver(func(context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider) {
narratorResolves.Add(1)
return narrator, nil, nil
@@ -165,7 +165,7 @@ func TestFleetReportAINarrationNeedsAIExecuteForTokens(t *testing.T) {
t.Cleanup(func() { reporting.SetEngine(original) })
var narratorResolves, findingsResolves atomic.Int32
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "vm-1")
handler.SetNarratorResolver(func(context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider) {
narratorResolves.Add(1)
return nil, stubFleetNarrator{}, nil
diff --git a/internal/api/report_schedules.go b/internal/api/report_schedules.go
index d5bea5ba1b..ca8fd53e44 100644
--- a/internal/api/report_schedules.go
+++ b/internal/api/report_schedules.go
@@ -541,17 +541,32 @@ func (h *ReportingHandlers) resolveReportScheduleResources(ctx context.Context,
entries = append(entries, multiReportResourceEntry{ResourceType: resourceType, ResourceID: resourceID})
return nil
}
+ // A schedule reports only on resources its own organization holds, so
+ // both explicit resources and tags resolve against that organization's
+ // inventory.
+ snapshot, ok := h.getReportingEnrichmentSnapshot(ctx, orgID)
+ if !ok {
+ return nil, reportScheduleValidationError{code: "scope_unavailable", message: "Schedule scope cannot be resolved until resource inventory is available"}
+ }
for _, res := range scope.Resources {
+ if _, err := normalizeReportResourceType(res.ResourceType); err != nil {
+ return nil, reportScheduleValidationError{code: "invalid_resource_type", message: err.Error()}
+ }
+ if !reportSubjectInInventory(res.ResourceID, snapshot) {
+ // A resource removed since the schedule was saved, or never
+ // part of this organization, is left out of the report.
+ log.Warn().
+ Str("org_id", orgID).
+ Str("resource_id", res.ResourceID).
+ Msg("report schedules: skipping a resource that is not in this organization's inventory")
+ continue
+ }
if err := appendEntry(res.ResourceType, res.ResourceID); err != nil {
return nil, reportScheduleValidationError{code: "invalid_resource_type", message: err.Error()}
}
}
if len(scope.Tags) > 0 {
- snapshot, ok := h.getReportingEnrichmentSnapshot(ctx, orgID)
- if !ok {
- return nil, reportScheduleValidationError{code: "scope_unavailable", message: "Tagged schedule scope cannot be resolved until resource inventory is available"}
- }
tags := map[string]struct{}{}
for _, tag := range scope.Tags {
tags[strings.ToLower(strings.TrimSpace(tag))] = struct{}{}
diff --git a/internal/api/report_schedules_test.go b/internal/api/report_schedules_test.go
index 9e2e650ed2..f93caac7a8 100644
--- a/internal/api/report_schedules_test.go
+++ b/internal/api/report_schedules_test.go
@@ -9,12 +9,15 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "reflect"
"strings"
"testing"
"time"
+ "unsafe"
"github.com/rcourtman/pulse-go-rewrite/internal/ai"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
@@ -35,6 +38,11 @@ func newTestReportingScheduleHandlers(t *testing.T) (*ReportingHandlers, *config
if persistence == nil {
t.Fatal("monitor config persistence is nil")
}
+ // A schedule only reports on resources its organization holds, so the
+ // default organization holds the VM validReportSchedulePayload names.
+ stateField := reflect.ValueOf(monitor).Elem().FieldByName("state")
+ state := reflect.NewAt(stateField.Type(), unsafe.Pointer(stateField.UnsafeAddr())).Elem().Interface().(*models.State)
+ state.UpdateVMs([]models.VM{{ID: "vm-1", Name: "VM 1", Status: "running"}})
return NewReportingHandlers(mtm, nil), persistence
}
@@ -359,3 +367,46 @@ func TestRunPatrolDigestScheduleFailsClearlyWithoutDigestOrEmail(t *testing.T) {
t.Fatal("failed digest run must still schedule the next occurrence")
}
}
+
+// A schedule runs inside its owning organization: its scope resolves against
+// that organization's inventory and its report reads only that organization's
+// metrics store. The fixture lives in reporting_org_scope_test.go.
+func TestReportingScheduledRunReadsOnlyItsOwningOrganizationsMetrics(t *testing.T) {
+ handlers := newReportingOrgScopeFixture(t)
+ unifiedA := orgScopeUnifiedNodeID(t, handlers, "org-a")
+ persistence := config.NewConfigPersistence(t.TempDir())
+
+ // A schedule saved in org B that names org A's resources alongside its
+ // own reports only on org B's resource, from org B's store.
+ schedule := validReportSchedulePayload()
+ schedule.ID = "org-b-weekly"
+ schedule.Cadence = config.ReportScheduleCadence{Type: config.ReportScheduleCadenceWeekly, Weekday: "monday", Time: "09:00", Timezone: "UTC"}
+ schedule.Format = config.ReportScheduleFormatCSV
+ schedule.Scope = config.ReportScheduleScope{Resources: []config.ReportScheduleResource{
+ {ResourceType: "node", ResourceID: "node-a"},
+ {ResourceType: "node", ResourceID: unifiedA},
+ {ResourceType: "node", ResourceID: "node-b"},
+ }}
+ now := time.Now()
+ result, updated := handlers.runReportSchedule(orgScopeContext("org-b"), persistence, schedule, now, true, "")
+ if updated.LastRunStatus != config.ReportScheduleLastRunOK || result.path == "" {
+ t.Fatalf("org B scheduled run = %+v (%q), want a saved report", updated, updated.LastError)
+ }
+ saved, err := os.ReadFile(filepath.Clean(result.path))
+ if err != nil {
+ t.Fatalf("read saved report: %v", err)
+ }
+ if body := string(saved); !strings.Contains(body, orgScopeValueB) || strings.Contains(body, orgScopeValueA) || strings.Contains(body, "node-a") {
+ t.Fatalf("org B scheduled report must carry only org B's resource and metrics:\n%s", body)
+ }
+
+ // A schedule whose resources all belong to another organization reads
+ // nothing.
+ schedule.Scope = config.ReportScheduleScope{Resources: []config.ReportScheduleResource{
+ {ResourceType: "node", ResourceID: "node-a"},
+ }}
+ result, updated = handlers.runReportSchedule(orgScopeContext("org-b"), persistence, schedule, now, true, "")
+ if updated.LastRunStatus != config.ReportScheduleLastRunFailed || result.path != "" {
+ t.Fatalf("org B schedule over org A's resource = %+v, want a failed run with no report", updated)
+ }
+}
diff --git a/internal/api/reporting_handlers_test.go b/internal/api/reporting_handlers_test.go
index f5adb84e9d..4ff7fd89da 100644
--- a/internal/api/reporting_handlers_test.go
+++ b/internal/api/reporting_handlers_test.go
@@ -179,7 +179,7 @@ func TestReportingHandlers_GenerateReport(t *testing.T) {
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
start := time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339)
end := time.Now().UTC().Format(time.RFC3339)
@@ -234,7 +234,7 @@ func TestReportingHandlers_AttachesEntitledReportBranding(t *testing.T) {
SetLicenseServiceProvider(reportBrandLicenseProvider{service: service})
t.Cleanup(func() { SetLicenseServiceProvider(nil) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
handler.SetSystemSettingsStore(reportBrandSettingsStore{settings: &config.SystemSettings{
ReportBranding: &config.ReportBrandSettings{
DisplayName: "Client Alpha MSP",
@@ -283,7 +283,7 @@ func TestReportingHandlers_StripsWorkspaceReportBrandLogoPath(t *testing.T) {
SetLicenseServiceProvider(reportBrandLicenseProvider{service: service})
t.Cleanup(func() { SetLicenseServiceProvider(nil) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
handler.SetSystemSettingsStore(reportBrandSettingsStore{settings: &config.SystemSettings{
ReportBranding: &config.ReportBrandSettings{
DisplayName: "Client Path",
@@ -313,7 +313,7 @@ func TestReportingHandlers_GenerateReport_TrimsOptionalFields(t *testing.T) {
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
req := httptest.NewRequest(
http.MethodGet,
"/api/reporting?format=pdf&resourceType=node&resourceId=node-1&metricType=+cpu+&title=+Node+report+",
@@ -395,7 +395,7 @@ func TestReportingHandlers_GenerateReport_AcceptsCanonicalAppContainerType(t *te
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "docker-1")
req := httptest.NewRequest(
http.MethodGet,
"/api/reporting?format=pdf&resourceType=app-container&resourceId=docker-1",
@@ -527,7 +527,7 @@ func TestReportingHandlers_GenerateMultiReport_TrimsOptionalFieldsAndUsesCanonic
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "vm-1")
body := `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"csv","metricType":" cpu ","title":" Fleet report "}`
req := httptest.NewRequest(http.MethodPost, "/api/reporting/generate-multi", strings.NewReader(body))
rr := httptest.NewRecorder()
@@ -561,7 +561,7 @@ func TestReportingHandlers_GenerateReport_UsesCatalogDefaultRangeDuration(t *tes
reporting.SetEngine(engine)
t.Cleanup(func() { reporting.SetEngine(original) })
- handler := NewReportingHandlers(nil, nil)
+ handler := newReportingHandlersWithInventoryForTest(t, "default", "node-1")
end := time.Date(2026, 3, 25, 15, 0, 0, 0, time.UTC)
req := httptest.NewRequest(
http.MethodGet,
diff --git a/internal/api/reporting_org_scope_test.go b/internal/api/reporting_org_scope_test.go
new file mode 100644
index 0000000000..eb3fc4a051
--- /dev/null
+++ b/internal/api/reporting_org_scope_test.go
@@ -0,0 +1,176 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+)
+
+// Org A owns node-a and org B owns node-b. Org A's metrics store also holds
+// points under node-b, so a report that reads the wrong organization's store
+// shows org A's value (11) instead of org B's (77).
+const (
+ orgScopeValueA = "11.00"
+ orgScopeValueB = "77.00"
+)
+
+func newReportingOrgScopeFixture(t *testing.T) *ReportingHandlers {
+ t.Helper()
+ now := time.Now()
+ stores := map[string]*metrics.Store{}
+ for orgID, series := range map[string]map[string]float64{
+ "org-a": {"node-a": 11, "node-b": 11},
+ "org-b": {"node-b": 77},
+ } {
+ store, err := metrics.NewStore(metrics.DefaultConfig(t.TempDir()))
+ if err != nil {
+ t.Fatalf("metrics store for %s: %v", orgID, err)
+ }
+ t.Cleanup(func() { store.Close() })
+ // Every tier holds the points, so whichever tier a report window
+ // selects finds them.
+ for resourceID, value := range series {
+ for _, tier := range []metrics.Tier{metrics.TierRaw, metrics.TierMinute, metrics.TierHourly, metrics.TierDaily} {
+ for i := 0; i < 6; i++ {
+ store.WriteWithTier("node", resourceID, "cpu", value, now.Add(time.Duration(-50+i*5)*time.Minute), tier)
+ }
+ }
+ }
+ store.Flush()
+ stores[orgID] = store
+ }
+
+ original := reporting.GetEngine()
+ reporting.SetEngine(reporting.NewReportEngine(reporting.EngineConfig{
+ MetricsStoreForOrg: func(orgID string) (*metrics.Store, error) {
+ store, ok := stores[orgID]
+ if !ok {
+ return nil, fmt.Errorf("organization %q is not provisioned", orgID)
+ }
+ return store, nil
+ },
+ }))
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ stateA := models.NewState()
+ stateA.Nodes = []models.Node{{ID: "node-a", Name: "pve-a", Status: "online"}}
+ stateB := models.NewState()
+ stateB.Nodes = []models.Node{{ID: "node-b", Name: "pve-b", Status: "online"}}
+
+ mtm := monitoring.NewMultiTenantMonitor(&config.Config{}, nil, nil)
+ setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{
+ "org-a": newReportingMonitorForTest(t, stateA, nil),
+ "org-b": newReportingMonitorForTest(t, stateB, nil),
+ })
+ return NewReportingHandlers(mtm, nil)
+}
+
+func orgScopeContext(orgID string) context.Context {
+ return context.WithValue(context.Background(), OrgIDContextKey, orgID)
+}
+
+func orgScopeUnifiedNodeID(t *testing.T, handlers *ReportingHandlers, orgID string) string {
+ t.Helper()
+ snapshot, ok := handlers.getReportingEnrichmentSnapshot(context.Background(), orgID)
+ if !ok {
+ t.Fatalf("no inventory snapshot for %s", orgID)
+ }
+ for _, resource := range snapshot.Resources {
+ if reporting.CanonicalResourceType(string(resource.Type)) != "" && resource.Name != "" {
+ return resource.ID
+ }
+ }
+ t.Fatalf("no unified resource in %s inventory: %+v", orgID, snapshot.Resources)
+ return ""
+}
+
+func TestReportingSingleReportReadsOnlyTheRequestOrganizationsMetrics(t *testing.T) {
+ handlers := newReportingOrgScopeFixture(t)
+ unifiedA := orgScopeUnifiedNodeID(t, handlers, "org-a")
+
+ generate := func(orgID, method, resourceID string) *httptest.ResponseRecorder {
+ var req *http.Request
+ if method == http.MethodGet {
+ req = httptest.NewRequest(http.MethodGet, "/api/admin/reports/generate?format=csv&resourceType=node&metricType=cpu&resourceId="+resourceID, nil)
+ } else {
+ body := fmt.Sprintf(`{"format":"csv","resourceType":"node","metricType":"cpu","resourceId":%q}`, resourceID)
+ req = httptest.NewRequest(http.MethodPost, "/api/admin/reports/generate", strings.NewReader(body))
+ }
+ rec := httptest.NewRecorder()
+ handlers.HandleGenerateReport(rec, req.WithContext(orgScopeContext(orgID)))
+ return rec
+ }
+
+ for _, method := range []string{http.MethodGet, http.MethodPost} {
+ // Org A's resource, by legacy and unified ID, is not reportable from org B.
+ for _, foreignID := range []string{"node-a", unifiedA} {
+ rec := generate("org-b", method, foreignID)
+ if rec.Code != http.StatusNotFound || strings.Contains(rec.Body.String(), orgScopeValueA) {
+ t.Fatalf("%s org B report on org A's %s = %d %q, want 404 without org A's metrics", method, foreignID, rec.Code, rec.Body.String())
+ }
+ }
+
+ // Org B's own resource reads org B's store, although org A's store
+ // holds points under the same ID.
+ rec := generate("org-b", method, "node-b")
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s org B report on node-b = %d %q", method, rec.Code, rec.Body.String())
+ }
+ if body := rec.Body.String(); !strings.Contains(body, orgScopeValueB) || strings.Contains(body, orgScopeValueA) {
+ t.Fatalf("%s org B report on node-b must carry only org B's metrics:\n%s", method, body)
+ }
+
+ // Org A still reports on its own resource.
+ rec = generate("org-a", method, "node-a")
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), orgScopeValueA) {
+ t.Fatalf("%s org A report on node-a = %d %q", method, rec.Code, rec.Body.String())
+ }
+ }
+}
+
+func TestReportingMultiReportReadsOnlyTheRequestOrganizationsMetrics(t *testing.T) {
+ handlers := newReportingOrgScopeFixture(t)
+ unifiedA := orgScopeUnifiedNodeID(t, handlers, "org-a")
+
+ generate := func(orgID string, resourceIDs ...string) *httptest.ResponseRecorder {
+ resources := make([]multiReportResourceEntry, 0, len(resourceIDs))
+ for _, id := range resourceIDs {
+ resources = append(resources, multiReportResourceEntry{ResourceType: "node", ResourceID: id})
+ }
+ body, err := json.Marshal(multiReportRequestBody{Resources: resources, Format: "csv", MetricType: "cpu"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/admin/reports/generate-multi", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handlers.HandleGenerateMultiReport(rec, req.WithContext(orgScopeContext(orgID)))
+ return rec
+ }
+
+ for _, foreignID := range []string{"node-a", unifiedA} {
+ rec := generate("org-b", "node-b", foreignID)
+ if rec.Code != http.StatusNotFound || strings.Contains(rec.Body.String(), orgScopeValueA) {
+ t.Fatalf("org B fleet report including org A's %s = %d %q, want 404 without org A's metrics", foreignID, rec.Code, rec.Body.String())
+ }
+ }
+
+ rec := generate("org-b", "node-b")
+ if rec.Code != http.StatusOK {
+ t.Fatalf("org B fleet report = %d %q", rec.Code, rec.Body.String())
+ }
+ if body := rec.Body.String(); !strings.Contains(body, orgScopeValueB) || strings.Contains(body, orgScopeValueA) {
+ t.Fatalf("org B fleet report must carry only org B's metrics:\n%s", body)
+ }
+}
diff --git a/internal/api/reporting_runtime_snapshot_test.go b/internal/api/reporting_runtime_snapshot_test.go
index 6c82f84fc9..162f0b2b31 100644
--- a/internal/api/reporting_runtime_snapshot_test.go
+++ b/internal/api/reporting_runtime_snapshot_test.go
@@ -253,3 +253,21 @@ func newReportingMTMForTest(t *testing.T, monitor *monitoring.Monitor) *monitori
})
return mtm
}
+
+// newReportingHandlersWithInventoryForTest returns handlers whose orgID
+// organization holds nodes with the given IDs, so report requests for them
+// pass the check that a reported resource belongs to the requesting
+// organization.
+func newReportingHandlersWithInventoryForTest(t *testing.T, orgID string, resourceIDs ...string) *ReportingHandlers {
+ t.Helper()
+
+ state := models.NewState()
+ for _, id := range resourceIDs {
+ state.Nodes = append(state.Nodes, models.Node{ID: id, Name: id})
+ }
+ mtm := monitoring.NewMultiTenantMonitor(&config.Config{}, nil, nil)
+ setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{
+ orgID: newReportingMonitorForTest(t, state, nil),
+ })
+ return NewReportingHandlers(mtm, nil)
+}
diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.go
index 37254e61c6..ae00e3ec89 100644
--- a/internal/api/router_routes_licensing.go
+++ b/internal/api/router_routes_licensing.go
@@ -149,57 +149,60 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHan
RequireLicenseFeature(r.licenseHandlers, featureRBACValue, rbacAdminEndpoints.HandleAdminReset)(w, req)
}))
- // Advanced Reporting routes
+ // Advanced Reporting routes. They are org-bound: every report reads only
+ // the request organization's inventory and metrics store, and schedules
+ // live in that organization's config, so an org manager may use them in
+ // their own organization.
r.mux.HandleFunc("/api/admin/reports/catalog", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireScope(config.ScopeSettingsRead, reportingAdminEndpoints.HandleGetReportingCatalog)(w, req)
}))
r.mux.HandleFunc("/api/admin/reports/generate", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsRead, reportingAdminEndpoints.HandleGenerateReport))(w, req)
}))
r.mux.HandleFunc("/api/admin/reports/generate-multi", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsRead, reportingAdminEndpoints.HandleGenerateMultiReport))(w, req)
}))
r.mux.HandleFunc("/api/admin/reports/inventory/vms/export", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsRead, reportingAdminEndpoints.HandleExportVMInventory))(w, req)
}))
r.mux.HandleFunc("GET /api/admin/reports/schedules", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsRead, reportingScheduleEndpoints.HandleListReportSchedules))(w, req)
}))
r.mux.HandleFunc("POST /api/admin/reports/schedules", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsWrite, reportingScheduleEndpoints.HandleCreateReportSchedule))(w, req)
}))
r.mux.HandleFunc("PUT /api/admin/reports/schedules/{id}", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsWrite, reportingScheduleEndpoints.HandleUpdateReportSchedule))(w, req)
}))
r.mux.HandleFunc("DELETE /api/admin/reports/schedules/{id}", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsWrite, reportingScheduleEndpoints.HandleDeleteReportSchedule))(w, req)
}))
r.mux.HandleFunc("POST /api/admin/reports/schedules/{id}/run", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceNodes, func(w http.ResponseWriter, req *http.Request) {
- if !ensureAdminSession(r.config, w, req) {
+ if !ensureOrgAdminSession(r.config, w, req) {
return
}
RequireLicenseFeature(r.licenseHandlers, featureAdvancedReportingValue, RequireScope(config.ScopeSettingsWrite, reportingScheduleEndpoints.HandleRunReportSchedule))(w, req)
diff --git a/internal/api/security_status_capabilities.go b/internal/api/security_status_capabilities.go
index 89ffe71040..0189737d9a 100644
--- a/internal/api/security_status_capabilities.go
+++ b/internal/api/security_status_capabilities.go
@@ -285,15 +285,20 @@ func (r *Router) securityStatusSettingsCapabilitiesFromSnapshot(snapshot securit
canReadReporting := canReadSettings &&
r.canAccessPermissionSurface(snapshot, internalauth.ActionRead, internalauth.ResourceNodes, config.ScopeSettingsRead)
- // Infrastructure and availability are org-bound: their routes use
- // RequireOrgAdmin / ensureOrgAdminSession, which admit an org manager
+ // Infrastructure, availability, and reporting are org-bound: their routes
+ // use RequireOrgAdmin / ensureOrgAdminSession, which admit an org manager
// inside their own organization, and their handlers read that
- // organization's config and monitor state. A provider opening a client
- // workspace lands there as the org owner, and without these the settings
- // navigation hides the pages that connect the client's systems. Every other
- // capability, reporting included, stays instance administration: report
- // generation still reads metrics from the instance's default store.
+ // organization's config, monitor state and metrics store. A provider
+ // opening a client workspace lands there as the org owner, and without
+ // these the settings navigation hides the pages that connect the client's
+ // systems and build its reports. Reporting also needs read:nodes, which
+ // RequirePermission checks before the session rule. Every other capability
+ // stays instance administration.
canReadOrgSettings := canReadSettings || snapshot.sessionManagesOrg
+ if snapshot.sessionManagesOrg && !canReadReporting {
+ allowed, err := r.authorizer.Authorize(snapshot.request.Context(), internalauth.ActionRead, internalauth.ResourceNodes)
+ canReadReporting = err == nil && allowed
+ }
return securityStatusSettingsCapabilities{
InfrastructureRead: canReadOrgSettings,
diff --git a/pkg/reporting/engine.go b/pkg/reporting/engine.go
index 69174cb6ac..fe827d4b6f 100644
--- a/pkg/reporting/engine.go
+++ b/pkg/reporting/engine.go
@@ -2,6 +2,7 @@ package reporting
import (
"context"
+ "errors"
"fmt"
"sort"
"strings"
@@ -21,6 +22,7 @@ const narrativeTimeout = 30 * time.Second
type ReportEngine struct {
metricsStore *metrics.Store
metricsStoreGetter func() *metrics.Store
+ metricsStoreForOrg func(orgID string) (*metrics.Store, error)
csvGen *CSVGenerator
pdfGen *PDFGenerator
}
@@ -36,6 +38,13 @@ type EngineConfig struct {
// When set, this is used instead of MetricsStore, ensuring queries
// always target the active store even after monitor reloads.
MetricsStoreGetter func() *metrics.Store
+
+ // MetricsStoreForOrg resolves the metrics store of the organization a
+ // request belongs to. When set it replaces MetricsStore and
+ // MetricsStoreGetter, and a request without an OrgID is refused, so a
+ // report on a multi-tenant install can only read the metrics of the
+ // organization it was requested in.
+ MetricsStoreForOrg func(orgID string) (*metrics.Store, error)
}
// NewReportEngine creates a new reporting engine.
@@ -43,18 +52,43 @@ func NewReportEngine(cfg EngineConfig) *ReportEngine {
return &ReportEngine{
metricsStore: cfg.MetricsStore,
metricsStoreGetter: cfg.MetricsStoreGetter,
+ metricsStoreForOrg: cfg.MetricsStoreForOrg,
csvGen: NewCSVGenerator(),
pdfGen: NewPDFGenerator(),
}
}
-// getMetricsStore returns the current metrics store, preferring the dynamic
-// getter over the static reference.
-func (e *ReportEngine) getMetricsStore() *metrics.Store {
+// ErrReportOrgRequired is returned when an engine that resolves metrics per
+// organization receives a request that does not name one.
+var ErrReportOrgRequired = errors.New("report request does not name an organization")
+
+// metricsStoreFor returns the metrics store a request for orgID reads. An
+// engine configured with MetricsStoreForOrg resolves the organization's own
+// store and refuses a request without one; otherwise the single configured
+// store is used, preferring the dynamic getter over the static reference.
+func (e *ReportEngine) metricsStoreFor(orgID string) (*metrics.Store, error) {
+ if e.metricsStoreForOrg != nil {
+ orgID = strings.TrimSpace(orgID)
+ if orgID == "" {
+ return nil, ErrReportOrgRequired
+ }
+ store, err := e.metricsStoreForOrg(orgID)
+ if err != nil {
+ return nil, fmt.Errorf("metrics store for organization %q: %w", orgID, err)
+ }
+ if store == nil {
+ return nil, fmt.Errorf("metrics store not initialized for organization %q", orgID)
+ }
+ return store, nil
+ }
+ store := e.metricsStore
if e.metricsStoreGetter != nil {
- return e.metricsStoreGetter()
+ store = e.metricsStoreGetter()
+ }
+ if store == nil {
+ return nil, fmt.Errorf("metrics store not initialized")
}
- return e.metricsStore
+ return store, nil
}
// CanonicalResourceType normalizes report resource type inputs to canonical v6 names.
@@ -158,8 +192,8 @@ func mergeMetricMapsByTimestamp(dst, src map[string][]metrics.MetricPoint) {
// Generate creates a report in the specified format.
func (e *ReportEngine) Generate(req MetricReportRequest) (data []byte, contentType string, err error) {
- if e.getMetricsStore() == nil {
- return nil, "", fmt.Errorf("metrics store not initialized")
+ if _, err := e.metricsStoreFor(req.OrgID); err != nil {
+ return nil, "", err
}
// Query metrics data
@@ -287,7 +321,10 @@ func (e *ReportEngine) queryMetrics(req MetricReportRequest) (*ReportData, error
data.Disks = req.Disks
data.Availability = req.Availability
- store := e.getMetricsStore()
+ store, err := e.metricsStoreFor(req.OrgID)
+ if err != nil {
+ return nil, err
+ }
storeTypes := metricsStoreResourceTypes(canonicalType)
if len(storeTypes) == 0 {
storeTypes = []string{canonicalType}
@@ -380,8 +417,8 @@ func (e *ReportEngine) queryMetrics(req MetricReportRequest) (*ReportData, error
// GenerateMulti creates a multi-resource report in the specified format.
func (e *ReportEngine) GenerateMulti(req MultiReportRequest) (data []byte, contentType string, err error) {
- if e.getMetricsStore() == nil {
- return nil, "", fmt.Errorf("metrics store not initialized")
+ if _, err := e.metricsStoreFor(req.OrgID); err != nil {
+ return nil, "", err
}
multiData := &MultiReportData{
@@ -405,6 +442,7 @@ func (e *ReportEngine) GenerateMulti(req MultiReportRequest) (data []byte, conte
resReq.End = req.End
resReq.MetricType = req.MetricType
resReq.Branding = req.Branding
+ resReq.OrgID = req.OrgID
if resReq.Narrator == nil {
resReq.Narrator = req.Narrator
}
@@ -510,10 +548,6 @@ func (e *ReportEngine) attachNarrative(reportData *ReportData, req MetricReportR
// (same length, ending at req.Start). Returns nil when the window is empty
// or the metrics store has no data for the prior range.
func (e *ReportEngine) priorPeriodFor(req MetricReportRequest) *PriorPeriodInput {
- store := e.getMetricsStore()
- if store == nil {
- return nil
- }
duration := req.End.Sub(req.Start)
if duration <= 0 {
return nil
@@ -583,8 +617,8 @@ func (e *ReportEngine) attachFleetNarrative(multiData *MultiReportData, req Mult
// resolution, same fail-closed-to-heuristic fallback as Generate; just
// no fpdf/csv output stage.
func (e *ReportEngine) NarrativeFor(req MetricReportRequest) (*Narrative, error) {
- if e.getMetricsStore() == nil {
- return nil, fmt.Errorf("metrics store not initialized")
+ if _, err := e.metricsStoreFor(req.OrgID); err != nil {
+ return nil, err
}
reportData, err := e.queryMetrics(req)
if err != nil {
@@ -604,8 +638,8 @@ func (e *ReportEngine) NarrativeFor(req MetricReportRequest) (*Narrative, error)
// subset of resources failed (the narrator is given what loaded, and
// the failed-resource list is logged at warn level by queryMetrics).
func (e *ReportEngine) FleetNarrativeFor(req MultiReportRequest) (*FleetNarrative, error) {
- if e.getMetricsStore() == nil {
- return nil, fmt.Errorf("metrics store not initialized")
+ if _, err := e.metricsStoreFor(req.OrgID); err != nil {
+ return nil, err
}
multiData := &MultiReportData{
Title: req.Title,
@@ -621,6 +655,7 @@ func (e *ReportEngine) FleetNarrativeFor(req MultiReportRequest) (*FleetNarrativ
resReq.Start = req.Start
resReq.End = req.End
resReq.MetricType = req.MetricType
+ resReq.OrgID = req.OrgID
if resReq.Narrator == nil {
resReq.Narrator = req.Narrator
}
diff --git a/pkg/reporting/engine_org_scope_test.go b/pkg/reporting/engine_org_scope_test.go
new file mode 100644
index 0000000000..1717aa042e
--- /dev/null
+++ b/pkg/reporting/engine_org_scope_test.go
@@ -0,0 +1,121 @@
+package reporting
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
+)
+
+func newOrgScopeTestStore(t *testing.T, cpu float64, now time.Time) *metrics.Store {
+ t.Helper()
+ store, err := metrics.NewStore(metrics.StoreConfig{
+ DBPath: filepath.Join(t.TempDir(), "metrics.db"),
+ WriteBufferSize: 10,
+ FlushInterval: 100 * time.Millisecond,
+ RetentionRaw: 24 * time.Hour,
+ RetentionMinute: 7 * 24 * time.Hour,
+ RetentionHourly: 30 * 24 * time.Hour,
+ RetentionDaily: 90 * 24 * time.Hour,
+ })
+ if err != nil {
+ t.Fatalf("create metrics store: %v", err)
+ }
+ t.Cleanup(func() { store.Close() })
+ // Both organizations record the same resource ID, so only the store a
+ // query lands on decides which value comes back.
+ for i := 0; i < 6; i++ {
+ store.Write("node", "shared-node", "cpu", cpu, now.Add(time.Duration(-30+i*5)*time.Minute))
+ }
+ store.Flush()
+ return store
+}
+
+func newOrgScopedTestEngine(t *testing.T, now time.Time) *ReportEngine {
+ t.Helper()
+ stores := map[string]*metrics.Store{
+ "org-a": newOrgScopeTestStore(t, 11, now),
+ "org-b": newOrgScopeTestStore(t, 77, now),
+ }
+ return NewReportEngine(EngineConfig{
+ MetricsStoreForOrg: func(orgID string) (*metrics.Store, error) {
+ store, ok := stores[orgID]
+ if !ok {
+ return nil, fmt.Errorf("organization %q is not provisioned", orgID)
+ }
+ return store, nil
+ },
+ })
+}
+
+func orgScopeTestRequest(orgID string, now time.Time) MetricReportRequest {
+ return MetricReportRequest{
+ OrgID: orgID,
+ ResourceType: "node",
+ ResourceID: "shared-node",
+ MetricType: "cpu",
+ Start: now.Add(-time.Hour),
+ End: now.Add(time.Minute),
+ Format: FormatCSV,
+ }
+}
+
+func TestReportEngineRefusesRequestsWithoutAnOrganization(t *testing.T) {
+ now := time.Now()
+ engine := newOrgScopedTestEngine(t, now)
+
+ req := orgScopeTestRequest("", now)
+ if _, _, err := engine.Generate(req); !errors.Is(err, ErrReportOrgRequired) {
+ t.Fatalf("Generate without org: got %v, want ErrReportOrgRequired", err)
+ }
+ if _, err := engine.NarrativeFor(req); !errors.Is(err, ErrReportOrgRequired) {
+ t.Fatalf("NarrativeFor without org: got %v, want ErrReportOrgRequired", err)
+ }
+ if _, err := engine.MetricEvidenceFor(context.Background(), req); !errors.Is(err, ErrReportOrgRequired) {
+ t.Fatalf("MetricEvidenceFor without org: got %v, want ErrReportOrgRequired", err)
+ }
+ multi := MultiReportRequest{
+ Resources: []MetricReportRequest{orgScopeTestRequest("org-a", now)},
+ Start: req.Start,
+ End: req.End,
+ Format: FormatCSV,
+ }
+ if _, _, err := engine.GenerateMulti(multi); !errors.Is(err, ErrReportOrgRequired) {
+ t.Fatalf("GenerateMulti without org: got %v, want ErrReportOrgRequired", err)
+ }
+ if _, err := engine.FleetNarrativeFor(multi); !errors.Is(err, ErrReportOrgRequired) {
+ t.Fatalf("FleetNarrativeFor without org: got %v, want ErrReportOrgRequired", err)
+ }
+ if _, _, err := engine.Generate(orgScopeTestRequest("org-unknown", now)); err == nil {
+ t.Fatal("Generate for an unprovisioned organization should fail")
+ }
+}
+
+func TestReportEngineMultiReportUsesTheRequestOrganizationForEveryResource(t *testing.T) {
+ now := time.Now()
+ engine := newOrgScopedTestEngine(t, now)
+
+ // A resource entry naming another organization must not redirect its
+ // query: the multi-report's organization applies to all of them.
+ resource := orgScopeTestRequest("org-a", now)
+ data, _, err := engine.GenerateMulti(MultiReportRequest{
+ OrgID: "org-b",
+ Resources: []MetricReportRequest{resource},
+ Start: resource.Start,
+ End: resource.End,
+ MetricType: "cpu",
+ Format: FormatCSV,
+ })
+ if err != nil {
+ t.Fatalf("GenerateMulti: %v", err)
+ }
+ csv := string(data)
+ if !strings.Contains(csv, "77.00") || strings.Contains(csv, "11.00") {
+ t.Fatalf("multi-report for org-b should carry only org-b's values, got:\n%s", csv)
+ }
+}
diff --git a/pkg/reporting/evidence.go b/pkg/reporting/evidence.go
index f2d31e812d..5f24df0d84 100644
--- a/pkg/reporting/evidence.go
+++ b/pkg/reporting/evidence.go
@@ -2,7 +2,6 @@ package reporting
import (
"context"
- "fmt"
"time"
)
@@ -41,8 +40,8 @@ func (e *ReportEngine) MetricEvidenceFor(ctx context.Context, req MetricReportRe
if err := ctx.Err(); err != nil {
return nil, err
}
- if e.getMetricsStore() == nil {
- return nil, fmt.Errorf("metrics store not initialized")
+ if _, err := e.metricsStoreFor(req.OrgID); err != nil {
+ return nil, err
}
data, err := e.queryMetrics(req)
if err != nil {
diff --git a/pkg/reporting/evidence_test.go b/pkg/reporting/evidence_test.go
index 158134ad93..058539e740 100644
--- a/pkg/reporting/evidence_test.go
+++ b/pkg/reporting/evidence_test.go
@@ -65,3 +65,24 @@ func TestMetricEvidenceRetainsObservedCoverageAcrossRestart(t *testing.T) {
_, err = engine.MetricEvidenceFor(ctx, req)
require.ErrorIs(t, err, context.Canceled)
}
+
+// Retained metric evidence backs Pulse Assistant's pulse_summarize, so it
+// must read only the requesting organization's store, as reports do.
+func TestReportEngineReadsOnlyTheRequestOrganizationsMetrics(t *testing.T) {
+ now := time.Now()
+ engine := newOrgScopedTestEngine(t, now)
+
+ for orgID, want := range map[string]float64{"org-a": 11, "org-b": 77} {
+ evidence, err := engine.MetricEvidenceFor(context.Background(), orgScopeTestRequest(orgID, now))
+ if err != nil {
+ t.Fatalf("%s: evidence: %v", orgID, err)
+ }
+ stats, ok := evidence.Metrics["cpu"]
+ if !ok || stats.RetainedPoints == 0 {
+ t.Fatalf("%s: expected cpu points from its own store, got %#v", orgID, evidence.Metrics)
+ }
+ if stats.Min != want || stats.Max != want {
+ t.Fatalf("%s: read cpu %v..%v, want only its own value %v", orgID, stats.Min, stats.Max, want)
+ }
+ }
+}
diff --git a/pkg/reporting/reporting.go b/pkg/reporting/reporting.go
index 7f3da336d7..a4daa601bb 100644
--- a/pkg/reporting/reporting.go
+++ b/pkg/reporting/reporting.go
@@ -23,6 +23,11 @@ type MetricReportRequest struct {
Title string
Branding ReportBranding
+ // OrgID is the organization the report is generated for. An engine that
+ // resolves metrics per organization reads only this organization's
+ // metrics store and refuses a request that leaves it empty.
+ OrgID string
+
// MetricsResourceID overrides ResourceID for metrics-store queries.
// The v6 API addresses resources by canonical unified ID while the
// metrics store is keyed by each platform's native source ID (the
@@ -193,6 +198,10 @@ type MultiReportRequest struct {
MetricType string
Branding ReportBranding
+ // OrgID is the organization the report is generated for. It applies to
+ // every resource in Resources, overriding any OrgID they carry.
+ OrgID string
+
// Optional fleet-level narrative interpretation. When FleetNarrator is
// non-nil the engine builds a FleetNarrativeInput from the queried
// per-resource report data and asks it to produce the cross-resource
diff --git a/pkg/server/reporting_engine.go b/pkg/server/reporting_engine.go
new file mode 100644
index 0000000000..3830f7845b
--- /dev/null
+++ b/pkg/server/reporting_engine.go
@@ -0,0 +1,30 @@
+package server
+
+import (
+ "fmt"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+)
+
+// newOrgScopedReportEngine builds the standard report engine. Each report
+// reads the metrics store of the organization it was requested in, resolved
+// per request through the current multi-tenant monitor so it follows monitor
+// reloads (which close and recreate the stores). The engine refuses a request
+// that names no organization rather than falling back to the default one.
+func newOrgScopedReportEngine(multiTenantMonitor func() *monitoring.MultiTenantMonitor) *reporting.ReportEngine {
+ return reporting.NewReportEngine(reporting.EngineConfig{
+ MetricsStoreForOrg: func(orgID string) (*metrics.Store, error) {
+ mtMonitor := multiTenantMonitor()
+ if mtMonitor == nil {
+ return nil, fmt.Errorf("monitoring is not running")
+ }
+ monitor, err := mtMonitor.GetMonitor(orgID)
+ if err != nil {
+ return nil, err
+ }
+ return monitor.GetMetricsStore(), nil
+ },
+ })
+}
diff --git a/pkg/server/reporting_engine_test.go b/pkg/server/reporting_engine_test.go
new file mode 100644
index 0000000000..224fa1c2e5
--- /dev/null
+++ b/pkg/server/reporting_engine_test.go
@@ -0,0 +1,60 @@
+package server
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+)
+
+func TestOrgScopedReportEngineResolvesTheRequestOrganizationsStore(t *testing.T) {
+ baseDir := t.TempDir()
+ mtm := monitoring.NewMultiTenantMonitor(&config.Config{DataPath: baseDir}, config.NewMultiTenantPersistence(baseDir), nil)
+ t.Cleanup(mtm.Stop)
+ monitor, err := mtm.GetMonitor("default")
+ if err != nil {
+ t.Fatalf("GetMonitor(default): %v", err)
+ }
+ store := monitor.GetMetricsStore()
+ if store == nil {
+ t.Fatal("default monitor has no metrics store")
+ }
+ now := time.Now()
+ store.Write("node", "node-1", "cpu", 42, now.Add(-10*time.Minute))
+ store.Flush()
+
+ engine := newOrgScopedReportEngine(func() *monitoring.MultiTenantMonitor { return mtm })
+ request := func(orgID string) reporting.MetricReportRequest {
+ return reporting.MetricReportRequest{
+ OrgID: orgID,
+ ResourceType: "node",
+ ResourceID: "node-1",
+ Start: now.Add(-time.Hour),
+ End: now.Add(time.Minute),
+ }
+ }
+
+ evidence, err := engine.MetricEvidenceFor(context.Background(), request("default"))
+ if err != nil {
+ t.Fatalf("default organization evidence: %v", err)
+ }
+ if stats := evidence.Metrics["cpu"]; stats.RetainedPoints == 0 || stats.Latest != 42 {
+ t.Fatalf("default organization evidence = %+v, want its own store's cpu reading", evidence.Metrics)
+ }
+
+ if _, err := engine.MetricEvidenceFor(context.Background(), request("")); !errors.Is(err, reporting.ErrReportOrgRequired) {
+ t.Fatalf("request without organization: got %v, want ErrReportOrgRequired", err)
+ }
+ if _, err := engine.MetricEvidenceFor(context.Background(), request("org-not-provisioned")); err == nil {
+ t.Fatal("an unprovisioned organization must not fall back to the default store")
+ }
+
+ stopped := newOrgScopedReportEngine(func() *monitoring.MultiTenantMonitor { return nil })
+ if _, err := stopped.MetricEvidenceFor(context.Background(), request("default")); err == nil {
+ t.Fatal("an engine without a running monitor must refuse requests")
+ }
+}
diff --git a/pkg/server/server.go b/pkg/server/server.go
index 4b6f849541..4cc70a9280 100644
--- a/pkg/server/server.go
+++ b/pkg/server/server.go
@@ -402,18 +402,10 @@ func Run(ctx context.Context, version string) (runErr error) {
// Initialize reporting engine if not already set by enterprise hooks.
// This ensures Pro license holders get reporting even with the standard binary.
- // Uses a dynamic store getter so the engine always queries the current monitor's
- // metrics store, even after monitor reloads (which close and recreate the store).
+ // Each report reads only its own organization's metrics store.
if reporting.GetEngine() == nil {
- if store := reloadableMonitor.GetMonitor().GetMetricsStore(); store != nil {
- engine := reporting.NewReportEngine(reporting.EngineConfig{
- MetricsStoreGetter: func() *metrics.Store {
- return reloadableMonitor.GetMonitor().GetMetricsStore()
- },
- })
- reporting.SetEngine(engine)
- log.Info().Msg("Advanced Infrastructure Reporting (PDF/CSV) initialized")
- }
+ reporting.SetEngine(newOrgScopedReportEngine(reloadableMonitor.GetMultiTenantMonitor))
+ log.Info().Msg("Advanced Infrastructure Reporting (PDF/CSV) initialized")
}
// WebSocket state ownership is tenant-aware by construction, including default-org state.