diff --git a/docs/API.md b/docs/API.md index c5c956148c..96157963b0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1663,7 +1663,7 @@ Returns organizations accessible to the authenticated user. ```json { "id": "acme-corp", "displayName": "Acme Corporation" } ``` -The creator becomes the owner and first member. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example. +The creator becomes the owner and first member. A user who is not an instance administrator can own at most 20 organizations. Past that the request returns `409` with `organization_limit_reached`. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example. ### Get Organization `GET /api/orgs/{id}` (requires `settings:read`) @@ -1689,7 +1689,7 @@ Returns all members with their roles. User must be a member of the org. ```json { "userId": "jane", "role": "editor" } ``` -Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role; there is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Default org members cannot be managed. +Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role. There is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Unless either is an instance administrator, a new owner who already owns 20 organizations is refused with `409` `organization_limit_reached`. Default org members cannot be managed. ### Remove Member `DELETE /api/orgs/{id}/members/{userId}` (requires `settings:write`, session auth only) diff --git a/docs/MULTI_TENANT.md b/docs/MULTI_TENANT.md index 22a98a7641..ff8aeff2ca 100644 --- a/docs/MULTI_TENANT.md +++ b/docs/MULTI_TENANT.md @@ -100,7 +100,10 @@ signed-in UI with its session and CSRF protection. {"id": "production-datacenter", "displayName": "Production Datacenter"} ``` -The creator becomes the owner. `id` is a stable ID of 1–64 characters using +The creator becomes the owner. A user who is not an instance administrator +can own at most 20 organizations: past that, creating one, or being handed one +by another such user, returns `409` with `organization_limit_reached`. +`id` is a stable ID of 1–64 characters using letters, digits, periods, underscores or hyphens, but not `.` or `..`; use a simple lowercase/hyphen ID such as the example. `displayName` is the name shown in Pulse. `name` and `description` are not the creation fields. diff --git a/frontend-modern/public/docs/API.md b/frontend-modern/public/docs/API.md index c5c956148c..96157963b0 100644 --- a/frontend-modern/public/docs/API.md +++ b/frontend-modern/public/docs/API.md @@ -1663,7 +1663,7 @@ Returns organizations accessible to the authenticated user. ```json { "id": "acme-corp", "displayName": "Acme Corporation" } ``` -The creator becomes the owner and first member. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example. +The creator becomes the owner and first member. A user who is not an instance administrator can own at most 20 organizations. Past that the request returns `409` with `organization_limit_reached`. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example. ### Get Organization `GET /api/orgs/{id}` (requires `settings:read`) @@ -1689,7 +1689,7 @@ Returns all members with their roles. User must be a member of the org. ```json { "userId": "jane", "role": "editor" } ``` -Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role; there is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Default org members cannot be managed. +Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role. There is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Unless either is an instance administrator, a new owner who already owns 20 organizations is refused with `409` `organization_limit_reached`. Default org members cannot be managed. ### Remove Member `DELETE /api/orgs/{id}/members/{userId}` (requires `settings:write`, session auth only) diff --git a/frontend-modern/public/docs/MULTI_TENANT.md b/frontend-modern/public/docs/MULTI_TENANT.md index 22a98a7641..ff8aeff2ca 100644 --- a/frontend-modern/public/docs/MULTI_TENANT.md +++ b/frontend-modern/public/docs/MULTI_TENANT.md @@ -100,7 +100,10 @@ signed-in UI with its session and CSRF protection. {"id": "production-datacenter", "displayName": "Production Datacenter"} ``` -The creator becomes the owner. `id` is a stable ID of 1–64 characters using +The creator becomes the owner. A user who is not an instance administrator +can own at most 20 organizations: past that, creating one, or being handed one +by another such user, returns `409` with `organization_limit_reached`. +`id` is a stable ID of 1–64 characters using letters, digits, periods, underscores or hyphens, but not `.` or `..`; use a simple lowercase/hyphen ID such as the example. `displayName` is the name shown in Pulse. `name` and `description` are not the creation fields. diff --git a/frontend-modern/src/utils/__tests__/docsLinks.test.ts b/frontend-modern/src/utils/__tests__/docsLinks.test.ts index f5753d5d50..6894e784d3 100644 --- a/frontend-modern/src/utils/__tests__/docsLinks.test.ts +++ b/frontend-modern/src/utils/__tests__/docsLinks.test.ts @@ -331,6 +331,19 @@ describe('docsLinks', () => { ); }); + it('documents the organization ownership limit where organizations are created and handed over', () => { + const api = apiReference(); + expect(api).toContain( + 'A user who is not an instance administrator can own at most 20 organizations. Past that the request returns `409` with `organization_limit_reached`.', + ); + expect(api).toContain( + 'a new owner who already owns 20 organizations is refused with `409` `organization_limit_reached`', + ); + expect(readFileSync(path.join(repoRoot, 'docs', 'MULTI_TENANT.md'), 'utf8')).toContain( + 'returns `409` with `organization_limit_reached`', + ); + }); + it('separates server removal from persistent-data erasure', () => { const installation = readFileSync(path.join(repoRoot, 'docs', 'INSTALL.md'), 'utf8'); const removal = installation.split('## 🗑️ Uninstall')[1]; diff --git a/internal/api/agent_resource_context_test.go b/internal/api/agent_resource_context_test.go index 1719393c45..18787783c2 100644 --- a/internal/api/agent_resource_context_test.go +++ b/internal/api/agent_resource_context_test.go @@ -1475,6 +1475,64 @@ func TestAgentOperationsLoopExternalAgentTokenReadyUsesPulseMCPSurfaceScopes(t * } } +// The readiness check clones every token record until one covers the Pulse +// MCP surface. A bound collector may repeat its own authority reduction, and +// each call assigns keys of the live record's Metadata map under config.Mu, so +// the provider must read a detached copy taken under that lock: a map shared +// with the live inventory ends the process with "concurrent map iteration and +// map write". Run with -race: a shared map is reported as a data race. +func TestExternalAgentReadinessReadsTheTokenInventoryUnderTheConfigLock(t *testing.T) { + record, err := config.NewAPITokenRecord("readiness-collector-test.12345678", "collector", []string{ + config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentExec, + }) + if err != nil { + t.Fatal(err) + } + record.OrgID = "default" + record.Metadata = map[string]string{"bound_agent_id": "agent-a", "bound_hostname": "node.example"} + cfg := &config.Config{DataPath: t.TempDir(), APITokens: []config.APITokenRecord{*record}} + router := newTestRouter(t, cfg, nil, nil, nil, nil, "test") + + stop := make(chan struct{}) + writerDone := make(chan struct{}) + writerStatus := make(chan int, 1) + go func() { + defer close(writerDone) + for { + select { + case <-stop: + return + default: + } + req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", + strings.NewReader(`{"agentId":"agent-a","hostname":"node.example"}`)) + req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "default")) + attachAPITokenRecord(req, record) + rec := httptest.NewRecorder() + router.handleReduceCollectorAuthority(rec, req) + if rec.Code != http.StatusNoContent { + writerStatus <- rec.Code + return + } + } + }() + + manifest := agentcapabilities.CanonicalManifest() + for i := 0; i < 2000; i++ { + if router.agentContextHandler.agentOperationsLoopExternalAgentReady(context.Background(), manifest, time.Now().UTC()) { + t.Fatal("a collector credential must not satisfy external-agent readiness") + } + } + + close(stop) + <-writerDone + select { + case status := <-writerStatus: + t.Fatalf("repeated collector authority reduction answered %d, want 204", status) + default: + } +} + func TestHandleAgentOperationsLoopStatus_AggregatesContentSafeLoopCounts(t *testing.T) { h, findings, approvals := fleetFixtureHandlers(t, []unified.Resource{ {ID: "vm:101", Type: "vm", Name: "db-01"}, diff --git a/internal/api/auth.go b/internal/api/auth.go index 639e0c64a3..c68ee8cb00 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -594,6 +594,19 @@ func validateAPITokenAgainstConfigsLocked(globalCfg, targetCfg *config.Config, t return validateAPITokenLocked(globalCfg, token) } +// tenantMonitorOutsideConfigLock requires config.Mu.RLock and returns with it +// held again. Resolving a cold tenant constructs its monitor, which waits for +// that tenant's connections and for the manager's settings lock. Holding +// config.Mu across that wait stalls every request behind the first queued +// token writer, and deadlocks against a settings save, which takes config.Mu +// while holding the settings lock. Callers must recheck the owner after +// validating against the returned monitor's config. +func tenantMonitorOutsideConfigLock(mtm *monitoring.MultiTenantMonitor, orgID string) (*monitoring.Monitor, error) { + config.Mu.RUnlock() + defer config.Mu.RLock() + return mtm.GetMonitor(orgID) +} + // CheckProxyAuth validates proxy authentication headers func CheckProxyAuth(cfg *config.Config, r *http.Request) (bool, string, bool) { // Check if proxy auth is configured @@ -1444,7 +1457,10 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantM } } - if mtm != nil { + // A tenant inventory is consulted only for an explicit token. A request + // without one must not resolve, and so possibly start, the monitor of + // whichever organization it names. + if mtm != nil && explicitTokenProvided { // Check for Tenant ID in header or cookie orgID := "default" if headerOrgID := r.Header.Get("X-Pulse-Org-ID"); headerOrgID != "" { @@ -1457,7 +1473,7 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantM if orgID != "default" { // Prevent DoS: Check if org exists before loading (which triggers directory creation) if mtm.OrgExists(orgID) { - if m, err := mtm.GetMonitor(orgID); err == nil && m != nil { + if m, err := tenantMonitorOutsideConfigLock(mtm, orgID); err == nil && m != nil { targetConfig = m.GetConfig() targetOrgID = strings.TrimSpace(orgID) } diff --git a/internal/api/auth_context_tenant_test.go b/internal/api/auth_context_tenant_test.go index 07dc8415f4..09815809d8 100644 --- a/internal/api/auth_context_tenant_test.go +++ b/internal/api/auth_context_tenant_test.go @@ -390,3 +390,59 @@ func TestAuthContextMiddlewareUsesCurrentTenantManager(t *testing.T) { }) } } + +// The auth context runs for every request before any credential is enforced. +// It must not start the tenant a request merely names, and a token request +// that does need a cold tenant's inventory must not hold config.Mu while that +// tenant starts: every token check queues as a writer behind that reader, and +// a settings save takes config.Mu under the lock the start is waiting for. +func TestExtractAndStoreAuthContextResolvesColdTenantOutsideConfigLock(t *testing.T) { + const orgID = "starting" + dir := t.TempDir() + mtp := config.NewMultiTenantPersistence(dir) + if _, err := mtp.GetPersistence(orgID); err != nil { + t.Fatal(err) + } + cfg := &config.Config{DataPath: dir, ConfigPath: dir} + manager := monitoring.NewMultiTenantMonitor(cfg, mtp, nil) + t.Cleanup(manager.Stop) + starts, startsUnderConfigLock := 0, 0 + manager.SetMonitorInitializer(func(*monitoring.Monitor) { + starts++ + writer := make(chan struct{}) + go func() { + config.Mu.Lock() + close(writer) + config.Mu.Unlock() + }() + select { + case <-writer: + case <-time.After(2 * time.Second): + startsUnderConfigLock++ + } + }) + newRequest := func(token string) *http.Request { + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.Header.Set("X-Pulse-Org-ID", orgID) + if token != "" { + req.Header.Set("X-API-Token", token) + } + return req + } + + extractAndStoreAuthContext(cfg, manager, newRequest("")) + if _, started := manager.PeekMonitor(orgID); started || starts != 0 { + t.Fatal("a request without credentials started the tenant it named") + } + + req := extractAndStoreAuthContext(cfg, manager, newRequest("unknown-token-123.12345678")) + if internalauth.GetUser(req.Context()) != "" || internalauth.GetAPIToken(req.Context()) != nil { + t.Fatal("unknown token must not receive user or API token context") + } + if _, started := manager.PeekMonitor(orgID); !started || starts != 1 { + t.Fatalf("tenant token inventory was not resolved (starts = %d)", starts) + } + if startsUnderConfigLock != 0 { + t.Fatal("config.Mu was held while the tenant monitor started") + } +} diff --git a/internal/api/connections_alerts.go b/internal/api/connections_alerts.go index 138dc589c7..98d9605da0 100644 --- a/internal/api/connections_alerts.go +++ b/internal/api/connections_alerts.go @@ -41,7 +41,7 @@ func buildAggregatorInputsWithRuntimeSources( if monitor != nil && monitor.GetConfig() == cfg { inputs.apiTokens = monitor.APITokenSnapshot() } else { - inputs.apiTokens = append([]config.APITokenRecord(nil), cfg.APITokens...) + inputs.apiTokens = snapshotAPITokenRecords(cfg) } inputs.agentTokenInventoryKnown = true inputs.pvePollingInterval = cfg.PVEPollingInterval diff --git a/internal/api/hosted_signup_handlers_test.go b/internal/api/hosted_signup_handlers_test.go index 839c31ae7c..6788feda8b 100644 --- a/internal/api/hosted_signup_handlers_test.go +++ b/internal/api/hosted_signup_handlers_test.go @@ -12,6 +12,8 @@ import ( "time" "github.com/rcourtman/pulse-go-rewrite/internal/config" + "github.com/rcourtman/pulse-go-rewrite/internal/license/entitlements" + "github.com/rcourtman/pulse-go-rewrite/internal/models" "github.com/rcourtman/pulse-go-rewrite/pkg/auth" ) @@ -145,6 +147,160 @@ func TestHostedSignupHostedModeGate(t *testing.T) { } } +// A runtime the control plane provisioned for one workspace is reachable at +// that workspace's public address, and its organization, owner and entitlement +// come from the control plane. Its signup route must stay closed to everyone. +func TestHostedSignupClosedOnProvisionedWorkspaceRuntime(t *testing.T) { + t.Setenv("PULSE_TENANT_ID", "t-workspace") + router, persistence, _, emailer, baseDir := newHostedSignupTestRouter(t, true) + + addedAt := time.Unix(1700000000, 0).UTC() + if err := persistence.SaveOrganization(&models.Organization{ + ID: "t-workspace", + DisplayName: "Workspace", + CreatedAt: addedAt, + OwnerUserID: "u_workspace_owner", + OwnerEmail: "alice.smith@example.com", + Members: []models.OrganizationMember{ + {UserID: "u_workspace_owner", Email: "alice.smith@example.com", Role: models.OrgRoleOwner, AddedAt: addedAt, AddedBy: "u_workspace_owner"}, + }, + }); err != nil { + t.Fatalf("save workspace org: %v", err) + } + + for _, email := range []string{"alice.smith@example.com", "alice.\u017fmith@example.com", "stranger@example.com"} { + rec := doHostedSignupRequest(router, fmt.Sprintf(`{"email":%q,"org_name":"anything"}`, email)) + if rec.Code != http.StatusNotFound { + t.Fatalf("signup for %q on a provisioned runtime: expected 404, got %d: %s", email, rec.Code, rec.Body.String()) + } + } + + org, err := persistence.LoadOrganization("t-workspace") + if err != nil { + t.Fatalf("load workspace org: %v", err) + } + if org.OwnerUserID != "u_workspace_owner" || org.OwnerEmail != "alice.smith@example.com" { + t.Fatalf("workspace owner = (%q, %q), want it unchanged", org.OwnerUserID, org.OwnerEmail) + } + if len(org.Members) != 1 || org.Members[0].UserID != "u_workspace_owner" { + t.Fatalf("workspace members = %+v, want the owner unchanged", org.Members) + } + state, err := config.NewFileBillingStore(baseDir).GetBillingState("t-workspace") + if err != nil { + t.Fatalf("get workspace billing state: %v", err) + } + if state != nil { + t.Fatalf("expected no billing state beside the control plane's, got %+v", state) + } + orgs, err := persistence.ListOrganizations() + if err != nil { + t.Fatalf("list orgs: %v", err) + } + for _, listed := range orgs { + if listed != nil && listed.ID != "default" && listed.ID != "t-workspace" { + t.Fatalf("signup created organization %q inside a provisioned runtime", listed.ID) + } + } + + emailer.mu.Lock() + defer emailer.mu.Unlock() + if emailer.calls != 0 { + t.Fatalf("expected no magic link email, got %d", emailer.calls) + } +} + +// Signing up again with an owner's address resolves to the organization that +// owner already has. The request must not put it back on a trial. +func TestHostedSignupExistingOwnerKeepsBillingState(t *testing.T) { + router, persistence, _, emailer, baseDir := newHostedSignupTestRouter(t, true) + + first := doHostedSignupRequest(router, `{"email":"owner@example.com","org_name":"My Organization"}`) + if first.Code != http.StatusAccepted { + t.Fatalf("first signup expected 202, got %d: %s", first.Code, first.Body.String()) + } + orgID := requireHostedSignupProvisionedOrgID(t, persistence, "owner@example.com") + + store := config.NewFileBillingStore(baseDir) + seeded, err := store.GetBillingState(orgID) + if err != nil { + t.Fatalf("get seeded billing state: %v", err) + } + if seeded == nil || seeded.SubscriptionState != entitlements.SubStateTrial || seeded.PlanVersion != "cloud_trial" { + t.Fatalf("expected a seeded cloud trial for the new organization, got %+v", seeded) + } + if err := store.SaveBillingState(orgID, &entitlements.BillingState{ + Capabilities: seeded.Capabilities, + Limits: map[string]int64{"max_monitored_systems": 10}, + PlanVersion: "cloud_starter", + SubscriptionState: entitlements.SubStateActive, + }); err != nil { + t.Fatalf("save active billing state: %v", err) + } + + second := doHostedSignupRequest(router, `{"email":"Owner@Example.com","org_name":"Another Name"}`) + if second.Code != http.StatusAccepted { + t.Fatalf("second signup expected 202, got %d: %s", second.Code, second.Body.String()) + } + + state, err := store.GetBillingState(orgID) + if err != nil { + t.Fatalf("get billing state after second signup: %v", err) + } + if state == nil || state.SubscriptionState != entitlements.SubStateActive || state.PlanVersion != "cloud_starter" { + t.Fatalf("expected the active subscription to survive a repeated signup, got %+v", state) + } + if state.TrialStartedAt != nil || state.TrialEndsAt != nil { + t.Fatalf("expected no trial window on the active subscription, got started=%v ends=%v", state.TrialStartedAt, state.TrialEndsAt) + } + + emailer.mu.Lock() + defer emailer.mu.Unlock() + if emailer.calls != 2 { + t.Fatalf("expected a sign-in link for each accepted request, got %d", emailer.calls) + } +} + +// Rollback undoes what a failed signup created. An organization that was +// already there is not that request's to delete. +func TestHostedSignupExistingOrganizationSurvivesMagicLinkFailure(t *testing.T) { + router, persistence, rbacProvider, emailer, _ := newHostedSignupTestRouter(t, true) + + first := doHostedSignupRequest(router, `{"email":"owner@example.com","org_name":"My Organization"}`) + if first.Code != http.StatusAccepted { + t.Fatalf("first signup expected 202, got %d: %s", first.Code, first.Body.String()) + } + orgID := requireHostedSignupProvisionedOrgID(t, persistence, "owner@example.com") + before, err := persistence.LoadOrganization(orgID) + if err != nil { + t.Fatalf("load org: %v", err) + } + + emailer.mu.Lock() + emailer.err = fmt.Errorf("forced SendMagicLink failure") + emailer.mu.Unlock() + + second := doHostedSignupRequest(router, `{"email":"owner@example.com","org_name":"My Organization"}`) + if second.Code != http.StatusInternalServerError { + t.Fatalf("second signup expected 500, got %d: %s", second.Code, second.Body.String()) + } + + after, err := persistence.LoadOrganization(orgID) + if err != nil { + t.Fatalf("expected the existing organization to survive a failed repeat signup: %v", err) + } + if after.OwnerUserID != before.OwnerUserID || after.OwnerEmail != before.OwnerEmail || len(after.Members) != len(before.Members) { + t.Fatalf("existing organization changed: before=%+v after=%+v", before, after) + } + manager, err := rbacProvider.GetManager(orgID) + if err != nil { + t.Fatalf("get rbac manager: %v", err) + } + assignment, ok := manager.GetUserAssignment(before.OwnerUserID) + if !ok || !containsRoleID(assignment.RoleIDs, auth.RoleAdmin) { + t.Fatalf("expected the owner to keep the admin role, got %+v (found=%v)", assignment, ok) + } +} + func TestHostedSignupRateLimit(t *testing.T) { router, _, _, _, _ := newHostedSignupTestRouter(t, true) @@ -415,6 +571,7 @@ type captureMagicLinkEmailer struct { calls int to string magicLinkURL string + err error } func (c *captureMagicLinkEmailer) SendMagicLink(to, magicLinkURL string) error { @@ -423,5 +580,5 @@ func (c *captureMagicLinkEmailer) SendMagicLink(to, magicLinkURL string) error { c.calls++ c.to = to c.magicLinkURL = magicLinkURL - return nil + return c.err } diff --git a/internal/api/maintenance_verification.go b/internal/api/maintenance_verification.go index 8711dd8566..0569898f21 100644 --- a/internal/api/maintenance_verification.go +++ b/internal/api/maintenance_verification.go @@ -245,7 +245,7 @@ func (h *MaintenanceVerificationHandlers) HandleRerun(w http.ResponseWriter, r * http.Error(w, "Resource ID required", http.StatusBadRequest) return } - report, err := h.sentinel.EvaluateOnce(r.Context(), resourceID) + report, err := h.sentinel.EvaluateOnce(r.Context(), GetOrgID(r.Context()), resourceID) if err != nil { if isMaintenanceWindowMissing(err) { writeJSONError(w, http.StatusBadRequest, "maintenance_window_missing", err.Error()) diff --git a/internal/api/maintenance_verification_test.go b/internal/api/maintenance_verification_test.go index b6b992e66a..ebe105c885 100644 --- a/internal/api/maintenance_verification_test.go +++ b/internal/api/maintenance_verification_test.go @@ -106,6 +106,69 @@ func TestMaintenanceVerification_RerunWritesReport(t *testing.T) { } } +func TestMaintenanceVerification_RerunIsScopedToRequestOrg(t *testing.T) { + h, defaultStore := newMaintenanceVerificationFixture(t) + acmeStore, err := h.resources.getStore("acme") + if err != nil { + t.Fatalf("get acme store: %v", err) + } + now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC) + seedMaintenanceWindow(t, defaultStore, "vm:101", now.Add(-time.Hour), now.Add(-15*time.Minute)) + + rerunAsAcme := func() *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/resources/vm:101/maintenance-verifications/rerun", nil) + req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "acme")) + h.HandleRerun(rec, req) + return rec + } + countReports := func(store unified.ResourceStore) int { + t.Helper() + reports, err := store.ListLoopReportsForResource(unified.LoopReportTypeMaintenanceVerification, "vm:101", 0) + if err != nil { + t.Fatalf("list: %v", err) + } + return len(reports) + } + + // The window belongs to the default org. A rerun authorized for + // another org must neither disclose it nor add to its history. + rec := rerunAsAcme() + if rec.Code != http.StatusBadRequest { + t.Fatalf("cross-org rerun status = %d body=%s", rec.Code, rec.Body.String()) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("body must be JSON: %v", err) + } + if body["error"] != "maintenance_window_missing" { + t.Fatalf("error code = %q want maintenance_window_missing", body["error"]) + } + if got := countReports(defaultStore); got != 0 { + t.Fatalf("cross-org rerun wrote %d reports into the default org", got) + } + + acmeEnd := now.Add(-2 * time.Hour) + seedMaintenanceWindow(t, acmeStore, "vm:101", now.Add(-3*time.Hour), acmeEnd) + rec = rerunAsAcme() + if rec.Code != http.StatusOK { + t.Fatalf("acme rerun status = %d body=%s", rec.Code, rec.Body.String()) + } + var report maintenanceVerificationReportAPI + if err := json.Unmarshal(rec.Body.Bytes(), &report); err != nil { + t.Fatalf("parse: %v", err) + } + if report.WindowEndedAt == nil || !report.WindowEndedAt.Equal(acmeEnd) { + t.Fatalf("window end = %v, want acme's %v", report.WindowEndedAt, acmeEnd) + } + if got := countReports(acmeStore); got != 1 { + t.Fatalf("acme reports = %d, want 1", got) + } + if got := countReports(defaultStore); got != 0 { + t.Fatalf("acme rerun wrote %d reports into the default org", got) + } +} + func TestMaintenanceVerification_RerunWithoutWindowReturns400(t *testing.T) { h, _ := newMaintenanceVerificationFixture(t) rec := httptest.NewRecorder() diff --git a/internal/api/org_delete_credentials_test.go b/internal/api/org_delete_credentials_test.go new file mode 100644 index 0000000000..ec6f778472 --- /dev/null +++ b/internal/api/org_delete_credentials_test.go @@ -0,0 +1,233 @@ +package api + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/rcourtman/pulse-go-rewrite/internal/config" + "github.com/rcourtman/pulse-go-rewrite/internal/models" +) + +func newOrgBoundTokenForTest(t *testing.T, id string, age time.Duration, scope, orgID string, orgIDs ...string) config.APITokenRecord { + t.Helper() + record, err := config.NewAPITokenRecord(id+"-raw-token-0123456789abcdef0123456789", id, []string{scope}) + if err != nil { + t.Fatalf("NewAPITokenRecord(%s): %v", id, err) + } + record.ID = id + record.CreatedAt = time.Now().UTC().Add(-age) + record.OrgID = orgID + record.OrgIDs = orgIDs + return *record +} + +// An organization is identified by an ID that is free to be claimed again once +// the organization is deleted. Its instance API tokens must not survive into +// whichever organization takes the ID next. +func TestCleanupTenantRevokesOrganizationAPITokens(t *testing.T) { + dataDir := t.TempDir() + persistence := config.NewConfigPersistence(dataDir) + + cfg := &config.Config{DataPath: dataDir} + cfg.APITokens = []config.APITokenRecord{ + newOrgBoundTokenForTest(t, "acme-only", 1*time.Minute, config.ScopeMonitoringRead, "acme"), + newOrgBoundTokenForTest(t, "acme-only-list", 2*time.Minute, config.ScopeMonitoringRead, "", "acme"), + newOrgBoundTokenForTest(t, "acme-list-over-globex", 3*time.Minute, config.ScopeMonitoringRead, "globex", "acme"), + newOrgBoundTokenForTest(t, "acme-and-globex", 4*time.Minute, config.ScopeMonitoringRead, "acme", "acme", "globex"), + newOrgBoundTokenForTest(t, "acme-and-default", 5*time.Minute, config.ScopeWildcard, "", "acme", "default"), + newOrgBoundTokenForTest(t, "globex-only", 6*time.Minute, config.ScopeMonitoringRead, "globex"), + newOrgBoundTokenForTest(t, "default-only", 7*time.Minute, config.ScopeWildcard, "default"), + } + cfg.SortAPITokens() + if err := persistence.SaveAPITokens(cfg.APITokens); err != nil { + t.Fatalf("SaveAPITokens: %v", err) + } + + router := &Router{config: cfg, persistence: persistence} + if err := router.CleanupTenant(context.Background(), "acme"); err != nil { + t.Fatalf("CleanupTenant: %v", err) + } + + assertInventory := func(source string, tokens []config.APITokenRecord) { + t.Helper() + var ids []string + for i := range tokens { + ids = append(ids, tokens[i].ID) + if tokens[i].CanAccessOrg("acme") || tokens[i].OrgID == "acme" { + t.Errorf("%s: token %q is still bound to the deleted organization", source, tokens[i].ID) + } + if tokens[i].IsLegacyToken() { + t.Errorf("%s: token %q lost its organization binding instead of being revoked", source, tokens[i].ID) + } + // Only the token that already was instance-wide may remain so. + if tokenActsForInstance(&tokens[i]) != (tokens[i].ID == "default-only") { + t.Errorf("%s: token %q changed whether it acts for the instance", source, tokens[i].ID) + } + } + if want := []string{"acme-and-globex", "globex-only", "default-only"}; !slices.Equal(ids, want) { + t.Fatalf("%s: tokens = %v, want %v", source, ids, want) + } + if !tokens[0].CanAccessOrg("globex") { + t.Errorf("%s: multi-organization token lost its remaining organization", source) + } + } + + assertInventory("live", cfg.APITokens) + persisted, err := persistence.LoadAPITokens() + if err != nil { + t.Fatalf("LoadAPITokens: %v", err) + } + assertInventory("persisted", persisted) +} + +func TestRevokeTenantCredentialsKeepsInventoryWhenSaveFails(t *testing.T) { + dataDir := t.TempDir() + persistence := config.NewConfigPersistence(dataDir) + + cfg := &config.Config{DataPath: dataDir} + cfg.APITokens = []config.APITokenRecord{ + newOrgBoundTokenForTest(t, "acme-only", 1*time.Minute, config.ScopeMonitoringRead, "acme"), + newOrgBoundTokenForTest(t, "globex-only", 2*time.Minute, config.ScopeMonitoringRead, "globex"), + } + cfg.SortAPITokens() + if err := persistence.SaveAPITokens(cfg.APITokens); err != nil { + t.Fatalf("SaveAPITokens: %v", err) + } + + // A real write refusal, confined to this disposable test directory. + tokensPath := filepath.Join(dataDir, "api_tokens.json") + if err := os.Remove(tokensPath); err != nil { + t.Fatalf("remove token file: %v", err) + } + if err := os.MkdirAll(filepath.Join(tokensPath, "blocked"), 0o700); err != nil { + t.Fatalf("block token file: %v", err) + } + + router := &Router{config: cfg, persistence: persistence} + if err := router.revokeTenantCredentials("acme"); err == nil { + t.Fatal("expected an error when the token inventory cannot be saved") + } + if len(cfg.APITokens) != 2 || !cfg.APITokens[0].CanAccessOrg("acme") { + t.Fatalf("live inventory changed although the revocation was not persisted: %+v", cfg.APITokens) + } +} + +func TestOrgHandlersDeleteRetainsOrgWhenCredentialRevocationFails(t *testing.T) { + t.Setenv("PULSE_DEV", "true") + defer SetMultiTenantEnabled(false) + SetMultiTenantEnabled(true) + + persistence := config.NewMultiTenantPersistence(t.TempDir()) + h := NewOrgHandlers(persistence, nil) + + revocationErr := errors.New("token inventory unavailable") + var order []string + h.SetCredentialRevoker(func(orgID string) error { + if !persistence.OrgExists(orgID) { + t.Errorf("credentials must be revoked before organization %q is removed", orgID) + } + order = append(order, "before") + return revocationErr + }) + h.SetOnDelete(func(_ context.Context, _ string) error { + order = append(order, "after") + return nil + }) + + if err := persistence.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme Corp", OwnerUserID: "alice"}); err != nil { + t.Fatalf("SaveOrganization: %v", err) + } + + deleteOrg := func() int { + req := withUser(httptest.NewRequest(http.MethodDelete, "/api/orgs/acme", nil), "alice") + req.SetPathValue("id", "acme") + rec := httptest.NewRecorder() + h.HandleDeleteOrg(rec, req) + return rec.Code + } + + if code := deleteOrg(); code != http.StatusInternalServerError { + t.Fatalf("expected 500 when credentials cannot be revoked, got %d", code) + } + if !persistence.OrgExists("acme") { + t.Fatal("organization was deleted although its credentials are still valid") + } + if !slices.Equal(order, []string{"before"}) { + t.Fatalf("callbacks = %v, want only the pre-delete callback", order) + } + + revocationErr = nil + order = nil + if code := deleteOrg(); code != http.StatusNoContent { + t.Fatalf("expected 204 once credentials are revoked, got %d", code) + } + if persistence.OrgExists("acme") { + t.Fatal("organization still exists after a successful delete") + } + if !slices.Equal(order, []string{"before", "after"}) { + t.Fatalf("callbacks = %v, want before then after", order) + } +} + +// Tokens orphaned by an organization that was deleted before deletion revoked +// them, or whose directory was removed by hand, are still bound to its ID. A +// new organization must not start out with them. +func TestOrgHandlersCreateRevokesCredentialsLeftOnTheID(t *testing.T) { + t.Setenv("PULSE_DEV", "true") + defer SetMultiTenantEnabled(false) + SetMultiTenantEnabled(true) + + dataDir := t.TempDir() + cfg := &config.Config{DataPath: dataDir} + cfg.APITokens = []config.APITokenRecord{ + newOrgBoundTokenForTest(t, "old-acme", 1*time.Minute, config.ScopeMonitoringRead, "acme"), + newOrgBoundTokenForTest(t, "globex-only", 2*time.Minute, config.ScopeMonitoringRead, "globex"), + } + cfg.SortAPITokens() + router := &Router{config: cfg, persistence: config.NewConfigPersistence(dataDir)} + + persistence := config.NewMultiTenantPersistence(dataDir) + h := NewOrgHandlers(persistence, nil) + var revocationErr error + h.SetCredentialRevoker(func(orgID string) error { + if persistence.OrgExists(orgID) { + t.Errorf("credentials must be revoked before organization %q exists", orgID) + } + if revocationErr != nil { + return revocationErr + } + return router.revokeTenantCredentials(orgID) + }) + + createOrg := func() int { + body := bytes.NewBufferString(`{"id":"acme","displayName":"New Acme"}`) + req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs", body), "bob") + rec := httptest.NewRecorder() + h.HandleCreateOrg(rec, req) + return rec.Code + } + + revocationErr = errors.New("token inventory unavailable") + if code := createOrg(); code != http.StatusInternalServerError { + t.Fatalf("expected 500 when stale credentials cannot be revoked, got %d", code) + } + if persistence.OrgExists("acme") { + t.Fatal("organization was created although stale credentials are still bound to its ID") + } + + revocationErr = nil + if code := createOrg(); code != http.StatusCreated { + t.Fatalf("expected 201 once stale credentials are revoked, got %d", code) + } + if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != "globex-only" { + t.Fatalf("tokens after create = %+v, want only globex-only", cfg.APITokens) + } +} diff --git a/internal/api/org_handlers.go b/internal/api/org_handlers.go index 6a9623b852..23ecd0e00e 100644 --- a/internal/api/org_handlers.go +++ b/internal/api/org_handlers.go @@ -12,6 +12,7 @@ import ( "sort" "strconv" "strings" + "sync" "time" "github.com/rcourtman/pulse-go-rewrite/internal/config" @@ -26,6 +27,19 @@ const ( licenseFeatureMultiTenantKey = "multi_tenant" ) +// maxOwnedOrganizations bounds the organizations one user below instance +// administrator may own. An organization is not just its org.json: it gets a +// monitor with its own alert manager, notification manager and stores, +// started when it is first used and again by the report scheduler after every +// restart. Without a bound, any signed-in user could exhaust the server's +// memory with small requests, and the saved organizations would exhaust it +// again on every start. +const maxOwnedOrganizations = 20 + +// orgOwnershipMu serializes counting a user's organizations and saving the +// one that adds to them, so parallel requests cannot pass the limit together. +var orgOwnershipMu sync.Mutex + var organizationIDPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`) var supportedOrganizationShareResourceTypes = map[string]struct{}{ @@ -94,6 +108,8 @@ type OrgHandlers struct { onDelete func(ctx context.Context, orgID string) error hostedMode bool accessPolicy *DefaultAuthorizationChecker + // revokeCredentials withdraws the credentials bound to an org ID. + revokeCredentials func(orgID string) error } func NewOrgHandlers( @@ -113,6 +129,18 @@ func NewOrgHandlers( } } +// SetCredentialRevoker configures an optional callback that withdraws the +// credentials bound to an org ID. It runs before an org's data is removed and +// before a free ID is claimed by a new org, and an error aborts either: +// credentials are matched to an org by ID alone and must not pass from one +// holder of an ID to the next. +func (h *OrgHandlers) SetCredentialRevoker(callback func(orgID string) error) { + if h == nil { + return + } + h.revokeCredentials = callback +} + // SetOnDelete configures an optional callback invoked after org deletion. func (h *OrgHandlers) SetOnDelete(callback func(ctx context.Context, orgID string) error) { if h == nil { @@ -367,10 +395,26 @@ func (h *OrgHandlers) HandleCreateOrg(w http.ResponseWriter, r *http.Request) { writeErrorResponse(w, http.StatusBadRequest, "invalid_display_name", "Display name is required", nil) return } + orgOwnershipMu.Lock() + defer orgOwnershipMu.Unlock() if h.persistence.OrgExists(req.ID) { writeErrorResponse(w, http.StatusConflict, "already_exists", "Organization already exists", nil) return } + if !h.admitOrganizationOwner(w, r, username) { + return + } + + // Credentials still bound to a free ID belong to an organization that no + // longer exists (deleted before deletion revoked them, or removed outside + // the API). They must not carry over to this one. + if h.revokeCredentials != nil { + if err := h.revokeCredentials(req.ID); err != nil { + log.Error().Err(err).Str("org_id", req.ID).Msg("Failed to revoke credentials left bound to organization ID; not creating it") + writeErrorResponse(w, http.StatusInternalServerError, "create_failed", "Failed to create organization", nil) + return + } + } now := time.Now().UTC() org := &models.Organization{ @@ -396,6 +440,36 @@ func (h *OrgHandlers) HandleCreateOrg(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusCreated, org) } +// admitOrganizationOwner reports whether owner may own one more organization, +// and writes the refusal when not. The limit binds users below instance +// administrator in what they create and what they hand to each other; +// instance administrators set up the organizations of a multi-organization +// instance and may create, receive and hand over any number. The caller holds +// orgOwnershipMu until the organization is saved. +func (h *OrgHandlers) admitOrganizationOwner(w http.ResponseWriter, r *http.Request, owner string) bool { + if h.accessPolicy != nil && h.accessPolicy.instanceAdmin != nil { + if h.accessPolicy.instanceAdmin(r.Context(), auth.GetUser(r.Context())) || h.accessPolicy.instanceAdmin(r.Context(), owner) { + return true + } + } + orgs, err := h.persistence.ListOrganizations() + if err != nil { + writeErrorResponse(w, http.StatusInternalServerError, "list_failed", "Failed to list organizations", nil) + return false + } + owned := 0 + for _, org := range orgs { + if org != nil && org.IsOwnerUserID(owner) { + owned++ + } + } + if owned >= maxOwnedOrganizations { + writeErrorResponse(w, http.StatusConflict, "organization_limit_reached", fmt.Sprintf("A user can own at most %d organizations", maxOwnedOrganizations), nil) + return false + } + return true +} + func (h *OrgHandlers) HandleGetOrg(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) @@ -524,6 +598,14 @@ func (h *OrgHandlers) HandleDeleteOrg(w http.ResponseWriter, r *http.Request) { defer h.mtMonitor.FinishTenantDeletion(orgID) } + if h.revokeCredentials != nil { + if err := h.revokeCredentials(orgID); err != nil { + log.Error().Err(err).Str("org_id", orgID).Msg("Failed to revoke organization credentials; retaining data") + writeErrorResponse(w, http.StatusInternalServerError, "delete_failed", "Failed to delete organization", nil) + return + } + } + if err := h.persistence.DeleteOrganization(orgID); err != nil { if errors.Is(err, os.ErrNotExist) || errors.Is(err, errOrgNotFound) { writeErrorResponse(w, http.StatusNotFound, "not_found", "Organization not found", nil) @@ -655,6 +737,13 @@ func (h *OrgHandlers) HandleInviteMember(w http.ResponseWriter, r *http.Request) writeErrorResponse(w, authErr.Status, authErr.Code, authErr.Message, nil) return } + // A transfer counts against the new owner like a creation, or a + // user could keep creating organizations and handing them on. + orgOwnershipMu.Lock() + defer orgOwnershipMu.Unlock() + if !h.admitOrganizationOwner(w, r, req.UserID) { + return + } for i := range org.Members { if org.Members[i].UserID == org.OwnerUserID { org.Members[i].Role = models.OrgRoleAdmin diff --git a/internal/api/org_handlers_test.go b/internal/api/org_handlers_test.go index cab05b29ca..a52d5b1819 100644 --- a/internal/api/org_handlers_test.go +++ b/internal/api/org_handlers_test.go @@ -13,6 +13,7 @@ import ( "path/filepath" "reflect" "strings" + "sync" "testing" "time" @@ -2030,3 +2031,170 @@ func TestOrgHandlersWriteBodyNativeHTTP(t *testing.T) { } } } + +func createOrgForTest(h *OrgHandlers, user, orgID string) int { + req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"`+orgID+`","displayName":"`+orgID+`"}`)), user) + rec := httptest.NewRecorder() + h.HandleCreateOrg(rec, req) + return rec.Code +} + +func transferOrgForTest(h *OrgHandlers, orgID, owner, target string) *httptest.ResponseRecorder { + req := withUser( + httptest.NewRequest(http.MethodPost, "/api/orgs/"+orgID+"/members", bytes.NewBufferString(`{"userId":"`+target+`","role":"owner"}`)), + owner, + ) + session := generateSessionToken() + GetSessionStore().CreateSession(session, time.Hour, "browser", "127.0.0.1", owner) + req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: session}) + req.SetPathValue("id", orgID) + rec := httptest.NewRecorder() + h.HandleInviteMember(rec, req) + return rec +} + +func ownedOrganizationsForTest(t *testing.T, persistence *config.MultiTenantPersistence, user string) int { + t.Helper() + orgs, err := persistence.ListOrganizations() + if err != nil { + t.Fatalf("list organizations: %v", err) + } + owned := 0 + for _, org := range orgs { + if org.IsOwnerUserID(user) { + owned++ + } + } + return owned +} + +func newOrgOwnershipLimitHandlers(t *testing.T) (*OrgHandlers, *config.MultiTenantPersistence) { + t.Helper() + t.Setenv("PULSE_DEV", "true") + previous := IsMultiTenantEnabled() + SetMultiTenantEnabled(true) + t.Cleanup(func() { SetMultiTenantEnabled(previous) }) + InitSessionStore(t.TempDir()) + + persistence := config.NewMultiTenantPersistence(t.TempDir()) + checker := NewAuthorizationChecker(NewMultiTenantOrganizationLoader(persistence)) + checker.SetInstanceAdminResolver(func(_ context.Context, userID string) bool { return userID == "root" }) + h := NewOrgHandlers(persistence, nil) + h.SetAccessPolicy(checker) + return h, persistence +} + +func TestOrgHandlersCreateBoundsOrganizationsPerOwner(t *testing.T) { + h, persistence := newOrgOwnershipLimitHandlers(t) + + for i := 0; i < maxOwnedOrganizations; i++ { + if code := createOrgForTest(h, "alice", fmt.Sprintf("alice-%d", i)); code != http.StatusCreated { + t.Fatalf("organization %d: status %d, want 201", i, code) + } + } + req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"alice-over","displayName":"Over"}`)), "alice") + rec := httptest.NewRecorder() + h.HandleCreateOrg(rec, req) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "organization_limit_reached") { + t.Fatalf("organization past the limit: %d %s, want 409 organization_limit_reached", rec.Code, rec.Body.String()) + } + if persistence.OrgExists("alice-over") { + t.Fatal("the refused organization was saved") + } + + if code := createOrgForTest(h, "bob", "bob-0"); code != http.StatusCreated { + t.Fatalf("another user's first organization: status %d, want 201", code) + } + deleteReq := withUser(httptest.NewRequest(http.MethodDelete, "/api/orgs/alice-0", nil), "alice") + deleteReq.SetPathValue("id", "alice-0") + deleteRec := httptest.NewRecorder() + h.HandleDeleteOrg(deleteRec, deleteReq) + if deleteRec.Code != http.StatusNoContent { + t.Fatalf("delete: status %d: %s", deleteRec.Code, deleteRec.Body.String()) + } + if code := createOrgForTest(h, "alice", "alice-again"); code != http.StatusCreated { + t.Fatalf("organization after deleting one: status %d, want 201", code) + } + + for i := 0; i <= maxOwnedOrganizations; i++ { + if code := createOrgForTest(h, "root", fmt.Sprintf("root-%d", i)); code != http.StatusCreated { + t.Fatalf("administrator's organization %d: status %d, want 201", i, code) + } + } +} + +func TestOrgHandlersCreateBoundsOrganizationsWithoutAccessPolicy(t *testing.T) { + t.Setenv("PULSE_DEV", "true") + previous := IsMultiTenantEnabled() + SetMultiTenantEnabled(true) + t.Cleanup(func() { SetMultiTenantEnabled(previous) }) + + persistence := config.NewMultiTenantPersistence(t.TempDir()) + h := NewOrgHandlers(persistence, nil) + for i := 0; i < maxOwnedOrganizations; i++ { + if code := createOrgForTest(h, "alice", fmt.Sprintf("alice-%d", i)); code != http.StatusCreated { + t.Fatalf("organization %d: status %d, want 201", i, code) + } + } + if code := createOrgForTest(h, "alice", "alice-over"); code != http.StatusConflict { + t.Fatalf("organization past the limit: status %d, want 409", code) + } + if owned := ownedOrganizationsForTest(t, persistence, "alice"); owned != maxOwnedOrganizations { + t.Fatalf("alice owns %d organizations, want %d", owned, maxOwnedOrganizations) + } +} + +func TestOrgHandlersCreateBoundsParallelRequests(t *testing.T) { + h, persistence := newOrgOwnershipLimitHandlers(t) + + var wg sync.WaitGroup + for i := 0; i < maxOwnedOrganizations*2; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + createOrgForTest(h, "alice", fmt.Sprintf("alice-%d", i)) + }(i) + } + wg.Wait() + + if owned := ownedOrganizationsForTest(t, persistence, "alice"); owned != maxOwnedOrganizations { + t.Fatalf("alice owns %d organizations, want %d", owned, maxOwnedOrganizations) + } +} + +func TestOrgHandlersOwnershipTransferCountsAgainstNewOwner(t *testing.T) { + h, persistence := newOrgOwnershipLimitHandlers(t) + + for i := 0; i < maxOwnedOrganizations; i++ { + if code := createOrgForTest(h, "bob", fmt.Sprintf("bob-%d", i)); code != http.StatusCreated { + t.Fatalf("bob's organization %d: status %d, want 201", i, code) + } + } + for _, creator := range []string{"alice", "root"} { + orgID := creator + "-org" + if code := createOrgForTest(h, creator, orgID); code != http.StatusCreated { + t.Fatalf("%s: status %d, want 201", orgID, code) + } + inviteMemberForTest(t, h, orgID, creator, "bob", "admin", http.StatusAccepted) + acceptInvitationForTest(t, h, orgID, "bob") + } + + rec := transferOrgForTest(h, "alice-org", "alice", "bob") + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "organization_limit_reached") { + t.Fatalf("transfer to an owner at the limit: %d %s, want 409 organization_limit_reached", rec.Code, rec.Body.String()) + } + org, err := persistence.LoadOrganization("alice-org") + if err != nil || org.OwnerUserID != "alice" || org.GetMemberRole("bob") != models.OrgRoleAdmin { + t.Fatalf("refused transfer changed the organization: %+v, %v", org, err) + } + + if rec := transferOrgForTest(h, "root-org", "root", "bob"); rec.Code != http.StatusOK { + t.Fatalf("administrator's transfer: status %d, want 200: %s", rec.Code, rec.Body.String()) + } + + inviteMemberForTest(t, h, "alice-org", "alice", "carol", "viewer", http.StatusAccepted) + acceptInvitationForTest(t, h, "alice-org", "carol") + if rec := transferOrgForTest(h, "alice-org", "alice", "carol"); rec.Code != http.StatusOK { + t.Fatalf("transfer below the limit: status %d, want 200: %s", rec.Code, rec.Body.String()) + } +} diff --git a/internal/api/public_signup_handlers.go b/internal/api/public_signup_handlers.go index 0a5283e899..facb40c0cb 100644 --- a/internal/api/public_signup_handlers.go +++ b/internal/api/public_signup_handlers.go @@ -72,6 +72,13 @@ func (h *HostedSignupHandlers) HandlePublicSignup(w http.ResponseWriter, r *http http.NotFound(w, r) return } + // A runtime the control plane provisioned for one workspace already has its + // organization, owner and signed entitlement from there. Signup belongs to + // the control plane, so the runtime offers none of its own. + if hostedRuntimeHomeOrgID() != "" { + http.NotFound(w, r) + return + } if h.persistence == nil { writeErrorResponse(w, http.StatusServiceUnavailable, "orgs_unavailable", "Organization persistence is not configured", nil) return @@ -144,17 +151,24 @@ func (h *HostedSignupHandlers) HandlePublicSignup(w http.ResponseWriter, r *http ownerEmail = strings.ToLower(strings.TrimSpace(req.Email)) } + // An organization the provisioner found rather than created is not this + // request's to initialize or to undo: it keeps its billing state, and a + // later failure must not delete it. + created := result.Status == hosted.ProvisionStatusCreated + var cleanupOnce sync.Once cleanupProvisioning := func() { cleanupOnce.Do(func() { hosted.GetHostedMetrics().RecordProvisionStatus(hosted.ProvisionMetricStatusFailure) - provisioner.RollbackProvisioning(orgID) + if created { + provisioner.RollbackProvisioning(orgID) + } }) } // Seed trial billing state so the tenant is usable immediately (before Stripe checkout completes). // Stripe webhook will overwrite this with active subscription state on successful checkout. - if h.billingStore != nil { + if h.billingStore != nil && created { now := time.Now().UTC() trialState := buildTrialBillingStateWithPlanFromLicensing( now, diff --git a/internal/api/router.go b/internal/api/router.go index 57678c8bf7..6b8f4fa78c 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -17,6 +17,7 @@ import ( "path" "path/filepath" "runtime" + "slices" "sort" "strconv" "strings" @@ -544,11 +545,9 @@ func (r *Router) setupRoutes() { if r.config == nil { return false } - config.Mu.Lock() - tokens := make([]config.APITokenRecord, len(r.config.APITokens)) - copy(tokens, r.config.APITokens) - config.Mu.Unlock() - return agentOperationsLoopExternalAgentTokenReady(manifest, tokens, now) + // A shallow copy still shares each record's Metadata map with the + // live inventory, and the readiness check clones every record. + return agentOperationsLoopExternalAgentTokenReady(manifest, snapshotAPITokenRecords(r.config), now) })) // Wire pending-approvals into the bundle. The provider resolves // the approval store at request time so multi-tenant rebuilds @@ -623,6 +622,7 @@ func (r *Router) setupRoutes() { orgHandlers := NewOrgHandlers(r.multiTenant, r.mtMonitor, rbacProvider) orgHandlers.SetHostedMode(r.hostedMode) orgHandlers.SetAccessPolicy(r.orgAccess) + orgHandlers.SetCredentialRevoker(r.revokeTenantCredentials) orgHandlers.SetOnDelete(func(ctx context.Context, orgID string) error { return r.CleanupTenant(ctx, orgID) }) @@ -1037,7 +1037,7 @@ func (r *Router) wireReportingAIResolvers() { } } -// CleanupTenant removes all per-tenant resources (RBAC, AI, License) for a deleted org. +// CleanupTenant removes all per-tenant resources (credentials, RBAC, AI, License) for a deleted org. func (r *Router) CleanupTenant(ctx context.Context, orgID string) error { orgID = strings.TrimSpace(orgID) if orgID == "" || orgID == "default" { @@ -1046,6 +1046,10 @@ func (r *Router) CleanupTenant(ctx context.Context, orgID string) error { var errs []error + if err := r.revokeTenantCredentials(orgID); err != nil { + errs = append(errs, fmt.Errorf("credential cleanup: %w", err)) + } + r.StopPatrolForOrg(orgID) if r.aiSettingsHandler != nil { @@ -1088,6 +1092,78 @@ func (r *Router) CleanupTenant(ctx context.Context, orgID string) error { return nil } +// revokeTenantCredentials withdraws every instance API token from an +// organization ID and ends its agent command sessions. It runs when the +// organization is deleted and again before the ID is claimed by a new one. +// Org-bound tokens (agent install tokens included) live in the instance +// inventory, not in the organization's directory, and are matched to an +// organization by ID alone. An ID is free to be claimed again once its +// organization is gone, so a credential that outlived the deletion would be +// valid in whichever organization takes the ID next. A save failure leaves the +// inventory untouched and is returned so the caller can abort the change. +func (r *Router) revokeTenantCredentials(orgID string) error { + orgID = strings.TrimSpace(orgID) + if r == nil || r.config == nil || orgID == "" || orgID == "default" { + return nil + } + + config.Mu.Lock() + previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...) + keptTokens := make([]config.APITokenRecord, 0, len(previousTokens)) + revoked := 0 + for _, record := range previousTokens { + bound := record.GetBoundOrgs() + remaining := slices.DeleteFunc(slices.Clone(bound), func(boundOrgID string) bool { + return strings.TrimSpace(boundOrgID) == orgID + }) + if len(remaining) == len(bound) { + keptTokens = append(keptTokens, record) + continue + } + revoked++ + // A multi-org token keeps its other organizations. + narrowed := record.Clone() + narrowed.OrgIDs = remaining + if strings.TrimSpace(narrowed.OrgID) == orgID { + narrowed.OrgID = "" + } + // Losing the binding must never widen the token: with no organization + // left it would read as an unbound legacy token, and with only the + // default one left it would start acting for the instance. Remove it. + if len(remaining) == 0 || tokenActsForInstance(&narrowed) { + continue + } + keptTokens = append(keptTokens, narrowed) + } + if revoked > 0 { + r.config.APITokens = keptTokens + r.config.SortAPITokens() + if r.persistence != nil { + if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil { + r.config.APITokens = previousTokens + r.config.SortAPITokens() + config.Mu.Unlock() + return fmt.Errorf("persist API token revocation: %w", err) + } + } + } + config.Mu.Unlock() + + if revoked > 0 { + log.Info(). + Str("org_id", orgID). + Int("tokens", revoked). + Msg("Revoked API tokens bound to organization ID") + } + + if r.agentExecServer != nil { + // Listing revalidates each of the organization's command sessions and + // closes those whose token is gone. + r.agentExecServer.GetConnectedAgentsForOrganization(orgID) + } + return nil +} + // RemoveTenantService removes the cached license service for a deleted org. func (h *LicenseHandlers) RemoveTenantService(orgID string) { h.services.Delete(orgID) @@ -8224,39 +8300,26 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req } setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req)) - activeConfig := r.config - activePersistence := r.persistence - if orgID != "" && orgID != "default" { - activeConfig = monitor.GetConfig() - if activeConfig == nil { - writeErrorResponse(w, http.StatusInternalServerError, "tenant_config_unavailable", "Tenant config is not available", nil) - return - } - if r.multiTenant == nil { - writeErrorResponse(w, http.StatusInternalServerError, "tenant_persistence_unavailable", "Tenant persistence is not configured", nil) - return - } - tenantPersistence, err := r.multiTenant.GetPersistence(orgID) - if err != nil { - writeErrorResponse(w, http.StatusInternalServerError, "tenant_persistence_unavailable", "Failed to resolve tenant persistence", nil) - return - } - activePersistence = tenantPersistence - } - if activeConfig == nil { + // A tenant organization's record also goes into the instance inventory, + // bound to it by OrgID, the same as agenttokens.IssueAndPersistForOrganization. + // That is the inventory header-less agents authenticate against and the + // only one /api/security/tokens lists, revokes and rotates. A record kept + // in the organization's own config copy still authenticates requests that + // name the organization, and no token route can show or revoke it. + if r.config == nil { writeErrorResponse(w, http.StatusInternalServerError, "config_unavailable", "Configuration is not loaded", nil) return } config.Mu.Lock() - previousTokens := append([]config.APITokenRecord(nil), activeConfig.APITokens...) - activeConfig.APITokens = append(activeConfig.APITokens, *record) - activeConfig.SortAPITokens() + previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...) + r.config.APITokens = append(r.config.APITokens, *record) + r.config.SortAPITokens() - if activePersistence != nil { - if err := activePersistence.SaveAPITokens(activeConfig.APITokens); err != nil { - activeConfig.APITokens = previousTokens - activeConfig.SortAPITokens() + if r.persistence != nil { + if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil { + r.config.APITokens = previousTokens + r.config.SortAPITokens() config.Mu.Unlock() log.Error().Err(err).Msg("Failed to persist API tokens after container runtime migration generation") writeErrorResponse(w, http.StatusInternalServerError, "token_persist_failed", "Failed to persist API token", nil) diff --git a/internal/api/router_low_coverage_additional_test.go b/internal/api/router_low_coverage_additional_test.go index 579cfa8bbf..368ae6a98c 100644 --- a/internal/api/router_low_coverage_additional_test.go +++ b/internal/api/router_low_coverage_additional_test.go @@ -2,6 +2,7 @@ package api import ( "bytes" + "context" "encoding/json" "net/http" "net/http/httptest" @@ -212,6 +213,78 @@ func TestHandleDiagnosticsDockerPrepareToken_Success(t *testing.T) { } } +// A token prepared in a tenant organization must land in the instance +// inventory, bound to the organization: that is the only inventory the token +// list, revoke and rotate routes manage. A record in the organization's own +// config copy still authenticates requests that name the organization and +// cannot be revoked. +func TestHandleDiagnosticsDockerPrepareToken_TenantTokenJoinsInstanceInventory(t *testing.T) { + defaultMonitor, _, _ := newTestMonitor(t) + tenantMonitor, tenantState, _ := newTestMonitor(t) + tenantState.DockerHosts = []models.DockerHost{{ID: "host-1", DisplayName: "Docker Host"}} + tenantConfig := &config.Config{} + setUnexportedField(t, tenantMonitor, "config", tenantConfig) + + mtm := &monitoring.MultiTenantMonitor{} + setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{"org-a": tenantMonitor}) + + dataDir := t.TempDir() + mtp := config.NewMultiTenantPersistence(dataDir) + tenantPersistence, err := mtp.GetPersistence("org-a") + if err != nil { + t.Fatalf("tenant persistence: %v", err) + } + instancePersistence := config.NewConfigPersistence(dataDir) + router := &Router{ + monitor: defaultMonitor, + mtMonitor: mtm, + multiTenant: mtp, + config: &config.Config{PublicURL: "https://pulse.example.com"}, + persistence: instancePersistence, + } + + req := httptest.NewRequest(http.MethodPost, "/api/diagnostics/docker/prepare-token", strings.NewReader(`{"agentId":"host-1"}`)) + req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a")) + rec := httptest.NewRecorder() + + router.handleDiagnosticsDockerPrepareToken(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String()) + } + var payload struct { + Token string `json:"token"` + } + if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil { + t.Fatalf("decode response: %v", err) + } + if len(router.config.APITokens) != 1 || router.config.APITokens[0].OrgID != "org-a" { + t.Fatalf("instance inventory = %+v, want one token bound to org-a", router.config.APITokens) + } + tokenID := router.config.APITokens[0].ID + if len(tenantConfig.APITokens) != 0 { + t.Fatalf("tenant config copy holds %d token(s) no token route can revoke", len(tenantConfig.APITokens)) + } + persisted, err := instancePersistence.LoadAPITokens() + if err != nil || len(persisted) != 1 || persisted[0].ID != tokenID { + t.Fatalf("persisted instance inventory = %+v (err=%v), want the prepared token", persisted, err) + } + if persisted, err := tenantPersistence.LoadAPITokens(); err != nil || len(persisted) != 0 { + t.Fatalf("persisted tenant inventory = %+v (err=%v), want none", persisted, err) + } + + req = httptest.NewRequest(http.MethodDelete, "/api/security/tokens/"+tokenID, nil) + req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a")) + rec = httptest.NewRecorder() + router.handleDeleteAPIToken(rec, req) + if rec.Code != http.StatusNoContent { + t.Fatalf("delete status = %d, want %d (body=%q)", rec.Code, http.StatusNoContent, rec.Body.String()) + } + if router.config.IsValidAPIToken(payload.Token) || tenantConfig.IsValidAPIToken(payload.Token) { + t.Fatal("deleted prepared token still authenticates") + } +} + func TestHandleDiagnosticsDockerPrepareToken_RollsBackWhenPersistenceFails(t *testing.T) { monitor, state, _ := newTestMonitor(t) state.DockerHosts = []models.DockerHost{{ID: "host-1", DisplayName: "Docker Host"}} diff --git a/internal/hosted/provisioner.go b/internal/hosted/provisioner.go index cce96122cb..5025af8684 100644 --- a/internal/hosted/provisioner.go +++ b/internal/hosted/provisioner.go @@ -177,7 +177,10 @@ func (p *Provisioner) findExistingOrganizationByOwnerEmail(email string) (*Provi if org == nil { continue } - if strings.EqualFold(strings.TrimSpace(org.OwnerEmail), email) || strings.EqualFold(strings.TrimSpace(org.OwnerUserID), email) { + // Compare as the organization model does when it resolves a principal + // by email. Unicode case folding would also accept look-alike + // addresses that are not the owner's. + if strings.ToLower(strings.TrimSpace(org.OwnerEmail)) == email || strings.ToLower(strings.TrimSpace(org.OwnerUserID)) == email { userID, err := p.ensureExistingOwnerStablePrincipal(org, email) if err != nil { return nil, err @@ -201,10 +204,11 @@ func (p *Provisioner) ensureExistingOwnerStablePrincipal(org *models.Organizatio if org == nil { return "", &SystemError{Op: "canonicalize_existing_owner_identity", Err: errors.New("organization is nil")} } - userID, _, ok := org.ResolvePrincipalByEmail(email) - userID = strings.TrimSpace(userID) - if ok && userID != "" && !strings.Contains(userID, "@") { - return userID, nil + // Only a legacy owner, one with no user ID or with an email in its place, + // is given a new one. Sessions, memberships and roles are bound to a stable + // owner ID, so a signup request never replaces it. + if ownerUserID := strings.TrimSpace(org.OwnerUserID); ownerUserID != "" && !strings.Contains(ownerUserID, "@") { + return ownerUserID, nil } return p.canonicalizeExistingOwnerPrincipal(org, email) diff --git a/internal/hosted/provisioner_test.go b/internal/hosted/provisioner_test.go index b6754d5c96..37cb88b154 100644 --- a/internal/hosted/provisioner_test.go +++ b/internal/hosted/provisioner_test.go @@ -597,6 +597,117 @@ func TestProvisionHostedSignupCanonicalizesBlankOwnerPrincipal(t *testing.T) { } } +// strings.EqualFold takes U+017F (long s) for "s", while the organization model +// lowercases and compares. An address that differs from the owner's only by +// such a fold is another address: it must neither select the owner's +// organization nor have it taken for a legacy record in need of a new owner ID. +func TestProvisionHostedSignupLookAlikeEmailLeavesExistingOwnerAlone(t *testing.T) { + baseDir := t.TempDir() + persistence := config.NewMultiTenantPersistence(baseDir) + authManager := &mockAuthManager{} + authProvider := &mockAuthProvider{manager: authManager} + provisioner := NewProvisioner(persistence, authProvider) + provisioner.newOrgID = func() string { return "look-alike-org" } + provisioner.newUserID = func() (string, error) { return "u_look_alike_owner", nil } + + addedAt := time.Unix(1700000400, 0).UTC() + if err := persistence.SaveOrganization(&models.Organization{ + ID: "existing-org", + DisplayName: "Existing Org", + CreatedAt: addedAt, + OwnerUserID: "u_existing_owner", + OwnerEmail: "alice.smith@example.com", + Members: []models.OrganizationMember{ + { + UserID: "u_existing_owner", + Email: "alice.smith@example.com", + Role: models.OrgRoleOwner, + AddedAt: addedAt, + AddedBy: "u_existing_owner", + }, + }, + }); err != nil { + t.Fatalf("SaveOrganization returned error: %v", err) + } + + result, err := provisioner.ProvisionHostedSignup(context.Background(), HostedSignupRequest{ + Email: "alice.\u017fmith@example.com", + OrgName: "Another Org", + }) + if err != nil { + t.Fatalf("ProvisionHostedSignup returned error: %v", err) + } + if result.Status != ProvisionStatusCreated || result.OrgID != "look-alike-org" || result.UserID != "u_look_alike_owner" { + t.Fatalf("result = %+v, want a separate organization for the look-alike address", result) + } + + org, err := persistence.LoadOrganization("existing-org") + if err != nil { + t.Fatalf("LoadOrganization returned error: %v", err) + } + if org.OwnerUserID != "u_existing_owner" || org.OwnerEmail != "alice.smith@example.com" { + t.Fatalf("owner identity = (%q, %q), want the existing owner unchanged", org.OwnerUserID, org.OwnerEmail) + } + if len(org.Members) != 1 || org.Members[0].UserID != "u_existing_owner" || org.Members[0].Email != "alice.smith@example.com" { + t.Fatalf("members = %+v, want the existing owner member unchanged", org.Members) + } + if authProvider.lastOrgID != "look-alike-org" || authManager.lastUser != "u_look_alike_owner" { + t.Fatalf("expected RBAC assignment only for the new organization, got org=%q user=%q", authProvider.lastOrgID, authManager.lastUser) + } +} + +// Canonicalization repairs legacy owners only. An owner that already has a +// stable ID keeps it even when its email does not resolve to one principal, +// here because a member entry carries the same address under another ID. +func TestProvisionHostedSignupKeepsStableOwnerPrincipal(t *testing.T) { + baseDir := t.TempDir() + persistence := config.NewMultiTenantPersistence(baseDir) + authManager := &mockAuthManager{} + authProvider := &mockAuthProvider{manager: authManager} + provisioner := NewProvisioner(persistence, authProvider) + provisioner.newUserID = func() (string, error) { return "u_must_not_be_used", nil } + + addedAt := time.Unix(1700000500, 0).UTC() + if err := persistence.SaveOrganization(&models.Organization{ + ID: "stable-owner-org", + DisplayName: "Stable Owner Org", + CreatedAt: addedAt, + OwnerUserID: "u_stable_owner", + OwnerEmail: "owner@example.com", + Members: []models.OrganizationMember{ + {UserID: "u_stable_owner", Email: "owner@example.com", Role: models.OrgRoleOwner, AddedAt: addedAt, AddedBy: "u_stable_owner"}, + {UserID: "u_other_member", Email: "owner@example.com", Role: models.OrgRoleViewer, AddedAt: addedAt, AddedBy: "u_stable_owner"}, + }, + }); err != nil { + t.Fatalf("SaveOrganization returned error: %v", err) + } + + result, err := provisioner.ProvisionHostedSignup(context.Background(), HostedSignupRequest{ + Email: "owner@example.com", + OrgName: "Another Org", + }) + if err != nil { + t.Fatalf("ProvisionHostedSignup returned error: %v", err) + } + if result.Status != ProvisionStatusExisting || result.OrgID != "stable-owner-org" || result.UserID != "u_stable_owner" { + t.Fatalf("result = %+v, want the existing stable owner", result) + } + + org, err := persistence.LoadOrganization("stable-owner-org") + if err != nil { + t.Fatalf("LoadOrganization returned error: %v", err) + } + if org.OwnerUserID != "u_stable_owner" || org.OwnerEmail != "owner@example.com" { + t.Fatalf("owner identity = (%q, %q), want the stable owner unchanged", org.OwnerUserID, org.OwnerEmail) + } + if len(org.Members) != 2 || org.Members[0].UserID != "u_stable_owner" || org.Members[1].UserID != "u_other_member" || org.Members[1].Role != models.OrgRoleViewer { + t.Fatalf("members = %+v, want both entries unchanged", org.Members) + } + if authProvider.calls != 0 || authManager.calls != 0 { + t.Fatalf("expected no RBAC calls for a stable owner, got provider=%d manager=%d", authProvider.calls, authManager.calls) + } +} + func TestCleanupOrgDirectorySkipsUnsafePath(t *testing.T) { baseDir := t.TempDir() p := &Provisioner{} diff --git a/internal/maintenancesentinel/sentinel.go b/internal/maintenancesentinel/sentinel.go index b553850110..fcde0d9705 100644 --- a/internal/maintenancesentinel/sentinel.go +++ b/internal/maintenancesentinel/sentinel.go @@ -18,8 +18,9 @@ import ( // and `internal/monitoring` imports so there are no cycles. type Providers struct { // Stores resolves the ResourceStore for the given org id. The - // sentinel runs against the default org for MVP; tenant-scoped - // scheduling is left to a future change. + // scheduled sweep runs against the default org for MVP; + // tenant-scoped scheduling is left to a future change. Request + // driven reruns (EvaluateOnce) resolve the caller's org. Stores func(orgID string) (unified.ResourceStore, error) // ActiveAlerts returns active alerts for a resource at this moment. ActiveAlerts func(orgID, canonicalID string) []AlertSummary @@ -52,8 +53,9 @@ type Sentinel struct { // Config configures a Sentinel instance. type Config struct { - // OrgID is the tenant the sentinel scans. MVP runs the default - // org only — multi-tenant scheduling is deferred. + // OrgID is the tenant the scheduled sweep scans. MVP runs the + // default org only — multi-tenant scheduling is deferred. It + // never scopes EvaluateOnce, which takes the org of its caller. OrgID string // Tick controls the sweep cadence. Defaults to one minute. Tick time.Duration @@ -153,7 +155,7 @@ func (s *Sentinel) evaluateForOccurrence(state unified.ResourceOperatorState, oc return } - inputs := s.buildInputs(state, occurrence, now) + inputs := s.buildInputs(s.orgID, state, occurrence, now) report := EvaluateVerification(inputs) if err := store.RecordLoopReport(report); err != nil { // A unique-constraint conflict (race against a parallel @@ -170,8 +172,9 @@ func (s *Sentinel) evaluateForOccurrence(state unified.ResourceOperatorState, oc // buildInputs gathers the deterministic input bundle for the // evaluator. Provider closures may be nil — the inputs simply carry -// zero values in that case. -func (s *Sentinel) buildInputs(state unified.ResourceOperatorState, occurrence unified.MaintenanceWindowOccurrence, now time.Time) VerificationInputs { +// zero values in that case. orgID must be the org whose store supplied +// state, so the evidence never mixes tenants. +func (s *Sentinel) buildInputs(orgID string, state unified.ResourceOperatorState, occurrence unified.MaintenanceWindowOccurrence, now time.Time) VerificationInputs { canonicalID := unified.CanonicalResourceID(state.CanonicalID) stateForOccurrence := cloneOperatorState(state) startAt, endAt := occurrence.StartAt.UTC(), occurrence.EndAt.UTC() @@ -185,20 +188,20 @@ func (s *Sentinel) buildInputs(state unified.ResourceOperatorState, occurrence u WindowEndedAt: endAt, } if s.providers.ActiveAlerts != nil { - inputs.ActiveAlerts = s.providers.ActiveAlerts(s.orgID, canonicalID) + inputs.ActiveAlerts = s.providers.ActiveAlerts(orgID, canonicalID) } if s.providers.ActiveFindings != nil { - inputs.ActiveFindings = s.providers.ActiveFindings(s.orgID, canonicalID) + inputs.ActiveFindings = s.providers.ActiveFindings(orgID, canonicalID) } if s.providers.RecentActions != nil { windowStart := inputs.WindowStartedAt if windowStart.IsZero() { windowStart = now.Add(-24 * time.Hour) } - inputs.RecentActions = s.providers.RecentActions(s.orgID, canonicalID, windowStart) + inputs.RecentActions = s.providers.RecentActions(orgID, canonicalID, windowStart) } if s.providers.PostWindowMetricSamples != nil { - samples, available := s.providers.PostWindowMetricSamples(s.orgID, canonicalID, inputs.WindowEndedAt, now) + samples, available := s.providers.PostWindowMetricSamples(orgID, canonicalID, inputs.WindowEndedAt, now) inputs.PostWindowMetricSamples = samples inputs.MetricSourceAvailable = available } @@ -235,10 +238,15 @@ func (s *Sentinel) now() time.Time { // the "rerun verification" handler so an operator can re-evaluate // without waiting for the next tick. // +// orgID is the org the caller was authorized for. Operator state, +// evidence and the persisted report are all scoped to it; the org the +// scheduled sweep is configured for (Config.OrgID) plays no part, so a +// rerun requested in one org can neither read nor write another's. +// // If the existing report for the (resource, window-end) triple is // found, this writes a *new* report with a -rerun-N suffix so the // review history is preserved. -func (s *Sentinel) EvaluateOnce(ctx context.Context, canonicalID string) (unified.LoopReport, error) { +func (s *Sentinel) EvaluateOnce(ctx context.Context, orgID, canonicalID string) (unified.LoopReport, error) { if ctx.Err() != nil { return unified.LoopReport{}, ctx.Err() } @@ -246,7 +254,7 @@ func (s *Sentinel) EvaluateOnce(ctx context.Context, canonicalID string) (unifie if canonicalID == "" { return unified.LoopReport{}, fmt.Errorf("maintenancesentinel: canonical id is required") } - store, err := s.providers.Stores(s.orgID) + store, err := s.providers.Stores(orgID) if err != nil { return unified.LoopReport{}, err } @@ -263,7 +271,7 @@ func (s *Sentinel) EvaluateOnce(ctx context.Context, canonicalID string) (unifie return unified.LoopReport{}, fmt.Errorf("maintenancesentinel: resource %q has no maintenance window to verify", canonicalID) } occurrence := occurrences[len(occurrences)-1] - inputs := s.buildInputs(state, occurrence, now) + inputs := s.buildInputs(orgID, state, occurrence, now) report := EvaluateVerification(inputs) report.ID = uniqueRerunID(store, report.ID) if err := store.RecordLoopReport(report); err != nil { diff --git a/internal/maintenancesentinel/sentinel_test.go b/internal/maintenancesentinel/sentinel_test.go index d3da0e2174..47f034e398 100644 --- a/internal/maintenancesentinel/sentinel_test.go +++ b/internal/maintenancesentinel/sentinel_test.go @@ -228,7 +228,7 @@ func TestSentinelEvaluateOncePersistsRerunReport(t *testing.T) { } sentinel.tickOnce(context.Background()) - rerun, err := sentinel.EvaluateOnce(context.Background(), "vm:101") + rerun, err := sentinel.EvaluateOnce(context.Background(), "default", "vm:101") if err != nil { t.Fatalf("evaluate once: %v", err) } @@ -262,7 +262,106 @@ func TestSentinelEvaluateOnceErrorsWhenNoWindow(t *testing.T) { if err != nil { t.Fatalf("new sentinel: %v", err) } - if _, err := sentinel.EvaluateOnce(context.Background(), "vm:404"); err == nil { + if _, err := sentinel.EvaluateOnce(context.Background(), "default", "vm:404"); err == nil { t.Fatalf("expected error when no maintenance window present") } } + +func TestSentinelEvaluateOnceIsScopedToCallerOrg(t *testing.T) { + now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC) + windowStart := now.Add(-time.Hour) + windowEnd := now.Add(-15 * time.Minute) + + stores := map[string]*unified.MemoryStore{ + "default": unified.NewMemoryStore(), + "acme": unified.NewMemoryStore(), + } + if err := stores["default"].SetResourceOperatorState(unified.ResourceOperatorState{ + CanonicalID: "vm:101", + MaintenanceStartAt: &windowStart, + MaintenanceEndAt: &windowEnd, + SetAt: windowStart, + SetBy: "operator", + }); err != nil { + t.Fatalf("seed default operator state: %v", err) + } + + var evidenceOrgs []string + providers := Providers{ + Stores: func(orgID string) (unified.ResourceStore, error) { return stores[orgID], nil }, + ActiveAlerts: func(orgID, _ string) []AlertSummary { + evidenceOrgs = append(evidenceOrgs, orgID) + return nil + }, + ActiveFindings: func(orgID, _ string) []FindingSummary { + evidenceOrgs = append(evidenceOrgs, orgID) + return nil + }, + RecentActions: func(orgID, _ string, _ time.Time) []ActionSummary { + evidenceOrgs = append(evidenceOrgs, orgID) + return nil + }, + PostWindowMetricSamples: func(orgID, _ string, _, _ time.Time) ([]MetricSample, bool) { + evidenceOrgs = append(evidenceOrgs, orgID) + return nil, false + }, + Now: func() time.Time { return now }, + } + sentinel, err := New(Config{OrgID: "default"}, providers) + if err != nil { + t.Fatalf("new sentinel: %v", err) + } + countReports := func(orgID string) int { + t.Helper() + reports, err := stores[orgID].ListLoopReportsForResource(unified.LoopReportTypeMaintenanceVerification, "vm:101", 0) + if err != nil { + t.Fatalf("list %s reports: %v", orgID, err) + } + return len(reports) + } + + // The window exists only in the sweep's own org: a rerun requested + // from another org must not see it, nor leave a report behind. + if _, err := sentinel.EvaluateOnce(context.Background(), "acme", "vm:101"); err == nil || !strings.Contains(err.Error(), "no operator state for") { + t.Fatalf("cross-org rerun error = %v, want missing operator state", err) + } + if len(evidenceOrgs) != 0 { + t.Fatalf("cross-org rerun gathered evidence for %v", evidenceOrgs) + } + if got := countReports("default"); got != 0 { + t.Fatalf("cross-org rerun wrote %d reports into the default org", got) + } + + acmeStart := now.Add(-3 * time.Hour) + acmeEnd := now.Add(-2 * time.Hour) + if err := stores["acme"].SetResourceOperatorState(unified.ResourceOperatorState{ + CanonicalID: "vm:101", + MaintenanceStartAt: &acmeStart, + MaintenanceEndAt: &acmeEnd, + SetAt: acmeStart, + SetBy: "operator", + }); err != nil { + t.Fatalf("seed acme operator state: %v", err) + } + report, err := sentinel.EvaluateOnce(context.Background(), "acme", "vm:101") + if err != nil { + t.Fatalf("evaluate once in acme: %v", err) + } + if report.WindowEndedAt == nil || !report.WindowEndedAt.Equal(acmeEnd) { + t.Fatalf("window end = %v, want acme's %v", report.WindowEndedAt, acmeEnd) + } + if len(evidenceOrgs) != 4 { + t.Fatalf("evidence providers called %d times, want 4", len(evidenceOrgs)) + } + for _, orgID := range evidenceOrgs { + if orgID != "acme" { + t.Fatalf("evidence gathered for org %q, want acme only (%v)", orgID, evidenceOrgs) + } + } + if got := countReports("acme"); got != 1 { + t.Fatalf("acme reports = %d, want 1", got) + } + if got := countReports("default"); got != 0 { + t.Fatalf("acme rerun wrote %d reports into the default org", got) + } +} diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go index bceb91c4a5..7078848579 100644 --- a/internal/monitoring/monitor_agents.go +++ b/internal/monitoring/monitor_agents.go @@ -1967,13 +1967,16 @@ func (m *Monitor) RebuildTokenBindings() { return } - // Build a set of valid token IDs from the current config + // Build a set of valid token IDs from the current config. Token writers + // edit the inventory in place under config.Mu. validTokens := make(map[string]struct{}) + config.Mu.RLock() for _, token := range m.config.APITokens { if token.ID != "" { validTokens[token.ID] = struct{}{} } } + config.Mu.RUnlock() // Rebuild Docker token bindings newDockerBindings := make(map[string]string) diff --git a/internal/monitoring/monitor_discovery_helpers.go b/internal/monitoring/monitor_discovery_helpers.go index d2d81140ad..5c2b6d3d2c 100644 --- a/internal/monitoring/monitor_discovery_helpers.go +++ b/internal/monitoring/monitor_discovery_helpers.go @@ -13,13 +13,19 @@ var lookupConfiguredHostIP = net.LookupIP // getConfiguredHostIPs returns a list of IP addresses from all configured Proxmox hosts. // This is used to prevent discovery from probing hosts we already know about. func (m *Monitor) getConfiguredHostIPs() []string { + // DeepCopy clones the API token records, which token writers edit in + // place under config.Mu. It is taken before the monitor lock, as in + // request authentication. + config.Mu.RLock() m.mu.RLock() if m.config == nil { m.mu.RUnlock() + config.Mu.RUnlock() return nil } cfg := m.config.DeepCopy() m.mu.RUnlock() + config.Mu.RUnlock() return configuredHostIPsFromConfig(cfg) } @@ -157,13 +163,17 @@ func mergeDiscoveryIPBlocklist(existing []string, discovered []string) []string } func (m *Monitor) discoveryConfigSnapshot() config.DiscoveryConfig { + // As in getConfiguredHostIPs: the copy includes the API token records. + config.Mu.RLock() m.mu.RLock() if m.config == nil { m.mu.RUnlock() + config.Mu.RUnlock() return config.DefaultDiscoveryConfig() } cfg := m.config.DeepCopy() m.mu.RUnlock() + config.Mu.RUnlock() discoveryCfg := config.CloneDiscoveryConfig(cfg.Discovery) discoveryCfg.IPBlocklist = mergeDiscoveryIPBlocklist(discoveryCfg.IPBlocklist, configuredHostIPsFromConfig(cfg)) diff --git a/pkg/server/telemetry_pulse_intelligence.go b/pkg/server/telemetry_pulse_intelligence.go index 7f78e429b7..eb44c45692 100644 --- a/pkg/server/telemetry_pulse_intelligence.go +++ b/pkg/server/telemetry_pulse_intelligence.go @@ -356,6 +356,9 @@ func applyPulseIntelligenceExternalAgentSnapshot( if currentCfg != nil { surfaceScopes := pulseIntelligenceExternalAgentSurfaceScopes(agentcapabilities.CanonicalManifest()) if len(surfaceScopes) > 0 { + // Token writers edit the inventory, and each record's Metadata + // map, in place under config.Mu; both checks clone the record. + config.Mu.RLock() for _, token := range currentCfg.APITokens { if pulseIntelligenceExternalAgentToken(token, surfaceScopes, now) { snap.PulseIntelligenceExternalAgentEnabled = true @@ -367,6 +370,7 @@ func applyPulseIntelligenceExternalAgentSnapshot( break } } + config.Mu.RUnlock() } } if persistence == nil {