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.

Preserve grandfathered monitored-system floors for v5 upgrades

rcourtman10f1459d1a5a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index fa0ceb8aa4..d51c8b0b5f 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -200,7 +200,12 @@ management, and fleet control surfaces.
commercial-owned `checkout_intent_id`, purchase-return tokens,
activation-bridge form state, owned billing purchase-arrival states, or
demo-hidden commercial route policy as installer credentials,
- registration state, or fleet enrollment authority.
+ registration state, or fleet enrollment authority. The same adjacent
+ commercial boundary now also owns migrated-v5 monitored-system
+ grandfathering: lifecycle surfaces may react to the resulting license or
+ entitlements payloads, but they must not cache their own pre-activation
+ host counts, synthesize a second grandfather floor, or treat install-time
+ fleet inventory as the authority for commercial continuity.
## Forbidden Paths
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 4cf29e3bf0..ace055bcf7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1186,6 +1186,13 @@ resolved, those API contracts must fail closed for net-new admissions rather
than serializing a fake zero. `/api/license/entitlements` therefore carries
limit-level `current_available` truth so clients can distinguish unavailable
monitored-system usage from a real `current: 0`.
+That same contract now also owns migrated legacy continuity. When a supported
+v5 license auto-exchanges or is activated manually in v6, `/api/license/status`
+and `/api/license/entitlements` must surface `max_monitored_systems` from the
+greater of the exchanged plan limit and the one-time deduped monitored-system
+floor captured from canonical runtime usage, and restored grant activations
+must backfill that floor once canonical usage becomes available instead of
+falling back to the raw exchanged grant limit after restart.
That same configured-path contract now also has an explicit shared owner for
manual auth env files: `internal/api/auth_env_path.go` must remain the only
place that derives `.env` from configured runtime paths, and neighboring
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 3bf2ebd3ff..2ccf93016e 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -775,6 +775,14 @@ when a recurring v5 customer migrates into v6, billing persistence,
entitlement evaluation, renewal handling, and Pro-license presentation must
preserve the customer's existing recurring price identity instead of silently
rewriting them onto current v6 retail pricing.
+That same continuity boundary now also owns monitored-system capacity
+preservation for migrated self-hosted estates. Activation persistence and
+grant refresh must carry local-only legacy-migration continuity metadata, and
+when canonical deduped monitored-system usage first resolves on a migrated
+installation Pulse must persist a one-time grandfather floor so status,
+runtime entitlement evaluation, and later restore/refresh flows keep the
+existing estate admissible without silently grandfathering post-migration
+growth.
That continuity rule cannot depend on webhook metadata being perfect. The
canonical Stripe price-to-plan lookup in `pkg/licensing/features.go` and
`pkg/licensing/stripe_subscription.go` must recognize the still-renewing
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c636c98684..ad2674ae75 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -169,7 +169,13 @@ querying, and the operator-facing storage health presentation layer.
`checkout_intent_id`, purchase-return tokens, activation-bridge
callbacks, owned billing purchase-arrival states, or demo-hidden
commercial route policy as recovery identity, restore proof, preview
- framing, or backup/recovery-local transport.
+ framing, or backup/recovery-local transport. That same adjacent commercial
+ boundary now also owns migrated-v5 monitored-system grandfathering:
+ storage and recovery may read the resulting entitlement limits as context,
+ but they must not infer a second capacity floor from protected inventory,
+ backup counts, or recovery-point presence when commercial continuity is
+ already defined by the canonical monitored-system resolver and activation
+ persistence.
## Forbidden Paths
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 1873233e86..c8e5134808 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -4803,6 +4803,160 @@ func TestContract_EntitlementPayloadMonitoredSystemUsageUnavailableJSONSnapshot(
assertJSONSnapshot(t, got, want)
}
+func TestContract_LegacyMigrationGrandfatherFloorJSONSnapshot(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+
+ grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{
+ LicenseID: "lic_contract_floor",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ Email: "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("generate grant jwt: %v", err)
+ }
+ pkglicensing.SetPublicKey(grantPublicKey)
+ t.Cleanup(func() { pkglicensing.SetPublicKey(nil) })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/licenses/exchange" {
+ t.Fatalf("path = %q, want /v1/licenses/exchange", r.URL.Path)
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(pkglicensing.ActivateInstallationResponse{
+ License: pkglicensing.ActivateResponseLicense{
+ LicenseID: "lic_contract_floor",
+ State: "active",
+ Tier: "pro",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ },
+ Installation: pkglicensing.ActivateResponseInstallation{
+ InstallationID: "inst_contract_floor",
+ InstallationToken: "pit_live_contract_floor",
+ Status: "active",
+ },
+ Grant: pkglicensing.GrantEnvelope{
+ JWT: grantJWT,
+ JTI: "grant_contract_floor",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
+
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ cp, err := mtp.GetPersistence("default")
+ if err != nil {
+ t.Fatalf("init default persistence: %v", err)
+ }
+ persistence, err := pkglicensing.NewPersistence(cp.GetConfigDir())
+ if err != nil {
+ t.Fatalf("new persistence: %v", err)
+ }
+ legacyJWT, err := pkglicensing.GenerateLicenseForTesting("[email protected]", pkglicensing.TierPro, 24*time.Hour)
+ if err != nil {
+ t.Fatalf("generate test license: %v", err)
+ }
+ if err := persistence.Save(legacyJWT); err != nil {
+ t.Fatalf("save legacy jwt: %v", err)
+ }
+
+ handlers := NewLicenseHandlers(mtp, false)
+ handlers.SetMonitors(buildGrandfatherFloorMonitor(23), nil)
+ t.Cleanup(handlers.StopAllBackgroundLoops)
+
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
+
+ statusReq := httptest.NewRequest(http.MethodGet, "/api/license/status", nil).WithContext(ctx)
+ statusRec := httptest.NewRecorder()
+ handlers.HandleLicenseStatus(statusRec, statusReq)
+ if statusRec.Code != http.StatusOK {
+ t.Fatalf("status=%d, want %d: %s", statusRec.Code, http.StatusOK, statusRec.Body.String())
+ }
+
+ entReq := httptest.NewRequest(http.MethodGet, "/api/license/entitlements", nil).WithContext(ctx)
+ entRec := httptest.NewRecorder()
+ handlers.HandleEntitlements(entRec, entReq)
+ if entRec.Code != http.StatusOK {
+ t.Fatalf("entitlements status=%d, want %d: %s", entRec.Code, http.StatusOK, entRec.Body.String())
+ }
+
+ var status pkglicensing.LicenseStatus
+ if err := json.Unmarshal(statusRec.Body.Bytes(), &status); err != nil {
+ t.Fatalf("decode status: %v", err)
+ }
+ var payload EntitlementPayload
+ if err := json.Unmarshal(entRec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode entitlements: %v", err)
+ }
+
+ got, err := json.Marshal(struct {
+ Status struct {
+ Tier pkglicensing.Tier `json:"tier"`
+ PlanVersion string `json:"plan_version"`
+ MaxMonitoredSystems int `json:"max_monitored_systems"`
+ Valid bool `json:"valid"`
+ } `json:"status"`
+ Entitlements struct {
+ Tier string `json:"tier"`
+ PlanVersion string `json:"plan_version"`
+ SubscriptionState string `json:"subscription_state"`
+ Limits []pkglicensing.LimitStatus `json:"limits"`
+ } `json:"entitlements"`
+ }{
+ Status: struct {
+ Tier pkglicensing.Tier `json:"tier"`
+ PlanVersion string `json:"plan_version"`
+ MaxMonitoredSystems int `json:"max_monitored_systems"`
+ Valid bool `json:"valid"`
+ }{
+ Tier: status.Tier,
+ PlanVersion: status.PlanVersion,
+ MaxMonitoredSystems: status.MaxMonitoredSystems,
+ Valid: status.Valid,
+ },
+ Entitlements: struct {
+ Tier string `json:"tier"`
+ PlanVersion string `json:"plan_version"`
+ SubscriptionState string `json:"subscription_state"`
+ Limits []pkglicensing.LimitStatus `json:"limits"`
+ }{
+ Tier: payload.Tier,
+ PlanVersion: payload.PlanVersion,
+ SubscriptionState: payload.SubscriptionState,
+ Limits: payload.Limits,
+ },
+ })
+ if err != nil {
+ t.Fatalf("marshal snapshot payload: %v", err)
+ }
+
+ const want = `{
+ "status":{
+ "tier":"pro",
+ "plan_version":"v5_pro_monthly_grandfathered",
+ "max_monitored_systems":23,
+ "valid":true
+ },
+ "entitlements":{
+ "tier":"pro",
+ "plan_version":"v5_pro_monthly_grandfathered",
+ "subscription_state":"active",
+ "limits":[{"key":"max_monitored_systems","limit":23,"current":23,"current_available":true,"state":"enforced"}]
+ }
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_HostedBillingStateFallbackJSONSnapshot(t *testing.T) {
baseDir := t.TempDir()
store := config.NewFileBillingStore(baseDir)
diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.go
index 93989570d1..d4d453f6fc 100644
--- a/internal/api/licensing_handlers.go
+++ b/internal/api/licensing_handlers.go
@@ -516,6 +516,7 @@ func (h *LicenseHandlers) getTenantComponents(ctx context.Context) (*licenseServ
if err := h.ensureEvaluatorForOrg(orgID, svc); err != nil {
log.Warn().Str("org_id", orgID).Err(err).Msg("Failed to refresh license evaluator for org")
}
+ h.ensureLegacyMigrationGrandfatherFloor(ctx, svc)
h.ensureHostedEntitlementRefreshForOrg(orgID, svc)
// We need persistence too, reconstruct it or cache it?
// Reconstructing persistence is cheap (just a struct with path).
@@ -553,6 +554,7 @@ func (h *LicenseHandlers) getTenantComponents(ctx context.Context) (*licenseServ
if err := service.RestoreActivation(activationState); err != nil {
log.Warn().Str("org_id", orgID).Err(err).Msg("Failed to restore activation")
} else {
+ h.ensureLegacyMigrationGrandfatherFloor(ctx, service)
if clearErr := h.setCommercialMigrationState(orgID, nil); clearErr != nil {
log.Warn().Str("org_id", orgID).Err(clearErr).Msg("Failed to clear commercial migration state after activation restore")
}
@@ -582,6 +584,7 @@ func (h *LicenseHandlers) getTenantComponents(ctx context.Context) (*licenseServ
}
log.Warn().Str("org_id", orgID).Err(err).Msg("Failed to auto-exchange persisted legacy license")
} else if service.IsActivated() {
+ h.ensureLegacyMigrationGrandfatherFloor(ctx, service)
if clearErr := h.setCommercialMigrationState(orgID, nil); clearErr != nil {
log.Warn().Str("org_id", orgID).Err(clearErr).Msg("Failed to clear commercial migration state after successful auto-exchange")
}
@@ -616,6 +619,40 @@ func (h *LicenseHandlers) getTenantComponents(ctx context.Context) (*licenseServ
return service, persistence, nil
}
+func (h *LicenseHandlers) canonicalMonitoredSystemGrandfatherFloor(ctx context.Context) (int, bool) {
+ usage := h.entitlementUsageSnapshot(ctx)
+ if !usage.MonitoredSystemsAvailable {
+ return 0, false
+ }
+ if usage.MonitoredSystems < 0 {
+ return 0, false
+ }
+ return int(usage.MonitoredSystems), true
+}
+
+func (h *LicenseHandlers) ensureLegacyMigrationGrandfatherFloor(ctx context.Context, service *licenseService) {
+ if h == nil || service == nil {
+ return
+ }
+
+ count, ok := h.canonicalMonitoredSystemGrandfatherFloor(ctx)
+ if !ok {
+ return
+ }
+
+ if err := service.CaptureLegacyMonitoredSystemGrandfatherFloor(count); err != nil {
+ orgID := GetOrgID(ctx)
+ if orgID == "" {
+ orgID = "default"
+ }
+ log.Warn().
+ Str("org_id", orgID).
+ Int("monitored_systems", count).
+ Err(err).
+ Msg("Failed to persist migrated monitored-system grandfather floor")
+ }
+}
+
func (h *LicenseHandlers) ensureEvaluatorForOrg(orgID string, service *licenseService) error {
if h == nil || service == nil || h.mtPersistence == nil {
return nil
@@ -1313,6 +1350,9 @@ func (h *LicenseHandlers) activateLicenseKey(ctx context.Context, licenseKey str
}
if service.IsActivated() {
+ if migratedLegacyKey {
+ h.ensureLegacyMigrationGrandfatherFloor(ctx, service)
+ }
h.stopHostedEntitlementRefreshLoop(orgID)
if clearErr := h.setCommercialMigrationState(orgID, nil); clearErr != nil {
log.Warn().Err(clearErr).Str("org_id", orgID).Msg("Failed to clear commercial migration state after activation")
diff --git a/internal/api/licensing_handlers_auto_migrate_test.go b/internal/api/licensing_handlers_auto_migrate_test.go
index 37b07e0d0b..8ad6e57b6b 100644
--- a/internal/api/licensing_handlers_auto_migrate_test.go
+++ b/internal/api/licensing_handlers_auto_migrate_test.go
@@ -3,6 +3,7 @@ package api
import (
"context"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
@@ -10,6 +11,8 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
@@ -292,6 +295,300 @@ func TestGetTenantComponents_PersistsCommercialMigrationState_WhenAutoExchangeFa
handlers.StopAllBackgroundLoops()
}
+func TestGetTenantComponents_AutoExchangeGrandfathersObservedMonitoredSystems(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+
+ grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{
+ LicenseID: "lic_floor_auto",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ Email: "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("generate grant jwt: %v", err)
+ }
+ pkglicensing.SetPublicKey(grantPublicKey)
+ t.Cleanup(func() { pkglicensing.SetPublicKey(nil) })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/licenses/exchange" {
+ t.Fatalf("path = %q, want /v1/licenses/exchange", r.URL.Path)
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(pkglicensing.ActivateInstallationResponse{
+ License: pkglicensing.ActivateResponseLicense{
+ LicenseID: "lic_floor_auto",
+ State: "active",
+ Tier: "pro",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ },
+ Installation: pkglicensing.ActivateResponseInstallation{
+ InstallationID: "inst_floor_auto",
+ InstallationToken: "pit_live_floor_auto",
+ Status: "active",
+ },
+ Grant: pkglicensing.GrantEnvelope{
+ JWT: grantJWT,
+ JTI: "grant_floor_auto",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
+
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ cp, err := mtp.GetPersistence("default")
+ if err != nil {
+ t.Fatalf("init default persistence: %v", err)
+ }
+
+ legacyJWT, err := pkglicensing.GenerateLicenseForTesting("[email protected]", pkglicensing.TierPro, 24*time.Hour)
+ if err != nil {
+ t.Fatalf("generate test license: %v", err)
+ }
+ persistence, err := pkglicensing.NewPersistence(cp.GetConfigDir())
+ if err != nil {
+ t.Fatalf("new persistence: %v", err)
+ }
+ if err := persistence.Save(legacyJWT); err != nil {
+ t.Fatalf("save legacy jwt: %v", err)
+ }
+
+ handlers := NewLicenseHandlers(mtp, false)
+ handlers.SetMonitors(buildGrandfatherFloorMonitor(23), nil)
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
+ svc := handlers.Service(ctx)
+ if svc == nil {
+ t.Fatal("expected non-nil service")
+ }
+ if !svc.IsActivated() {
+ t.Fatal("expected persisted legacy JWT to auto-exchange into activation state")
+ }
+ if got := svc.Status().MaxMonitoredSystems; got != 23 {
+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23", got)
+ }
+ if activationState, err := persistence.LoadActivationState(); err != nil {
+ t.Fatalf("load activation state: %v", err)
+ } else if activationState == nil {
+ t.Fatal("expected activation state after legacy exchange")
+ } else {
+ if !activationState.Continuity.LegacyMigration {
+ t.Fatal("expected legacy migration continuity flag")
+ }
+ if activationState.Continuity.GrandfatheredMaxMonitoredSystems != 23 {
+ t.Fatalf("GrandfatheredMaxMonitoredSystems=%d, want 23", activationState.Continuity.GrandfatheredMaxMonitoredSystems)
+ }
+ if activationState.Continuity.GrandfatheredMonitoredSystemsCapturedAt == 0 {
+ t.Fatal("expected grandfather capture timestamp")
+ }
+ }
+
+ handlers.StopAllBackgroundLoops()
+}
+
+func TestGetTenantComponents_BackfillsGrandfatherFloorAfterRestoreWhenMonitorArrivesLate(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+
+ grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{
+ LicenseID: "lic_floor_restore",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ Email: "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("generate grant jwt: %v", err)
+ }
+ pkglicensing.SetPublicKey(grantPublicKey)
+ t.Cleanup(func() { pkglicensing.SetPublicKey(nil) })
+
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ cp, err := mtp.GetPersistence("default")
+ if err != nil {
+ t.Fatalf("init default persistence: %v", err)
+ }
+ persistence, err := pkglicensing.NewPersistence(cp.GetConfigDir())
+ if err != nil {
+ t.Fatalf("new persistence: %v", err)
+ }
+ if err := persistence.SaveActivationState(&pkglicensing.ActivationState{
+ InstallationID: "inst_floor_restore",
+ InstallationToken: "pit_live_floor_restore",
+ LicenseID: "lic_floor_restore",
+ GrantJWT: grantJWT,
+ GrantJTI: "grant_floor_restore",
+ GrantExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ InstanceFingerprint: "fp-floor-restore",
+ LicenseServerURL: "https://license.pulserelay.pro",
+ ActivatedAt: time.Now().Add(-time.Hour).Unix(),
+ LastRefreshedAt: time.Now().Add(-time.Hour).Unix(),
+ Continuity: pkglicensing.ActivationContinuity{
+ LegacyMigration: true,
+ },
+ }); err != nil {
+ t.Fatalf("save activation state: %v", err)
+ }
+
+ handlers := NewLicenseHandlers(mtp, false)
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
+ svc := handlers.Service(ctx)
+ if svc == nil {
+ t.Fatal("expected non-nil service")
+ }
+ if got := svc.Status().MaxMonitoredSystems; got != 10 {
+ t.Fatalf("initial status.MaxMonitoredSystems=%d, want 10 before floor capture", got)
+ }
+
+ handlers.SetMonitors(buildGrandfatherFloorMonitor(23), nil)
+ svc = handlers.Service(ctx)
+ if svc == nil {
+ t.Fatal("expected cached service")
+ }
+ if got := svc.Status().MaxMonitoredSystems; got != 23 {
+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23 after late monitor capture", got)
+ }
+
+ loaded, err := persistence.LoadActivationState()
+ if err != nil {
+ t.Fatalf("load activation state: %v", err)
+ }
+ if loaded == nil {
+ t.Fatal("expected activation state")
+ }
+ if loaded.Continuity.GrandfatheredMaxMonitoredSystems != 23 {
+ t.Fatalf("GrandfatheredMaxMonitoredSystems=%d, want 23", loaded.Continuity.GrandfatheredMaxMonitoredSystems)
+ }
+ if loaded.Continuity.GrandfatheredMonitoredSystemsCapturedAt == 0 {
+ t.Fatal("expected captured timestamp after late monitor restore")
+ }
+
+ handlers.StopAllBackgroundLoops()
+}
+
+func TestActivateLicenseKey_GrandfathersObservedMonitoredSystemsForLegacyMigration(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+
+ grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{
+ LicenseID: "lic_floor_manual",
+ Tier: "pro",
+ PlanKey: "v5_pro_annual_grandfathered",
+ State: "active",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ Email: "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("generate grant jwt: %v", err)
+ }
+ pkglicensing.SetPublicKey(grantPublicKey)
+ t.Cleanup(func() { pkglicensing.SetPublicKey(nil) })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/licenses/exchange" {
+ t.Fatalf("path = %q, want /v1/licenses/exchange", r.URL.Path)
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(pkglicensing.ActivateInstallationResponse{
+ License: pkglicensing.ActivateResponseLicense{
+ LicenseID: "lic_floor_manual",
+ State: "active",
+ Tier: "pro",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ },
+ Installation: pkglicensing.ActivateResponseInstallation{
+ InstallationID: "inst_floor_manual",
+ InstallationToken: "pit_live_floor_manual",
+ Status: "active",
+ },
+ Grant: pkglicensing.GrantEnvelope{
+ JWT: grantJWT,
+ JTI: "grant_floor_manual",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
+
+ handlers := createTestHandler(t)
+ handlers.SetMonitors(buildGrandfatherFloorMonitor(23), nil)
+ t.Cleanup(handlers.StopAllBackgroundLoops)
+
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
+ legacyJWT, err := pkglicensing.GenerateLicenseForTesting("[email protected]", pkglicensing.TierPro, 24*time.Hour)
+ if err != nil {
+ t.Fatalf("generate test license: %v", err)
+ }
+
+ resp, err := handlers.activateLicenseKey(ctx, legacyJWT)
+ if err != nil {
+ t.Fatalf("activateLicenseKey: %v", err)
+ }
+ if !resp.Success {
+ t.Fatalf("expected success, got %+v", resp)
+ }
+
+ svc := handlers.Service(ctx)
+ if svc == nil {
+ t.Fatal("expected non-nil service")
+ }
+ if got := svc.Status().MaxMonitoredSystems; got != 23 {
+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23", got)
+ }
+}
+
+func buildGrandfatherFloorMonitor(count int) *monitoring.Monitor {
+ now := time.Now().UTC()
+ registry := unifiedresources.NewRegistry(nil)
+ records := make([]unifiedresources.IngestRecord, 0, count)
+ for i := 0; i < count; i++ {
+ id := fmt.Sprintf("host-%02d", i+1)
+ hostname := fmt.Sprintf("legacy-%02d.lab.local", i+1)
+ machineID := fmt.Sprintf("machine-%02d", i+1)
+ records = append(records, unifiedresources.IngestRecord{
+ SourceID: id,
+ Resource: unifiedresources.Resource{
+ ID: id,
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: hostname,
+ Status: unifiedresources.StatusOnline,
+ LastSeen: now,
+ UpdatedAt: now,
+ Agent: &unifiedresources.AgentData{
+ AgentID: "agent-" + id,
+ Hostname: hostname,
+ MachineID: machineID,
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ MachineID: machineID,
+ Hostnames: []string{hostname},
+ },
+ },
+ })
+ }
+ registry.IngestRecords(unifiedresources.SourceAgent, records)
+
+ monitor := &monitoring.Monitor{}
+ monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(registry))
+ return monitor
+}
+
// base64RawURLEncode is a helper for tests.
func base64RawURLEncode(data []byte) string {
// Use the same encoding as JWT: base64 URL-safe without padding.
diff --git a/pkg/licensing/activation_types.go b/pkg/licensing/activation_types.go
index 7aac6e006f..c97c8f65f8 100644
--- a/pkg/licensing/activation_types.go
+++ b/pkg/licensing/activation_types.go
@@ -17,16 +17,81 @@ const DefaultLicenseServerURL = "https://license.pulserelay.pro"
// ActivationState holds the local state for an activation-key-based license.
// Persisted encrypted on disk via Persistence.SaveActivationState.
type ActivationState struct {
- InstallationID string `json:"installation_id"` // inst_...
- InstallationToken string `json:"installation_token"` // pit_live_... (secret)
- LicenseID string `json:"license_id"` // lic_...
- GrantJWT string `json:"grant_jwt"` // current relay grant JWT
- GrantJTI string `json:"grant_jti"` // grant ID for dedup
- GrantExpiresAt int64 `json:"grant_expires_at"` // Unix timestamp
- InstanceFingerprint string `json:"instance_fingerprint"` // stable UUID for this installation
- LicenseServerURL string `json:"license_server_url"` // base URL used for this activation
- ActivatedAt int64 `json:"activated_at"` // Unix timestamp of initial activation
- LastRefreshedAt int64 `json:"last_refreshed_at"` // Unix timestamp of last grant refresh
+ InstallationID string `json:"installation_id"` // inst_...
+ InstallationToken string `json:"installation_token"` // pit_live_... (secret)
+ LicenseID string `json:"license_id"` // lic_...
+ GrantJWT string `json:"grant_jwt"` // current relay grant JWT
+ GrantJTI string `json:"grant_jti"` // grant ID for dedup
+ GrantExpiresAt int64 `json:"grant_expires_at"` // Unix timestamp
+ InstanceFingerprint string `json:"instance_fingerprint"` // stable UUID for this installation
+ LicenseServerURL string `json:"license_server_url"` // base URL used for this activation
+ ActivatedAt int64 `json:"activated_at"` // Unix timestamp of initial activation
+ LastRefreshedAt int64 `json:"last_refreshed_at"` // Unix timestamp of last grant refresh
+ Continuity ActivationContinuity `json:"continuity,omitempty"`
+}
+
+// ActivationContinuity captures local-only continuity state that must survive
+// activation restore and grant refresh without becoming part of the server
+// grant wire contract.
+type ActivationContinuity struct {
+ // LegacyMigration marks installations activated from a supported v5 license
+ // exchange rather than a native v6 activation key.
+ LegacyMigration bool `json:"legacy_migration,omitempty"`
+
+ // GrandfatheredMaxMonitoredSystems stores the deduped monitored-system floor
+ // captured for a migrated v5 installation when its existing estate exceeds
+ // the exchanged plan limit.
+ GrandfatheredMaxMonitoredSystems int `json:"grandfathered_max_monitored_systems,omitempty"`
+
+ // GrandfatheredMonitoredSystemsCapturedAt marks that the migration floor was
+ // resolved exactly once from canonical runtime usage, even when no override
+ // was needed because the observed estate was already within the exchanged
+ // plan limit.
+ GrandfatheredMonitoredSystemsCapturedAt int64 `json:"grandfathered_monitored_systems_captured_at,omitempty"`
+}
+
+func normalizeActivationContinuity(continuity ActivationContinuity) ActivationContinuity {
+ if continuity.GrandfatheredMaxMonitoredSystems < 0 {
+ continuity.GrandfatheredMaxMonitoredSystems = 0
+ }
+ if continuity.GrandfatheredMonitoredSystemsCapturedAt < 0 {
+ continuity.GrandfatheredMonitoredSystemsCapturedAt = 0
+ }
+ return continuity
+}
+
+func (c ActivationContinuity) needsLegacyMonitoredSystemCapture() bool {
+ c = normalizeActivationContinuity(c)
+ return c.LegacyMigration && c.GrandfatheredMonitoredSystemsCapturedAt == 0
+}
+
+func applyActivationContinuityToClaims(claims *Claims, continuity ActivationContinuity) {
+ if claims == nil {
+ return
+ }
+
+ continuity = normalizeActivationContinuity(continuity)
+ if continuity.GrandfatheredMaxMonitoredSystems <= 0 {
+ return
+ }
+
+ currentLimit := int64(0)
+ if existing, ok := claims.EffectiveLimits()[MaxMonitoredSystemsLicenseGateKey]; ok {
+ currentLimit = existing
+ }
+ if currentLimit >= int64(continuity.GrandfatheredMaxMonitoredSystems) {
+ return
+ }
+
+ if claims.Limits == nil {
+ claims.Limits = map[string]int64{}
+ } else {
+ claims.Limits = NormalizeMonitoredSystemLimits(claims.Limits)
+ }
+ claims.Limits[MaxMonitoredSystemsLicenseGateKey] = int64(continuity.GrandfatheredMaxMonitoredSystems)
+ if claims.MaxMonitoredSystems < continuity.GrandfatheredMaxMonitoredSystems {
+ claims.MaxMonitoredSystems = continuity.GrandfatheredMaxMonitoredSystems
+ }
}
// GrantClaims are the claims parsed from a relay grant JWT payload.
@@ -65,6 +130,10 @@ func (g *GrantClaims) UnmarshalJSON(data []byte) error {
// grantClaimsToClaims maps grant claims to the existing Claims struct
// so that all feature gating and monitored-system limits work unchanged.
func grantClaimsToClaims(gc *GrantClaims) Claims {
+ return grantClaimsToClaimsWithContinuity(gc, ActivationContinuity{})
+}
+
+func grantClaimsToClaimsWithContinuity(gc *GrantClaims, continuity ActivationContinuity) Claims {
c := Claims{
LicenseID: gc.LicenseID,
Email: gc.Email,
@@ -90,12 +159,22 @@ func grantClaimsToClaims(gc *GrantClaims) Claims {
c.SubState = SubStateSuspended
}
+ applyActivationContinuityToClaims(&c, continuity)
+
return c
}
// grantClaimsToLicense creates a License from parsed grant claims.
func grantClaimsToLicense(gc *GrantClaims, rawJWT string) *License {
- claims := grantClaimsToClaims(gc)
+ return grantClaimsToLicenseWithContinuity(gc, rawJWT, ActivationContinuity{})
+}
+
+func grantClaimsToLicenseWithContinuity(
+ gc *GrantClaims,
+ rawJWT string,
+ continuity ActivationContinuity,
+) *License {
+ claims := grantClaimsToClaimsWithContinuity(gc, continuity)
lic := &License{
Raw: rawJWT,
diff --git a/pkg/licensing/activation_types_test.go b/pkg/licensing/activation_types_test.go
index 7b0b874c68..dfdb014288 100644
--- a/pkg/licensing/activation_types_test.go
+++ b/pkg/licensing/activation_types_test.go
@@ -179,6 +179,54 @@ func TestGrantClaimsToLicense(t *testing.T) {
})
}
+func TestGrantClaimsToClaimsWithContinuityAppliesGrandfatherFloor(t *testing.T) {
+ gc := &GrantClaims{
+ LicenseID: "lic_floor",
+ State: "active",
+ Tier: "pro",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ }
+
+ claims := grantClaimsToClaimsWithContinuity(gc, ActivationContinuity{
+ LegacyMigration: true,
+ GrandfatheredMaxMonitoredSystems: 23,
+ GrandfatheredMonitoredSystemsCapturedAt: time.Now().Unix(),
+ })
+
+ if claims.MaxMonitoredSystems != 23 {
+ t.Fatalf("MaxMonitoredSystems = %d, want 23", claims.MaxMonitoredSystems)
+ }
+ if got := claims.EffectiveLimits()[MaxMonitoredSystemsLicenseGateKey]; got != 23 {
+ t.Fatalf("EffectiveLimits()[max_monitored_systems] = %d, want 23", got)
+ }
+}
+
+func TestGrantClaimsToClaimsWithContinuityDoesNotLowerGrantLimit(t *testing.T) {
+ gc := &GrantClaims{
+ LicenseID: "lic_noop",
+ State: "active",
+ Tier: "pro",
+ MaxMonitoredSystems: 15,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ }
+
+ claims := grantClaimsToClaimsWithContinuity(gc, ActivationContinuity{
+ LegacyMigration: true,
+ GrandfatheredMaxMonitoredSystems: 10,
+ GrandfatheredMonitoredSystemsCapturedAt: time.Now().Unix(),
+ })
+
+ if claims.MaxMonitoredSystems != 15 {
+ t.Fatalf("MaxMonitoredSystems = %d, want 15", claims.MaxMonitoredSystems)
+ }
+ if got := claims.EffectiveLimits()[MaxMonitoredSystemsLicenseGateKey]; got != 15 {
+ t.Fatalf("EffectiveLimits()[max_monitored_systems] = %d, want 15", got)
+ }
+}
+
func TestGrantClaimsToClaimsCanonicalizesCloudPlanAtEntitlementBoundary(t *testing.T) {
gc := &GrantClaims{
LicenseID: "lic_cloud",
diff --git a/pkg/licensing/grant_refresh.go b/pkg/licensing/grant_refresh.go
index 0438e65570..a362f952fc 100644
--- a/pkg/licensing/grant_refresh.go
+++ b/pkg/licensing/grant_refresh.go
@@ -209,7 +209,11 @@ func (s *Service) refreshGrantOnce(ctx context.Context) error {
}
// Update the license from the new grant.
- lic := grantClaimsToLicense(gc, resp.Grant.JWT)
+ continuity := ActivationContinuity{}
+ if state != nil {
+ continuity = normalizeActivationContinuity(state.Continuity)
+ }
+ lic := grantClaimsToLicenseWithContinuity(gc, resp.Grant.JWT, continuity)
s.mu.Lock()
@@ -231,6 +235,7 @@ func (s *Service) refreshGrantOnce(ctx context.Context) error {
s.activationState.GrantJTI = resp.Grant.JTI
s.activationState.GrantExpiresAt = resp.Grant.ParseExpiresAt()
s.activationState.LastRefreshedAt = time.Now().Unix()
+ s.activationState.Continuity = continuity
}
cb := s.onLicenseChange
diff --git a/pkg/licensing/grant_refresh_test.go b/pkg/licensing/grant_refresh_test.go
index f2aaf86dff..a3717cfe49 100644
--- a/pkg/licensing/grant_refresh_test.go
+++ b/pkg/licensing/grant_refresh_test.go
@@ -444,6 +444,93 @@ func TestRefreshGrantOnce_PersistsState(t *testing.T) {
}
}
+func TestRefreshGrantOnce_PreservesLegacyGrandfatherFloor(t *testing.T) {
+ setupTestPublicKey(t)
+
+ newGrantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_refreshed_floor",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(RefreshGrantResponse{
+ Grant: GrantEnvelope{
+ JWT: newGrantJWT,
+ JTI: "grant_refreshed_floor",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+
+ tmpDir, err := os.MkdirTemp("", "pulse-refresh-floor-*")
+ if err != nil {
+ t.Fatalf("create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ p, err := NewPersistence(tmpDir)
+ if err != nil {
+ t.Fatalf("create persistence: %v", err)
+ }
+
+ initialGrantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_initial_floor",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ svc := NewService()
+ svc.SetLicenseServerClient(NewLicenseServerClient(server.URL))
+ svc.SetPersistence(p)
+
+ state := &ActivationState{
+ InstallationID: "inst_refresh_floor",
+ InstallationToken: "pit_live_refresh_floor",
+ LicenseID: "lic_initial_floor",
+ GrantJWT: initialGrantJWT,
+ GrantJTI: "grant_old_floor",
+ InstanceFingerprint: "fp-refresh-floor",
+ Continuity: ActivationContinuity{
+ LegacyMigration: true,
+ GrandfatheredMaxMonitoredSystems: 23,
+ GrandfatheredMonitoredSystemsCapturedAt: time.Now().Unix(),
+ },
+ }
+ if err := svc.RestoreActivation(state); err != nil {
+ t.Fatalf("RestoreActivation: %v", err)
+ }
+
+ if err := svc.refreshGrantOnce(context.Background()); err != nil {
+ t.Fatalf("refreshGrantOnce: %v", err)
+ }
+
+ status := svc.Status()
+ if status.MaxMonitoredSystems != 23 {
+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23", status.MaxMonitoredSystems)
+ }
+
+ loaded, err := p.LoadActivationState()
+ if err != nil {
+ t.Fatalf("LoadActivationState: %v", err)
+ }
+ if loaded == nil {
+ t.Fatal("expected persisted activation state")
+ }
+ if loaded.Continuity.GrandfatheredMaxMonitoredSystems != 23 {
+ t.Fatalf("GrandfatheredMaxMonitoredSystems=%d, want 23", loaded.Continuity.GrandfatheredMaxMonitoredSystems)
+ }
+}
+
func TestRefreshGrantOnce_MissingCloudPlanFailsClosed(t *testing.T) {
setupTestPublicKey(t)
diff --git a/pkg/licensing/service.go b/pkg/licensing/service.go
index d8d5965530..1960d0ba71 100644
--- a/pkg/licensing/service.go
+++ b/pkg/licensing/service.go
@@ -243,7 +243,7 @@ func (s *Service) ActivateWithKey(activationKey string) (*License, error) {
return nil, fmt.Errorf("activation failed: %w", err)
}
- return s.applyActivationResponse(resp, fingerprint, client.BaseURL(), persistence)
+ return s.applyActivationResponse(resp, fingerprint, client.BaseURL(), persistence, ActivationContinuity{})
}
// ActivateLegacyLicense exchanges a legacy v5 JWT-style license for a v6 activation.
@@ -277,7 +277,9 @@ func (s *Service) ActivateLegacyLicense(legacyLicenseKey string) (*License, erro
return nil, fmt.Errorf("activation failed: %w", err)
}
- return s.applyActivationResponse(resp, fingerprint, client.BaseURL(), persistence)
+ return s.applyActivationResponse(resp, fingerprint, client.BaseURL(), persistence, ActivationContinuity{
+ LegacyMigration: true,
+ })
}
func (s *Service) applyActivationResponse(
@@ -285,6 +287,7 @@ func (s *Service) applyActivationResponse(
fingerprint string,
serverURL string,
persistence *Persistence,
+ continuity ActivationContinuity,
) (*License, error) {
// Parse the grant JWT to extract claims.
gc, err := verifyAndParseGrantJWT(resp.Grant.JWT)
@@ -293,7 +296,8 @@ func (s *Service) applyActivationResponse(
}
// Build the license from grant claims.
- lic := grantClaimsToLicense(gc, resp.Grant.JWT)
+ continuity = normalizeActivationContinuity(continuity)
+ lic := grantClaimsToLicenseWithContinuity(gc, resp.Grant.JWT, continuity)
// Build activation state for persistence and refresh.
now := time.Now().Unix()
@@ -308,6 +312,7 @@ func (s *Service) applyActivationResponse(
LicenseServerURL: serverURL,
ActivatedAt: now,
LastRefreshedAt: now,
+ Continuity: continuity,
}
s.mu.Lock()
@@ -383,13 +388,16 @@ func (s *Service) RestoreActivation(state *ActivationState) error {
return fmt.Errorf("parse persisted grant: %w", err)
}
- lic := grantClaimsToLicense(gc, state.GrantJWT)
+ stateCopy := *state
+ stateCopy.Continuity = normalizeActivationContinuity(stateCopy.Continuity)
+
+ lic := grantClaimsToLicenseWithContinuity(gc, stateCopy.GrantJWT, stateCopy.Continuity)
s.mu.Lock()
s.license = cloneLicense(lic)
source := NewTokenSource(&s.license.Claims)
s.evaluator = NewEvaluator(source)
- s.activationState = state
+ s.activationState = &stateCopy
cb := s.onLicenseChange
snapshot := cloneLicense(s.license)
s.mu.Unlock()
@@ -401,6 +409,66 @@ func (s *Service) RestoreActivation(state *ActivationState) error {
return nil
}
+// CaptureLegacyMonitoredSystemGrandfatherFloor resolves the one-time
+// monitored-system floor for a migrated legacy activation using the canonical
+// deduped monitored-system count observed at runtime.
+func (s *Service) CaptureLegacyMonitoredSystemGrandfatherFloor(count int) error {
+ if count < 0 {
+ count = 0
+ }
+
+ s.mu.Lock()
+ if s.activationState == nil {
+ s.mu.Unlock()
+ return nil
+ }
+
+ continuity := normalizeActivationContinuity(s.activationState.Continuity)
+ if !continuity.needsLegacyMonitoredSystemCapture() {
+ s.mu.Unlock()
+ return nil
+ }
+
+ currentLimit := 0
+ if s.license != nil {
+ currentLimit = monitoredSystemLimitFromClaims(s.license.Claims)
+ }
+ continuity.GrandfatheredMonitoredSystemsCapturedAt = time.Now().Unix()
+ if count > currentLimit {
+ continuity.GrandfatheredMaxMonitoredSystems = count
+ }
+ s.activationState.Continuity = continuity
+
+ shouldNotify := false
+ if s.license != nil {
+ claims := cloneClaims(s.license.Claims)
+ applyActivationContinuityToClaims(&claims, continuity)
+ updatedLimit := monitoredSystemLimitFromClaims(claims)
+ shouldNotify = updatedLimit != currentLimit
+ s.license.Claims = claims
+ source := NewTokenSource(&s.license.Claims)
+ s.evaluator = NewEvaluator(source)
+ }
+
+ stateCopy := *s.activationState
+ persistence := s.persistence
+ cb := s.onLicenseChange
+ snapshot := cloneLicense(s.license)
+ s.mu.Unlock()
+
+ if persistence != nil {
+ if err := persistence.SaveActivationState(&stateCopy); err != nil {
+ return fmt.Errorf("persist activation continuity: %w", err)
+ }
+ }
+
+ if shouldNotify && cb != nil {
+ cb(snapshot)
+ }
+
+ return nil
+}
+
// Clear removes the current license.
// If an activation-key license is present, it also stops the refresh loop and clears the state.
func (s *Service) Clear() {
@@ -796,6 +864,13 @@ func safeIntFromInt64(v int64) int {
return int(v)
}
+func monitoredSystemLimitFromClaims(claims Claims) int {
+ if limit, ok := claims.EffectiveLimits()[MaxMonitoredSystemsLicenseGateKey]; ok {
+ return safeIntFromInt64(limit)
+ }
+ return 0
+}
+
func remainingDaysCeil(expiresAtUnix, nowUnix int64) int {
deltaSeconds := expiresAtUnix - nowUnix
if deltaSeconds <= 0 {
diff --git a/pkg/licensing/service_activate_test.go b/pkg/licensing/service_activate_test.go
index 2dcb4c2c7d..0ac8a8433c 100644
--- a/pkg/licensing/service_activate_test.go
+++ b/pkg/licensing/service_activate_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
"strings"
"testing"
"time"
@@ -115,6 +116,156 @@ func TestServiceActivate_AllowsLegacyJWTInDevMode(t *testing.T) {
}
}
+func TestServiceActivate_ExchangedLegacyJWTMarksLegacyMigrationContinuity(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+ setupTestPublicKey(t)
+
+ tmpDir, err := os.MkdirTemp("", "pulse-service-legacy-*")
+ if err != nil {
+ t.Fatalf("create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ p, err := NewPersistence(tmpDir)
+ if err != nil {
+ t.Fatalf("create persistence: %v", err)
+ }
+
+ svc := NewService()
+ svc.SetPersistence(p)
+
+ licenseKey, err := GenerateLicenseForTesting("[email protected]", TierPro, 24*time.Hour)
+ if err != nil {
+ t.Fatalf("GenerateLicenseForTesting: %v", err)
+ }
+
+ grantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_continuity",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/licenses/exchange" {
+ t.Fatalf("Path = %q, want /v1/licenses/exchange", r.URL.Path)
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(ActivateInstallationResponse{
+ License: ActivateResponseLicense{
+ LicenseID: "lic_continuity",
+ State: "active",
+ Tier: "pro",
+ MaxMonitoredSystems: 10,
+ },
+ Installation: ActivateResponseInstallation{
+ InstallationID: "inst_continuity",
+ InstallationToken: "pit_live_continuity",
+ Status: "active",
+ },
+ Grant: GrantEnvelope{
+ JWT: grantJWT,
+ JTI: "grant_continuity",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+
+ svc.SetLicenseServerClient(NewLicenseServerClient(server.URL))
+
+ if _, err := svc.Activate(licenseKey); err != nil {
+ t.Fatalf("Activate: %v", err)
+ }
+
+ state := svc.GetActivationState()
+ if state == nil {
+ t.Fatal("expected activation state")
+ }
+ if !state.Continuity.LegacyMigration {
+ t.Fatal("expected legacy exchange to mark legacy migration continuity")
+ }
+ if state.Continuity.GrandfatheredMonitoredSystemsCapturedAt != 0 {
+ t.Fatalf("GrandfatheredMonitoredSystemsCapturedAt=%d, want 0 before capture", state.Continuity.GrandfatheredMonitoredSystemsCapturedAt)
+ }
+}
+
+func TestServiceCaptureLegacyMonitoredSystemGrandfatherFloorPersistsAndUpdatesStatus(t *testing.T) {
+ setupTestPublicKey(t)
+
+ tmpDir, err := os.MkdirTemp("", "pulse-service-floor-*")
+ if err != nil {
+ t.Fatalf("create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ p, err := NewPersistence(tmpDir)
+ if err != nil {
+ t.Fatalf("create persistence: %v", err)
+ }
+
+ initialGrantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_floor",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ svc := NewService()
+ svc.SetPersistence(p)
+ state := &ActivationState{
+ InstallationID: "inst_floor",
+ InstallationToken: "pit_live_floor",
+ LicenseID: "lic_floor",
+ GrantJWT: initialGrantJWT,
+ GrantJTI: "grant_floor",
+ InstanceFingerprint: "fp-floor",
+ Continuity: ActivationContinuity{
+ LegacyMigration: true,
+ },
+ }
+ if err := svc.RestoreActivation(state); err != nil {
+ t.Fatalf("RestoreActivation: %v", err)
+ }
+
+ if err := svc.CaptureLegacyMonitoredSystemGrandfatherFloor(23); err != nil {
+ t.Fatalf("CaptureLegacyMonitoredSystemGrandfatherFloor: %v", err)
+ }
+
+ status := svc.Status()
+ if status.MaxMonitoredSystems != 23 {
+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23", status.MaxMonitoredSystems)
+ }
+
+ current := svc.Current()
+ if current == nil {
+ t.Fatal("expected current license")
+ }
+ if got := current.Claims.EffectiveLimits()[MaxMonitoredSystemsLicenseGateKey]; got != 23 {
+ t.Fatalf("EffectiveLimits()[max_monitored_systems]=%d, want 23", got)
+ }
+
+ loaded, err := p.LoadActivationState()
+ if err != nil {
+ t.Fatalf("LoadActivationState: %v", err)
+ }
+ if loaded == nil {
+ t.Fatal("expected persisted activation state")
+ }
+ if loaded.Continuity.GrandfatheredMaxMonitoredSystems != 23 {
+ t.Fatalf("GrandfatheredMaxMonitoredSystems=%d, want 23", loaded.Continuity.GrandfatheredMaxMonitoredSystems)
+ }
+ if loaded.Continuity.GrandfatheredMonitoredSystemsCapturedAt == 0 {
+ t.Fatal("expected persisted capture timestamp")
+ }
+}
+
func TestServiceActivate_RejectsMalformedLegacyKeyOutsideDevMode(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "false")