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.

Support entitlement-backed quickstart bootstrap

rcourtmanac4872c8d601
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index a6ebfe2a8d..63e1121aa3 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -2245,6 +2245,127 @@
"kind": "file"
}
]
+ },
+ {
+ "id": "RA25",
+ "summary": "Patrol quickstart bootstrap must resolve a real server-verified commercial principal, never synthetic local identity: activated installs use installation tokens, while entitlement-backed trial or hosted runtimes use signed entitlement leases without fabricating installation-scoped activation state.",
+ "kind": "invariant",
+ "blocking_level": "repo-ready",
+ "proof_type": "automated",
+ "lane_ids": [
+ "L3",
+ "L6"
+ ],
+ "subsystem_ids": [
+ "ai-runtime",
+ "api-contracts",
+ "cloud-paid"
+ ],
+ "release_gate_ids": [],
+ "proof_commands": [
+ {
+ "id": "quickstart-dual-principal-license-server-tests",
+ "run": [
+ "go",
+ "-C",
+ "../pulse-pro/license-server",
+ "test",
+ "-run",
+ "TestHandleQuickstartBootstrap_.*HostedEntitlement|TestHandleQuickstartBootstrap_IssuesTokenForVerifiedInstallation|TestHandleQuickstartBootstrap_RequiresAuth",
+ "-count=1"
+ ]
+ },
+ {
+ "id": "quickstart-dual-principal-runtime-tests",
+ "run": [
+ "go",
+ "test",
+ "./internal/ai",
+ "./internal/api",
+ "./pkg/licensing",
+ "-run",
+ "Quickstart|AISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart|AISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingState|AISettingsHandler_UpdateSettings_QuickstartBootstrapBeforeEnableUsesActivationIdentity|ClientBootstrapQuickstart",
+ "-count=1"
+ ]
+ }
+ ],
+ "evidence": [
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/status.json",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/subsystems/ai-runtime.md",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/subsystems/api-contracts.md",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/subsystems/cloud-paid.md",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/quickstart.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/quickstart_test.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/api/ai_handlers_test.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/config/entitlement_billing_state.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "pkg/licensing/license_server_client.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "pkg/licensing/quickstart_bootstrap.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse-pro",
+ "path": "license-server/quickstart_entitlement.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse-pro",
+ "path": "license-server/quickstart_proxy.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse-pro",
+ "path": "license-server/quickstart_proxy_test.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse-pro",
+ "path": "license-server/quickstart_store.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse-pro",
+ "path": "license-server/secrets.env.template",
+ "kind": "file"
+ }
+ ]
}
],
"evidence_reference_policy": {
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 2b7244dd82..b42aa63b0a 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -129,24 +129,29 @@ management, and fleet control surfaces.
may be invoked by lifecycle-adjacent surfaces, but server-issued
quickstart tokens, Patrol quickstart credit snapshots, and AI runtime auth
remain `ai-runtime` plus `api-contracts` concerns rather than install-token
- or lifecycle credential state. Installation activation remains the only
- authority for Patrol quickstart bootstrap, so lifecycle flows must not
- reintroduce anonymous bootstrap identity or tenant-local commercial-owner
- surrogates when they traverse those shared handlers.
+ or lifecycle credential state. Server-verified runtime identity remains the
+ only authority for Patrol quickstart bootstrap: self-hosted installs use the
+ shared installation-scoped `activation.enc`, while entitled hosted lanes use
+ the signed entitlement lease already carried in canonical billing state.
+ Lifecycle flows must not reintroduce anonymous bootstrap identity,
+ tenant-local commercial-owner surrogates, or fake activation records when
+ they traverse those shared handlers.
That same shared quickstart boundary is vendor-neutral at the lifecycle
edge too: lifecycle-adjacent consumers may observe the stable
`quickstart:pulse-hosted` alias in AI settings payloads, but they must not
bake vendor model IDs or provider-model fallback rules into install or
activation flows just because those routes share the backend API tree.
- The shared installation-scoped `activation.enc` path is that authority:
- tenant-local lifecycle routes may reuse it, but they must not fork per-org
- activation caches, alternate installation-token stores, or competing
- quickstart-owner identity. That same shared AI/runtime boundary now also
- owns Patrol quickstart execution identity: lifecycle-adjacent flows may
- trigger or observe Patrol runs through `internal/api/chat_service_adapter.go`,
- but they must preserve the stable execution identifier that lets the hosted
- quickstart contract bill once per higher-level Patrol run rather than once
- per internal provider turn.
+ The machine-scoped quickstart authority must stay canonical too:
+ tenant-local lifecycle routes may reuse shared installation activation or
+ effective entitlement billing state, but they must not fork per-org
+ activation caches, alternate installation-token stores, synthetic
+ entitlement mirrors, or competing quickstart-owner identity. That same
+ shared AI/runtime boundary now also owns Patrol quickstart execution
+ identity: lifecycle-adjacent flows may trigger or observe Patrol runs
+ through `internal/api/chat_service_adapter.go`, but they must preserve the
+ stable execution identifier that lets the hosted quickstart contract bill
+ once per higher-level Patrol run rather than once per internal provider
+ turn.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
Proxmox host-agent setup must treat local `proxmox-registered` markers as a cache, not authority: before skipping token setup or node repair, `internal/hostagent/proxmox_setup.go` must revalidate the current type and candidate hosts against Pulse through the canonical auto-register contract.
@@ -504,8 +509,10 @@ staying canonical before the first settings write. Hosted operators may land
in Chat, Patrol-backed setup hints, or AI-dependent remediation surfaces
before anyone has visited AI Settings, so the shared `internal/api/`
hosted-AI bootstrap helper must persist the machine-owned quickstart-backed
-`ai.enc` for entitled tenants instead of leaving lifecycle-adjacent hosted
-flows in a fake `AI disabled` state that disappears only after a manual save.
+`ai.enc` for entitled tenants by reusing the signed entitlement lease already
+present in billing state; it must not fabricate installation activation just
+to satisfy quickstart bootstrap. Otherwise lifecycle-adjacent hosted flows end
+up in a fake `AI disabled` state that disappears only after a manual save.
That same lifecycle-adjacent hosted entitlement path must also preserve the
trial quickstart grant fields already seeded into billing state. Hosted setup
and pairing may depend on the shared `internal/api/` entitlement refresh, but
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 90ba548cf3..3c35e31afb 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -132,15 +132,20 @@ than through a baked runtime fallback, so model churn does not leak into the
Pulse runtime or API contract.
That same Patrol quickstart boundary is now server-authoritative end to end.
`internal/ai/quickstart.go` must bootstrap before the first Patrol-only
-quickstart use, resolve installation identity from the installation-scoped
-`activation.enc` path even when Patrol runs under a tenant-local persistence
-directory, and refuse bootstrap entirely when no valid installation token is
-available. `quickstart.enc` may cache only the server-issued token snapshot
-and latest server-reported inventory through the shared
-`internal/config/persistence.go` and `internal/config/quickstart_state.go`
-helpers; it must not persist anonymous bootstrap identity or revive local
-counter truth. `internal/ai/providers/quickstart.go` must authenticate Patrol
-proxy calls with `Authorization: Bearer <quickstart_token>`, sync
+quickstart use, resolve the strongest server-verified runtime authority in
+this order, and refuse bootstrap entirely when neither exists: installation
+identity from installation-scoped `activation.enc` for activated self-hosted
+installs, then signed entitlement-lease identity from the effective
+entitlement-backed billing state for hosted or trial-backed runtimes. Tenant-
+local Patrol persistence must therefore reuse installation-scoped activation
+state where it exists and must fall back to the shared entitlement lease
+without inventing shadow activation files or anonymous client identity.
+`quickstart.enc` may cache only the server-issued token snapshot and latest
+server-reported inventory through the shared `internal/config/persistence.go`,
+`internal/config/entitlement_billing_state.go`, and
+`internal/config/quickstart_state.go` helpers; it must not persist anonymous
+bootstrap identity or revive local counter truth. `internal/ai/providers/quickstart.go`
+must authenticate Patrol proxy calls with `Authorization: Bearer <quickstart_token>`, sync
`credits_remaining` / `credits_total` back into that cache on every server
response, accept both `quickstart_token_expires_at` and the older
`token_expires_at` response field while mixed quickstart deployments exist,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 89dc08cb19..d29812bf46 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -177,6 +177,7 @@ Own canonical runtime payload shapes between backend and frontend.
19. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.
20. Keep hosted billing-state quickstart payload fields on the shared API contract: `internal/api/hosted_entitlement_refresh.go`, `internal/api/subscription_state_handlers.go`, and `internal/api/contract_test.go` must preserve `quickstart_credits_granted`, `quickstart_credits_used`, and `quickstart_credits_granted_at` through hosted signup, hosted lease refresh, and billing-state reads instead of letting lease rewrites silently erase seeded quickstart inventory.
21. Keep hosted AI settings bootstrap on the shared API contract: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as a canonical bootstrap condition, persist one machine-owned quickstart-backed AI config with the Pulse-owned alias `quickstart:pulse-hosted` when hosted entitlements grant AI capability, and preserve that configured settings payload as the same public contract that Chat, Patrol, and AI Settings consume instead of embedding a third-party model ID in the transport contract.
+ That same hosted bootstrap surface must also preserve the secure quickstart-identity contract: hosted or trial-backed AI settings reads and enablement may bootstrap Patrol quickstart from the effective signed entitlement lease when no self-hosted installation token exists, but they must not fabricate installation-scoped activation state or anonymous client identity to satisfy `/v1/quickstart/bootstrap`.
22. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface: `internal/api/ai_handler.go`, `internal/api/ai_handlers.go`, `internal/api/router_routes_ai_relay.go`, and `internal/api/contract_test.go` must turn the governed approvals-list API into the canonical empty-list payload as soon as settings-driven AI enablement succeeds, rather than leaving that surface on `503 Approval store not initialized` until some separate startup-only side effect happens.
23. Keep infrastructure summary chart transport contract-backed on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and frontend infrastructure summary consumers must normalize long-range mixed-cadence history into equal-time summary buckets before shipping the infrastructure charts API payload, so 7-day and 30-day summary cards do not expose compressed right-edge tails just because recent samples arrive at a finer storage resolution.
24. Keep long-range workload chart transport time-proportional on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload chart consumers must cap mixed-cadence workload history by equal-time buckets rather than raw point index for the per-workload and aggregate workload chart APIs, so 7-day and 30-day workload cards do not bunch recent samples at the right edge just because recent telemetry is stored more densely.
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 153921fda4..653f8abfa6 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -246,10 +246,13 @@ bootstrap. `pkg/licensing/license_server_client.go` and
`pkg/licensing/quickstart_bootstrap.go` must treat
`POST /v1/quickstart/bootstrap` as the canonical exchange for a server-issued
quickstart token plus the authoritative quickstart credit snapshot. The Pulse
-runtime must authenticate that bootstrap with the installation token from the
-installation-scoped activation state, whether the install is activated
-self-hosted or hosted/trial-backed, and there is no anonymous
-`client_installation_id` fallback in the v6 runtime contract. Local runtime
+runtime must authenticate that bootstrap with one of the server-verified
+commercial authorities owned by the shared commercial boundary: an
+installation token from installation-scoped activation state for activated
+self-hosted installs, or a signed hosted entitlement lease for entitlement-
+backed trial/cloud runtimes. There is no anonymous `client_installation_id`
+fallback in the v6 runtime contract, and hosted/trial quickstart must not fake
+self-hosted `activation.enc` just to satisfy the bootstrap path. Local runtime
cache files may memoize the returned token and counts but may not treat those
cached counts as commercial authority. The transport must also remain
mixed-version compatible while quickstart rolls out: Pulse may send optional
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 50a56d044f..467b12204a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -111,12 +111,17 @@ querying, and the operator-facing storage health presentation layer.
state exposed through shared AI handlers are transport facts owned by the
AI/runtime plus API-contract lanes, and storage/recovery surfaces must not
reintroduce local quickstart accounting, token lifecycle, anonymous
- bootstrap identity, or commercial identity rules.
+ bootstrap identity, fake activation records, or commercial identity rules.
That shared AI settings payload is also intentionally vendor-neutral:
storage/recovery-adjacent consumers may react to the stable
`quickstart:pulse-hosted` alias, but they must not treat vendor model IDs
or quickstart upstream-model defaults as part of storage/recovery transport
ownership or route behavior.
+ Self-hosted installation activation and hosted entitlement lease authority
+ for quickstart bootstrap remain owned by the shared AI/runtime boundary;
+ storage/recovery-adjacent helpers may consume the resulting state, but they
+ must not mint alternate installation surrogates or duplicate entitlement
+ verification logic.
That same adjacent `internal/api/` boundary also now carries Patrol-run
execution identity for hosted quickstart billing. Storage and recovery may
observe shared Patrol transport through `internal/api/chat_service_adapter.go`,
@@ -682,6 +687,10 @@ recovery-adjacent hosted tenants may share Patrol-backed investigation and
recovery context with the rest of the app, but the shared `internal/api/`
lease refresh must not clear quickstart inventory and leave adjacent product
surfaces inferring a fake "unavailable" runtime from rewritten billing state.
+That same canonical billing state is also the hosted quickstart authority, so
+recovery-adjacent code must not compensate for missing install activation by
+fabricating local activation state when the lease-backed runtime already has a
+server-verifiable principal.
That adjacent ledger read must also preserve canonical grouped system status,
including `warning`, so recovery- and storage-adjacent support views do not
flatten governed degraded state into a fake `unknown` label when the shared
@@ -1804,8 +1813,9 @@ backed investigation or AI-assisted recovery guidance before an operator has
ever opened AI Settings, so the shared hosted runtime helper must persist the
canonical quickstart-backed `ai.enc` from entitled billing state when no
explicit AI config exists. Adjacent recovery surfaces must not invent their
-own "AI disabled until configured" fallback when the hosted runtime already
-has enough entitlement proof to bootstrap the machine-owned default.
+own "AI disabled until configured" fallback or synthetic activation state when
+the hosted runtime already has enough entitlement proof to bootstrap the
+machine-owned default.
That same shared settings helper layer must then preserve canonical
org-management privilege for non-default tenant requests. Storage- and
recovery-adjacent hosted flows that reuse settings-bound helpers must allow
diff --git a/internal/ai/quickstart.go b/internal/ai/quickstart.go
index 0ea3dfafd2..0d607d2fa7 100644
--- a/internal/ai/quickstart.go
+++ b/internal/ai/quickstart.go
@@ -392,25 +392,91 @@ func (m *PersistentQuickstartCreditManager) secureBootstrapIdentityLocked() (str
return "", "", fmt.Errorf("quickstart: persistence unavailable")
}
+ if bearerToken, fingerprint, ok, err := m.installationBootstrapIdentityLocked(); err != nil {
+ return "", "", err
+ } else if ok {
+ return bearerToken, fingerprint, nil
+ }
+
+ return m.entitlementBootstrapIdentityLocked()
+}
+
+func (m *PersistentQuickstartCreditManager) installationBootstrapIdentityLocked() (string, string, bool, error) {
+ if m == nil || m.persistence == nil {
+ return "", "", false, fmt.Errorf("quickstart: persistence unavailable")
+ }
+
licensePersistence, err := pkglicensing.NewPersistence(m.persistence.SharedInstallationDataDir())
if err != nil {
- return "", "", fmt.Errorf("quickstart: load license persistence: %w", err)
+ return "", "", false, fmt.Errorf("quickstart: load license persistence: %w", err)
}
activationState, err := licensePersistence.LoadActivationState()
if err != nil {
- return "", "", fmt.Errorf("quickstart: load activation state: %w", err)
+ return "", "", false, fmt.Errorf("quickstart: load activation state: %w", err)
}
if activationState == nil {
- return "", "", quickstartActivationRequiredError()
+ return "", "", false, nil
}
installationToken := strings.TrimSpace(activationState.InstallationToken)
instanceFingerprint := strings.TrimSpace(activationState.InstanceFingerprint)
if installationToken == "" || instanceFingerprint == "" {
+ return "", "", false, nil
+ }
+
+ return installationToken, instanceFingerprint, true, nil
+}
+
+func (m *PersistentQuickstartCreditManager) entitlementBootstrapIdentityLocked() (string, string, error) {
+ if m == nil || m.persistence == nil {
+ return "", "", fmt.Errorf("quickstart: persistence unavailable")
+ }
+
+ state, _, err := config.LoadEffectiveEntitlementBillingState(m.persistence.SharedInstallationDataDir(), m.orgID)
+ if err != nil {
+ return "", "", fmt.Errorf("quickstart: load entitlement billing state: %w", err)
+ }
+
+ entitlementJWT := ""
+ if state != nil {
+ entitlementJWT = strings.TrimSpace(state.EntitlementJWT)
+ }
+ if entitlementJWT == "" {
return "", "", quickstartActivationRequiredError()
}
- return installationToken, instanceFingerprint, nil
+ publicKey, err := pkglicensing.TrialActivationPublicKey()
+ if err != nil {
+ return "", "", fmt.Errorf("quickstart: load entitlement verification key: %w", err)
+ }
+
+ claims, err := pkglicensing.VerifyEntitlementLeaseToken(entitlementJWT, publicKey, "", m.now())
+ if err != nil {
+ return "", "", fmt.Errorf("quickstart: verify entitlement lease: %w", err)
+ }
+ if !quickstartEntitlementSupportsPatrol(claims) {
+ return "", "", quickstartActivationRequiredError()
+ }
+
+ return entitlementJWT, "", nil
+}
+
+func quickstartEntitlementSupportsPatrol(claims *pkglicensing.EntitlementLeaseClaims) bool {
+ if claims == nil {
+ return false
+ }
+ switch claims.SubscriptionState {
+ case pkglicensing.SubStateActive, pkglicensing.SubStateGrace, pkglicensing.SubStateTrial:
+ default:
+ return false
+ }
+ for _, capability := range claims.Capabilities {
+ switch strings.TrimSpace(capability) {
+ case pkglicensing.FeatureAIPatrol, pkglicensing.FeatureAIAutoFix:
+ return true
+ }
+ }
+ return false
}
func quickstartBlockedReasonFromError(err error) string {
diff --git a/internal/ai/quickstart_test.go b/internal/ai/quickstart_test.go
index 73b57efb92..85f6ea8fe9 100644
--- a/internal/ai/quickstart_test.go
+++ b/internal/ai/quickstart_test.go
@@ -2,6 +2,8 @@ package ai
import (
"context"
+ "crypto/ed25519"
+ "encoding/base64"
"testing"
"time"
@@ -27,6 +29,37 @@ func (s *stubQuickstartBootstrapClient) BootstrapQuickstart(ctx context.Context,
return s.resp, nil
}
+func seedQuickstartEntitlementState(t *testing.T, persistence *config.ConfigPersistence, orgID, instanceHost string) string {
+ t.Helper()
+
+ pub, priv, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ t.Fatalf("GenerateKey(): %v", err)
+ }
+ t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))
+
+ entitlementJWT, err := pkglicensing.SignEntitlementLeaseToken(priv, pkglicensing.EntitlementLeaseClaims{
+ OrgID: orgID,
+ InstanceHost: instanceHost,
+ PlanVersion: "cloud_starter",
+ SubscriptionState: pkglicensing.SubStateTrial,
+ Capabilities: []string{pkglicensing.FeatureAIPatrol},
+ })
+ if err != nil {
+ t.Fatalf("SignEntitlementLeaseToken(): %v", err)
+ }
+
+ billingStore := config.NewFileBillingStore(persistence.SharedInstallationDataDir())
+ if err := billingStore.SaveBillingState(orgID, &pkglicensing.BillingState{
+ EntitlementJWT: entitlementJWT,
+ EntitlementRefreshToken: "etr_test_default",
+ }); err != nil {
+ t.Fatalf("SaveBillingState(): %v", err)
+ }
+
+ return entitlementJWT
+}
+
func TestPersistentQuickstartCreditManager_EnsureBootstrapUsesActivationIdentity(t *testing.T) {
dir := t.TempDir()
persistence := config.NewConfigPersistence(dir)
@@ -276,3 +309,47 @@ func TestPersistentQuickstartCreditManager_TenantUsesSharedInstallationActivatio
t.Fatalf("CreditsRemaining() = %d, want 14", mgr.CreditsRemaining())
}
}
+
+func TestPersistentQuickstartCreditManager_EnsureBootstrapUsesEntitlementIdentityWhenActivationMissing(t *testing.T) {
+ dir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(dir)
+
+ defaultPersistence, err := mtp.GetPersistence("default")
+ if err != nil {
+ t.Fatalf("GetPersistence(default): %v", err)
+ }
+ tenantPersistence, err := mtp.GetPersistence("t-tenant")
+ if err != nil {
+ t.Fatalf("GetPersistence(t-tenant): %v", err)
+ }
+
+ entitlementJWT := seedQuickstartEntitlementState(t, defaultPersistence, "default", "t-hosted.cloud.pulserelay.pro")
+ client := &stubQuickstartBootstrapClient{
+ resp: &pkglicensing.QuickstartBootstrapResponse{
+ QuickstartToken: "qst_live_entitlement",
+ QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
+ CreditsRemaining: 23,
+ CreditsTotal: 25,
+ },
+ }
+ mgr := NewPersistentQuickstartCreditManagerWithClient(tenantPersistence, "t-tenant", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
+
+ if err := mgr.EnsureBootstrap(context.Background()); err != nil {
+ t.Fatalf("EnsureBootstrap(): %v", err)
+ }
+ if client.calls != 1 {
+ t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)
+ }
+ if client.bearer != entitlementJWT {
+ t.Fatalf("bearer = %q, want entitlement lease JWT", client.bearer)
+ }
+ if client.req.InstanceFingerprint != "" {
+ t.Fatalf("InstanceFingerprint = %q, want empty for entitlement bootstrap", client.req.InstanceFingerprint)
+ }
+ if mgr.CreditsRemaining() != 23 {
+ t.Fatalf("CreditsRemaining() = %d, want 23", mgr.CreditsRemaining())
+ }
+ if mgr.GetProvider() == nil {
+ t.Fatal("expected quickstart provider after entitlement bootstrap")
+ }
+}
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index 5ed456aa49..f18c06af0f 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -240,9 +240,11 @@ func TestAISettingsResponse_UsesCanonicalEmptyCollections(t *testing.T) {
func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testing.T) {
t.Setenv("PULSE_HOSTED_MODE", "true")
useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {
- assert.Equal(t, "Bearer pit_live_test", strings.TrimSpace(r.Header.Get("Authorization")))
- instanceFingerprint, _ := reqBody["instance_fingerprint"].(string)
- assert.Equal(t, "fp-live-test", instanceFingerprint)
+ authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
+ assert.True(t, strings.HasPrefix(authHeader, "Bearer "))
+ assert.Len(t, strings.Split(strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer ")), "."), 3)
+ _, hasFingerprint := reqBody["instance_fingerprint"]
+ assert.False(t, hasFingerprint)
assert.Equal(t, "patrol", reqBody["use_case"])
})
@@ -252,7 +254,6 @@ func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testing
require.NoError(t, err)
seedHostedAIBillingState(t, mtp, "default")
- persistQuickstartActivationState(t, persistence)
handler := NewAISettingsHandler(mtp, nil, nil)
handler.defaultConfig = &config.Config{DataPath: tmp}
@@ -279,9 +280,11 @@ func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testing
func TestAISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingState(t *testing.T) {
t.Setenv("PULSE_HOSTED_MODE", "true")
useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {
- assert.Equal(t, "Bearer pit_live_test", strings.TrimSpace(r.Header.Get("Authorization")))
- instanceFingerprint, _ := reqBody["instance_fingerprint"].(string)
- assert.Equal(t, "fp-live-test", instanceFingerprint)
+ authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
+ assert.True(t, strings.HasPrefix(authHeader, "Bearer "))
+ assert.Len(t, strings.Split(strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer ")), "."), 3)
+ _, hasFingerprint := reqBody["instance_fingerprint"]
+ assert.False(t, hasFingerprint)
assert.Equal(t, "patrol", reqBody["use_case"])
})
@@ -289,11 +292,8 @@ func TestAISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingS
mtp := config.NewMultiTenantPersistence(tmp)
persistence, err := mtp.GetPersistence("t-tenant")
require.NoError(t, err)
- defaultPersistence, err := mtp.GetPersistence("default")
- require.NoError(t, err)
seedHostedAIBillingState(t, mtp, "default")
- persistQuickstartActivationState(t, defaultPersistence)
handler := NewAISettingsHandler(mtp, nil, nil)
handler.defaultConfig = &config.Config{DataPath: tmp}
diff --git a/internal/api/ai_hosted_runtime.go b/internal/api/ai_hosted_runtime.go
index 6098083c40..bc1d9dbfff 100644
--- a/internal/api/ai_hosted_runtime.go
+++ b/internal/api/ai_hosted_runtime.go
@@ -46,13 +46,7 @@ func shouldAutoBootstrapHostedAIConfig(hostedMode bool, persistence *config.Conf
}
func ensureHostedAIQuickstartBillingState(billingBaseDir, orgID string) (*billingState, error) {
- billingBaseDir = strings.TrimSpace(billingBaseDir)
- if billingBaseDir == "" {
- return nil, nil
- }
-
- billingStore := config.NewFileBillingStore(billingBaseDir)
- state, effectiveOrgID, err := loadHostedEffectiveBillingState(billingStore, orgID)
+ state, effectiveOrgID, err := config.LoadEffectiveEntitlementBillingState(billingBaseDir, orgID)
if err != nil || state == nil {
return state, err
}
@@ -61,6 +55,7 @@ func ensureHostedAIQuickstartBillingState(billingBaseDir, orgID string) (*billin
}
updated := normalizeBillingStateFromLicensing(state)
+ billingStore := config.NewFileBillingStore(strings.TrimSpace(billingBaseDir))
updated.GrantQuickstartCredits()
if err := billingStore.SaveBillingState(effectiveOrgID, updated); err != nil {
return nil, fmt.Errorf("save hosted Pulse Assistant quickstart billing state: %w", err)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 62aa6bf62d..b13b9f2d8d 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2125,6 +2125,21 @@ func TestContract_BillingStateQuickstartJSONSnapshot(t *testing.T) {
func TestContract_HostedAISettingsAutoBootstrapJSONSnapshot(t *testing.T) {
t.Setenv("PULSE_HOSTED_MODE", "true")
+ useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {
+ authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
+ if !strings.HasPrefix(authHeader, "Bearer ") {
+ t.Fatalf("expected Bearer auth, got %q", authHeader)
+ }
+ if parts := strings.Split(strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer ")), "."); len(parts) != 3 {
+ t.Fatalf("expected entitlement JWT bearer token, got %q", authHeader)
+ }
+ if _, hasFingerprint := reqBody["instance_fingerprint"]; hasFingerprint {
+ t.Fatalf("expected hosted quickstart bootstrap to omit instance_fingerprint, got %v", reqBody)
+ }
+ if got := reqBody["use_case"]; got != "patrol" {
+ t.Fatalf("use_case=%v want patrol", got)
+ }
+ })
baseDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(baseDir)
@@ -2154,7 +2169,7 @@ func TestContract_HostedAISettingsAutoBootstrapJSONSnapshot(t *testing.T) {
"model":"quickstart:pulse-hosted",
"chat_model":"quickstart:pulse-hosted",
"patrol_model":"quickstart:pulse-hosted",
- "configured":false,
+ "configured":true,
"custom_context":"",
"auth_method":"api_key",
"oauth_connected":false,
@@ -2179,12 +2194,11 @@ func TestContract_HostedAISettingsAutoBootstrapJSONSnapshot(t *testing.T) {
"control_level":"read_only",
"protected_guests":[],
"discovery_enabled":false,
- "quickstart_credits_total":0,
+ "quickstart_credits_total":25,
"quickstart_credits_used":0,
- "quickstart_credits_remaining":0,
- "quickstart_credits_available":false,
- "using_quickstart":false,
- "quickstart_blocked_reason":"Activate this install or start a trial to use AI Patrol quickstart. Otherwise connect your API key."
+ "quickstart_credits_remaining":25,
+ "quickstart_credits_available":true,
+ "using_quickstart":true
}`
assertJSONSnapshot(t, rec.Body.Bytes(), want)
@@ -2660,6 +2674,21 @@ func TestContract_ReportingInvalidFormatErrorsUseCatalogDefinitions(t *testing.T
func TestContract_HostedTenantAISettingsFallbackJSONSnapshot(t *testing.T) {
t.Setenv("PULSE_HOSTED_MODE", "true")
+ useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {
+ authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
+ if !strings.HasPrefix(authHeader, "Bearer ") {
+ t.Fatalf("expected Bearer auth, got %q", authHeader)
+ }
+ if parts := strings.Split(strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer ")), "."); len(parts) != 3 {
+ t.Fatalf("expected entitlement JWT bearer token, got %q", authHeader)
+ }
+ if _, hasFingerprint := reqBody["instance_fingerprint"]; hasFingerprint {
+ t.Fatalf("expected hosted quickstart bootstrap to omit instance_fingerprint, got %v", reqBody)
+ }
+ if got := reqBody["use_case"]; got != "patrol" {
+ t.Fatalf("use_case=%v want patrol", got)
+ }
+ })
baseDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(baseDir)
@@ -2690,7 +2719,7 @@ func TestContract_HostedTenantAISettingsFallbackJSONSnapshot(t *testing.T) {
"model":"quickstart:pulse-hosted",
"chat_model":"quickstart:pulse-hosted",
"patrol_model":"quickstart:pulse-hosted",
- "configured":false,
+ "configured":true,
"custom_context":"",
"auth_method":"api_key",
"oauth_connected":false,
@@ -2715,12 +2744,11 @@ func TestContract_HostedTenantAISettingsFallbackJSONSnapshot(t *testing.T) {
"control_level":"read_only",
"protected_guests":[],
"discovery_enabled":false,
- "quickstart_credits_total":0,
+ "quickstart_credits_total":25,
"quickstart_credits_used":0,
- "quickstart_credits_remaining":0,
- "quickstart_credits_available":false,
- "using_quickstart":false,
- "quickstart_blocked_reason":"Activate this install or start a trial to use AI Patrol quickstart. Otherwise connect your API key."
+ "quickstart_credits_remaining":25,
+ "quickstart_credits_available":true,
+ "using_quickstart":true
}`
assertJSONSnapshot(t, rec.Body.Bytes(), want)
diff --git a/internal/api/hosted_billing_state.go b/internal/api/hosted_billing_state.go
deleted file mode 100644
index e1bceb727e..0000000000
--- a/internal/api/hosted_billing_state.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package api
-
-import (
- "fmt"
- "strings"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
-)
-
-func loadHostedEffectiveBillingState(billingStore *config.FileBillingStore, orgID string) (*billingState, string, error) {
- if billingStore == nil {
- return nil, "", nil
- }
-
- effectiveOrgID := normalizeHostedEntitlementOrgID(orgID)
- state, err := billingStore.GetBillingState(effectiveOrgID)
- if err != nil {
- return nil, "", fmt.Errorf("load hosted billing state for org %q: %w", effectiveOrgID, err)
- }
- if effectiveOrgID == hostedRelayBootstrapOrgID || hostedBillingStateHasSubscription(state) {
- return state, effectiveOrgID, nil
- }
-
- defaultState, err := billingStore.GetBillingState(hostedRelayBootstrapOrgID)
- if err != nil {
- return nil, "", fmt.Errorf("load hosted default billing state fallback: %w", err)
- }
- if hostedBillingStateHasSubscription(defaultState) {
- return defaultState, hostedRelayBootstrapOrgID, nil
- }
- return state, effectiveOrgID, nil
-}
-
-func hostedBillingStateHasSubscription(state *billingState) bool {
- return state != nil && strings.TrimSpace(string(state.SubscriptionState)) != ""
-}
diff --git a/internal/config/entitlement_billing_state.go b/internal/config/entitlement_billing_state.go
new file mode 100644
index 0000000000..dc54d4d13e
--- /dev/null
+++ b/internal/config/entitlement_billing_state.go
@@ -0,0 +1,60 @@
+package config
+
+import (
+ "fmt"
+ "strings"
+
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
+)
+
+const entitlementBillingDefaultOrgID = "default"
+
+// NormalizeEntitlementBillingOrgID canonicalizes the org scope used for
+// entitlement-backed billing reads.
+func NormalizeEntitlementBillingOrgID(raw string) string {
+ orgID := strings.TrimSpace(raw)
+ if orgID == "" {
+ return entitlementBillingDefaultOrgID
+ }
+ return orgID
+}
+
+// LoadEffectiveEntitlementBillingState loads the effective billing state for an
+// entitlement-backed runtime. Multi-tenant hosted lanes can store the
+// canonical entitlement lease under the default org and inherit it from
+// org-scoped runtime directories.
+func LoadEffectiveEntitlementBillingState(baseDataDir, orgID string) (*pkglicensing.BillingState, string, error) {
+ baseDataDir = strings.TrimSpace(baseDataDir)
+ if baseDataDir == "" {
+ return nil, "", nil
+ }
+
+ billingStore := NewFileBillingStore(baseDataDir)
+ effectiveOrgID := NormalizeEntitlementBillingOrgID(orgID)
+ state, err := billingStore.GetBillingState(effectiveOrgID)
+ if err != nil {
+ return nil, "", fmt.Errorf("load billing state for org %q: %w", effectiveOrgID, err)
+ }
+ if effectiveOrgID == entitlementBillingDefaultOrgID || billingStateHasEntitlementAuthority(state) {
+ return state, effectiveOrgID, nil
+ }
+
+ defaultState, err := billingStore.GetBillingState(entitlementBillingDefaultOrgID)
+ if err != nil {
+ return nil, "", fmt.Errorf("load default entitlement billing state: %w", err)
+ }
+ if billingStateHasEntitlementAuthority(defaultState) {
+ return defaultState, entitlementBillingDefaultOrgID, nil
+ }
+
+ return state, effectiveOrgID, nil
+}
+
+func billingStateHasEntitlementAuthority(state *pkglicensing.BillingState) bool {
+ if state == nil {
+ return false
+ }
+ return strings.TrimSpace(string(state.SubscriptionState)) != "" ||
+ strings.TrimSpace(state.EntitlementJWT) != "" ||
+ strings.TrimSpace(state.EntitlementRefreshToken) != ""
+}
diff --git a/pkg/licensing/license_server_client.go b/pkg/licensing/license_server_client.go
index bd43af0813..bc4894995c 100644
--- a/pkg/licensing/license_server_client.go
+++ b/pkg/licensing/license_server_client.go
@@ -142,13 +142,14 @@ func (c *LicenseServerClient) RefreshGrant(ctx context.Context, installationID,
// BootstrapQuickstart exchanges a runtime identity for a short-lived
// quickstart token and the current authoritative quickstart inventory.
-// Callers must pass a server-verified installation token as bearerToken.
+// Callers must pass a server-verified quickstart authority token as
+// bearerToken: either an installation token or a signed entitlement lease JWT.
func (c *LicenseServerClient) BootstrapQuickstart(ctx context.Context, bearerToken string, req QuickstartBootstrapRequest) (*QuickstartBootstrapResponse, error) {
if strings.TrimSpace(bearerToken) == "" {
return nil, &LicenseServerError{
StatusCode: http.StatusUnauthorized,
Code: "activation_required",
- Message: "Quickstart bootstrap requires an installation token",
+ Message: "Quickstart bootstrap requires an activated or entitlement-backed runtime",
Retryable: false,
}
}
diff --git a/pkg/licensing/license_server_client_test.go b/pkg/licensing/license_server_client_test.go
index 659d4bda4b..eb08a78959 100644
--- a/pkg/licensing/license_server_client_test.go
+++ b/pkg/licensing/license_server_client_test.go
@@ -344,7 +344,7 @@ func TestClientRefreshGrant(t *testing.T) {
}
func TestClientBootstrapQuickstart(t *testing.T) {
- t.Run("uses installation bearer token when provided", func(t *testing.T) {
+ t.Run("uses provided quickstart bearer token", func(t *testing.T) {
var seenAuthorization string
var seenRequest QuickstartBootstrapRequest
diff --git a/pkg/licensing/quickstart_bootstrap.go b/pkg/licensing/quickstart_bootstrap.go
index 50d99d83bd..214d0ab76d 100644
--- a/pkg/licensing/quickstart_bootstrap.go
+++ b/pkg/licensing/quickstart_bootstrap.go
@@ -3,8 +3,9 @@ package licensing
// QuickstartBootstrapRequest is sent to the license server to exchange a
// runtime identity for a server-issued quickstart token.
//
-// Activated or hosted/trial-backed installs authenticate the request with
-// their installation token. The request body supplies only binding metadata.
+// Activated installs authenticate the request with their installation token.
+// Entitlement-backed runtimes authenticate the request with their signed
+// entitlement lease JWT. The request body supplies only binding metadata.
type QuickstartBootstrapRequest struct {
InstanceFingerprint string `json:"instance_fingerprint,omitempty"`
InstanceName string `json:"instance_name,omitempty"`