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.

Harden commercial callback and transport URL policy

rcourtman8a42bb432e0a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e72d6a4134..27c7f2dcb8 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -270,6 +270,9 @@ an add-only capacity posture.
lifecycle-adjacent surfaces may coexist with that shared browser route, but
they must not strand install or fleet flows on a raw Pulse Account error
tab, reinterpret `purchase=unavailable` as lifecycle repair state, or
+ bypass the shared secure callback policy that limits self-hosted commercial
+ return URLs to HTTPS instance origins or direct-loopback HTTP and keeps
+ hosted commercial follow-up fetches on the restricted outbound client.
bypass the owned billing retry/recovery path.
That same adjacent commercial/auth boundary also owns the canonical
self-hosted purchase intent label: lifecycle-adjacent setup and install
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 535335c26b..8784d3d3b5 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -880,7 +880,11 @@ that same `portal_handoff_id` into Pulse's activation callback, and Pulse
must compare both `portal_handoff_id` and `purchase_return_jti` against the
commercial checkout-session result before redeeming the activation key, so
browser form/query state and Stripe metadata alone never become the source of
-truth for a completed self-hosted upgrade. Once that commercial binding
+truth for a completed self-hosted upgrade. That same owned callback path must
+resolve only to HTTPS instance origins or a direct loopback HTTP origin, and
+the hosted trial/entitlement follow-up fetches behind that path must stay on
+the restricted outbound client instead of raw commercial HTTP calls. Once that
+commercial binding
verifies, Pulse's owned callback must persist a dedicated local
purchase-return redemption record keyed by `portal_handoff_id` plus
`purchase_return_jti`, use explicit local redemption state
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 197275d172..1c1d405ea8 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -170,6 +170,10 @@ Community limit enforcement.
7. Add or change Stripe provisioning plan resolution through `internal/cloudcp/stripe/provisioner.go`
8. Add or change activation/grant lifecycle, release build helper gating, or dev-mode capability widening through `pkg/licensing/dev_mode_features.go`, `pkg/licensing/service.go`, `pkg/licensing/testing_helpers.go`, `pkg/licensing/grant_refresh.go`, and `pkg/licensing/revocation_poll.go`
9. Add or change license-server transport through `pkg/licensing/license_server_client.go` and `pkg/licensing/quickstart_bootstrap.go`
+ That transport boundary must use HTTPS for non-loopback commercial endpoints,
+ may allow plaintext only on direct loopback development targets, and must
+ route outbound license-server fetches through the restricted HTTP client so
+ DNS rebinding or private-network drift cannot silently reopen the boundary.
10. Add or change encrypted activation persistence through `pkg/licensing/persistence.go` and `pkg/licensing/activation_store.go`
That persistence boundary must encrypt new state only with the persistent
random key file and the current HKDF-based derivation. Machine ID may
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 01820d98f2..4655139043 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -324,6 +324,9 @@ querying, and the operator-facing storage health presentation layer.
boundary also owns the canonical self-hosted purchase intent label:
storage- and recovery-adjacent surfaces may observe `self_hosted_plan`, but
they must not emit or reinterpret legacy `max_monitored_systems` intent or
+ bypass the shared secure callback policy that limits self-hosted commercial
+ return URLs to HTTPS instance origins or direct-loopback HTTP and keeps
+ hosted commercial follow-up fetches on the restricted outbound client.
query state as a recovery-local contract once uncapped self-hosted
monitoring is canonical.
That same adjacent commercial
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index b62522aec2..cfc278b0af 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2364,6 +2364,57 @@ func TestContract_TrialStartHostedSignupRedirectContract(t *testing.T) {
}
}
+func TestContract_TrialStartRejectsInsecureNonLoopbackCallbackURL(t *testing.T) {
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ h := NewLicenseHandlers(mtp, false, &config.Config{
+ ProTrialSignupURL: "https://billing.example.com/start-pro-trial?source=contract",
+ })
+
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "http://192.168.1.25:7655/api/license/trial/start",
+ nil,
+ ).WithContext(context.WithValue(context.Background(), OrgIDContextKey, "default"))
+ req.Host = "192.168.1.25:7655"
+ req.RemoteAddr = "192.168.1.50:54321"
+ rec := httptest.NewRecorder()
+ h.HandleStartTrial(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+
+ var payload APIError
+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ payload = payload.NormalizeCollections()
+ got, err := json.Marshal(struct {
+ StatusCode int `json:"status_code"`
+ Code string `json:"code"`
+ Error string `json:"error"`
+ Details map[string]string `json:"details"`
+ }{
+ StatusCode: payload.StatusCode,
+ Code: payload.Code,
+ Error: payload.ErrorMessage,
+ Details: payload.Details,
+ })
+ if err != nil {
+ t.Fatalf("marshal payload snapshot: %v", err)
+ }
+
+ const want = `{
+ "status_code":503,
+ "code":"trial_signup_unavailable",
+ "error":"Hosted trial signup is unavailable",
+ "details":{}
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_TrialStartRateLimitContract(t *testing.T) {
baseDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(baseDir)
@@ -6874,6 +6925,45 @@ func TestContract_SelfHostedPurchaseHandoffUnavailableJSONSnapshot(t *testing.T)
assertJSONSnapshot(t, got, want)
}
+func TestContract_SelfHostedPurchaseHandoffRejectsInsecureNonLoopbackCallbackURL(t *testing.T) {
+ handler := createTestHandler(t)
+
+ req := httptest.NewRequest(
+ http.MethodGet,
+ "http://192.168.1.25:7655"+licensePurchaseStartPath+"?feature=max_monitored_systems",
+ nil,
+ )
+ req.Host = "192.168.1.25:7655"
+ req.RemoteAddr = "192.168.1.50:54321"
+ rec := httptest.NewRecorder()
+
+ handler.HandleCheckoutStart(rec, req)
+
+ got, err := json.MarshalIndent(struct {
+ StatusCode int `json:"status_code"`
+ TitlePresent bool `json:"title_present"`
+ SecureFailureMessage bool `json:"secure_failure_message"`
+ OwnedRedirectPath bool `json:"owned_redirect_path"`
+ }{
+ StatusCode: rec.Code,
+ TitlePresent: strings.Contains(rec.Body.String(), "Pulse Account unavailable"),
+ SecureFailureMessage: strings.Contains(rec.Body.String(), "Pulse could not open Pulse Account from this instance right now"),
+ OwnedRedirectPath: strings.Contains(rec.Body.String(), "/settings/system/billing/plan?intent=self_hosted_plan&purchase=unavailable"),
+ }, "", "\t")
+ if err != nil {
+ t.Fatalf("marshal insecure handoff snapshot: %v", err)
+ }
+
+ const want = `{
+ "status_code": 503,
+ "title_present": true,
+ "secure_failure_message": true,
+ "owned_redirect_path": true
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_HandoffExchangeJSONSnapshot(t *testing.T) {
key := []byte("test-handoff-key")
configDir := t.TempDir()
diff --git a/internal/api/hosted_entitlement_refresh.go b/internal/api/hosted_entitlement_refresh.go
index f4b91d9f01..ebf21b581c 100644
--- a/internal/api/hosted_entitlement_refresh.go
+++ b/internal/api/hosted_entitlement_refresh.go
@@ -13,6 +13,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rs/zerolog/log"
)
@@ -435,7 +436,11 @@ func (h *LicenseHandlers) requestHostedEntitlementLeaseRefresh(orgID, instanceHo
}
req.Header.Set("Content-Type", "application/json")
- resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
+ client := securityutil.NewRestrictedOutboundHTTPClient(5*time.Second, securityutil.RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowLoopback: true,
+ })
+ resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("post hosted entitlement refresh request: %w", err)
}
diff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.go
index 4f7fa2f575..b82d30bf3a 100644
--- a/internal/api/license_handlers_test.go
+++ b/internal/api/license_handlers_test.go
@@ -838,6 +838,28 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tes
}
}
+func TestHandleCheckoutStart_FailsClosedOnInsecureNonLoopbackCallbackURL(t *testing.T) {
+ handler := createTestHandler(t)
+
+ req := httptest.NewRequest(
+ http.MethodGet,
+ "http://192.168.1.25:7655/auth/license-purchase-start?feature=relay",
+ nil,
+ )
+ req.Host = "192.168.1.25:7655"
+ req.RemoteAddr = "192.168.1.50:54321"
+ rec := httptest.NewRecorder()
+
+ handler.HandleCheckoutStart(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "Pulse could not open Pulse Account from this instance right now") {
+ t.Fatalf("body = %q, want secure callback failure message", rec.Body.String())
+ }
+}
+
func TestHandleCheckoutActivation_GETRendersAutoSubmitBridge(t *testing.T) {
handler := createTestHandler(t)
handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})
diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.go
index 68048d8c51..f7b317e9c8 100644
--- a/internal/api/licensing_handlers.go
+++ b/internal/api/licensing_handlers.go
@@ -20,6 +20,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/crypto"
"github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rs/zerolog/log"
)
@@ -219,16 +220,33 @@ func publicBaseURLForRequest(r *http.Request, cfg *config.Config) string {
return baseURL
}
-func trialCallbackURLForRequest(r *http.Request, cfg *config.Config) string {
+func securePublicCallbackBaseURLForRequest(r *http.Request, cfg *config.Config) string {
baseURL := publicBaseURLForRequest(r, cfg)
if baseURL == "" {
return ""
}
+
+ parsed, err := securityutil.NormalizePulseHTTPBaseURL(baseURL)
+ if err != nil {
+ return ""
+ }
+ if parsed.Scheme == "http" && (r == nil || !isDirectLoopbackRequest(r)) {
+ return ""
+ }
+
+ return strings.TrimRight(parsed.String(), "/")
+}
+
+func trialCallbackURLForRequest(r *http.Request, cfg *config.Config) string {
+ baseURL := securePublicCallbackBaseURLForRequest(r, cfg)
+ if baseURL == "" {
+ return ""
+ }
return baseURL + "/auth/trial-activate"
}
func licensePurchaseCallbackURLForRequest(r *http.Request, cfg *config.Config) string {
- baseURL := publicBaseURLForRequest(r, cfg)
+ baseURL := securePublicCallbackBaseURLForRequest(r, cfg)
if baseURL == "" {
return ""
}
@@ -242,6 +260,29 @@ func purchaseReturnExpectedHost(r *http.Request, cfg *config.Config) string {
return normalizeHostForTrial(publicBaseURLForRequest(r, nil))
}
+func parseHostedCommercialURL(raw string) (*url.URL, error) {
+ parsed, err := securityutil.NormalizeAbsoluteHTTPURL(strings.TrimSpace(raw))
+ if err != nil {
+ return nil, err
+ }
+
+ switch strings.ToLower(parsed.Scheme) {
+ case "https":
+ parsed.Scheme = "https"
+ case "http":
+ if !securityutil.IsLoopbackHost(parsed.Hostname()) {
+ return nil, fmt.Errorf("URL %q must use https unless host is loopback", raw)
+ }
+ parsed.Scheme = "http"
+ default:
+ return nil, fmt.Errorf("URL %q has unsupported scheme %q", raw, parsed.Scheme)
+ }
+
+ parsed.Host = strings.ToLower(parsed.Host)
+ parsed.Fragment = ""
+ return parsed, nil
+}
+
func trialSignupActionURLForRequest(cfg *config.Config, orgID, returnURL, instanceToken string) (string, error) {
signupBaseURL := ""
if cfg != nil {
@@ -252,7 +293,7 @@ func trialSignupActionURLForRequest(cfg *config.Config, orgID, returnURL, instan
return "", fmt.Errorf("trial signup URL is unavailable")
}
- parsed, err := url.Parse(signupURL)
+ parsed, err := parseHostedCommercialURL(signupURL)
if err != nil {
return "", fmt.Errorf("parse trial signup URL: %w", err)
}
@@ -348,7 +389,7 @@ func pulseAccountUpgradeURLForRequest(portalHandoffID string, query url.Values)
}
func publicAbsoluteURLForPath(r *http.Request, cfg *config.Config, path string) (string, error) {
- baseURL := publicBaseURLForRequest(r, cfg)
+ baseURL := securePublicCallbackBaseURLForRequest(r, cfg)
if baseURL == "" {
return "", fmt.Errorf("public base url is unavailable")
}
@@ -1242,7 +1283,10 @@ func (h *LicenseHandlers) acknowledgeHostedTrialRedemption(token string) (*hoste
return nil, fmt.Errorf("build trial redemption request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
- client := &http.Client{Timeout: 5 * time.Second}
+ client := securityutil.NewRestrictedOutboundHTTPClient(5*time.Second, securityutil.RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowLoopback: true,
+ })
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("post trial redemption acknowledgement: %w", err)
@@ -1273,7 +1317,7 @@ func trialSignupRedemptionURLFromConfig(cfg *config.Config) string {
if signupURL == "" {
return ""
}
- parsed, err := url.Parse(signupURL)
+ parsed, err := parseHostedCommercialURL(signupURL)
if err != nil || parsed == nil {
return ""
}
@@ -1291,7 +1335,7 @@ func hostedEntitlementRefreshURLFromConfig(cfg *config.Config) string {
if signupURL == "" {
return ""
}
- parsed, err := url.Parse(signupURL)
+ parsed, err := parseHostedCommercialURL(signupURL)
if err != nil || parsed == nil {
return ""
}
diff --git a/internal/api/trial_handlers_test.go b/internal/api/trial_handlers_test.go
index 3e975ca61e..e85033c4b1 100644
--- a/internal/api/trial_handlers_test.go
+++ b/internal/api/trial_handlers_test.go
@@ -186,6 +186,33 @@ func TestTrialStart_FailsClosedWithoutCallbackURL(t *testing.T) {
}
}
+func TestTrialStart_FailsClosedOnInsecureNonLoopbackCallbackURL(t *testing.T) {
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ h := NewLicenseHandlers(mtp, false, &config.Config{
+ ProTrialSignupURL: "https://billing.example.com/start-pro-trial",
+ })
+
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
+ req := httptest.NewRequest(http.MethodPost, "http://192.168.1.25:7655/api/license/trial/start", nil).WithContext(ctx)
+ req.Host = "192.168.1.25:7655"
+ req.RemoteAddr = "192.168.1.50:54321"
+ rec := httptest.NewRecorder()
+ h.HandleStartTrial(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+
+ var resp APIError
+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Code != "trial_signup_unavailable" {
+ t.Fatalf("code=%q, want %q", resp.Code, "trial_signup_unavailable")
+ }
+}
+
func TestTrialStart_RejectsAlreadyUsedTrial(t *testing.T) {
baseDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(baseDir)
diff --git a/internal/securityutil/httpurl.go b/internal/securityutil/httpurl.go
index 1f375bb103..eac8143fd1 100644
--- a/internal/securityutil/httpurl.go
+++ b/internal/securityutil/httpurl.go
@@ -17,6 +17,10 @@ func NormalizeHTTPBaseURL(raw string, defaultScheme string) (*url.URL, error) {
return pubsec.NormalizeHTTPBaseURL(raw, defaultScheme)
}
+func NormalizeSecureHTTPBaseURL(raw string) (*url.URL, error) {
+ return pubsec.NormalizeSecureHTTPBaseURL(raw)
+}
+
func IsLoopbackHost(host string) bool {
return pubsec.IsLoopbackHost(host)
}
diff --git a/internal/securityutil/httpurl_test.go b/internal/securityutil/httpurl_test.go
index debd2efaba..c9b6652593 100644
--- a/internal/securityutil/httpurl_test.go
+++ b/internal/securityutil/httpurl_test.go
@@ -103,6 +103,57 @@ func TestNormalizePulseHTTPBaseURL(t *testing.T) {
}
}
+func TestNormalizeSecureHTTPBaseURL(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want string
+ wantError string
+ }{
+ {
+ name: "normalizes secure url",
+ raw: "HTTPS://Billing.Example.com/api/",
+ want: "https://billing.example.com/api",
+ },
+ {
+ name: "allows loopback http",
+ raw: "http://LOCALHOST:8080/portal/",
+ want: "http://localhost:8080/portal",
+ },
+ {
+ name: "rejects private-network http",
+ raw: "http://10.0.0.5:8080/portal",
+ wantError: "must use https unless host is loopback",
+ },
+ {
+ name: "rejects unsupported scheme",
+ raw: "ftp://billing.example.com/portal",
+ wantError: "scheme must be http or https",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := NormalizeSecureHTTPBaseURL(tt.raw)
+ if tt.wantError != "" {
+ if err == nil {
+ t.Fatalf("NormalizeSecureHTTPBaseURL(%q) expected error", tt.raw)
+ }
+ if !strings.Contains(err.Error(), tt.wantError) {
+ t.Fatalf("NormalizeSecureHTTPBaseURL(%q) error = %q, want substring %q", tt.raw, err.Error(), tt.wantError)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("NormalizeSecureHTTPBaseURL(%q) error = %v", tt.raw, err)
+ }
+ if got.String() != tt.want {
+ t.Fatalf("NormalizeSecureHTTPBaseURL(%q) = %q, want %q", tt.raw, got.String(), tt.want)
+ }
+ })
+ }
+}
+
func TestNormalizePulseWebSocketBaseURL(t *testing.T) {
tests := []struct {
name string
diff --git a/pkg/licensing/license_server_client.go b/pkg/licensing/license_server_client.go
index 934fc9ddea..71b495407f 100644
--- a/pkg/licensing/license_server_client.go
+++ b/pkg/licensing/license_server_client.go
@@ -13,12 +13,15 @@ import (
"os"
"strings"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
)
// LicenseServerClient communicates with the Pulse license server for activation and grant refresh.
type LicenseServerClient struct {
baseURL string
httpClient *http.Client
+ initErr error
}
// CheckoutSessionResult is the canonical purchase-fulfillment response returned
@@ -67,18 +70,48 @@ func NewLicenseServerClient(baseURL string) *LicenseServerClient {
if baseURL == "" {
baseURL = DefaultLicenseServerURL
}
- baseURL = strings.TrimRight(baseURL, "/")
+
+ var initErr error
+ normalizedBaseURL, err := securityutil.NormalizeSecureHTTPBaseURL(baseURL)
+ if err != nil {
+ initErr = fmt.Errorf("license server URL %q is invalid: %w", baseURL, err)
+ baseURL = ""
+ } else {
+ baseURL = normalizedBaseURL.String()
+ }
return &LicenseServerClient{
baseURL: baseURL,
- httpClient: &http.Client{
- Timeout: 15 * time.Second,
- },
+ httpClient: securityutil.NewRestrictedOutboundHTTPClient(15*time.Second, securityutil.RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowLoopback: true,
+ }),
+ initErr: initErr,
+ }
+}
+
+func (c *LicenseServerClient) ready() error {
+ if c == nil {
+ return fmt.Errorf("license server client is nil")
+ }
+ if c.initErr != nil {
+ return c.initErr
+ }
+ if strings.TrimSpace(c.baseURL) == "" {
+ return fmt.Errorf("license server URL is unavailable")
}
+ if c.httpClient == nil {
+ return fmt.Errorf("license server HTTP client is unavailable")
+ }
+ return nil
}
// Activate calls the license server to create an installation and receive a relay grant.
func (c *LicenseServerClient) Activate(ctx context.Context, req ActivateInstallationRequest) (*ActivateInstallationResponse, error) {
+ if err := c.ready(); err != nil {
+ return nil, err
+ }
+
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal activate request: %w", err)
@@ -112,6 +145,10 @@ func (c *LicenseServerClient) Activate(ctx context.Context, req ActivateInstalla
// The response shape matches normal activation so the runtime can persist activation
// state and start using grant refresh immediately.
func (c *LicenseServerClient) ExchangeLegacyLicense(ctx context.Context, req ExchangeLegacyLicenseRequest) (*ActivateInstallationResponse, error) {
+ if err := c.ready(); err != nil {
+ return nil, err
+ }
+
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal exchange request: %w", err)
@@ -144,6 +181,10 @@ func (c *LicenseServerClient) ExchangeLegacyLicense(ctx context.Context, req Exc
// RefreshGrant calls the license server to refresh a relay grant.
// The installationToken is sent as a Bearer token in the Authorization header.
func (c *LicenseServerClient) RefreshGrant(ctx context.Context, installationID, installationToken string, req RefreshGrantRequest) (*RefreshGrantResponse, error) {
+ if err := c.ready(); err != nil {
+ return nil, err
+ }
+
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal refresh request: %w", err)
@@ -180,6 +221,10 @@ func (c *LicenseServerClient) RefreshGrant(ctx context.Context, installationID,
// GetCheckoutSessionResult resolves a commercial checkout session into its
// authoritative fulfillment payload.
func (c *LicenseServerClient) GetCheckoutSessionResult(ctx context.Context, sessionID string) (*CheckoutSessionResult, error) {
+ if err := c.ready(); err != nil {
+ return nil, err
+ }
+
sessionID = strings.TrimSpace(sessionID)
if sessionID == "" {
return nil, fmt.Errorf("checkout session id is required")
@@ -216,6 +261,10 @@ func (c *LicenseServerClient) GetCheckoutSessionResult(ctx context.Context, sess
// CreateCheckoutPortalHandoff stores a server-owned Pulse Account bootstrap
// record and returns an opaque portal_handoff_id for browser navigation.
func (c *LicenseServerClient) CreateCheckoutPortalHandoff(ctx context.Context, req CheckoutPortalHandoffRequest) (*CheckoutPortalHandoffResponse, error) {
+ if err := c.ready(); err != nil {
+ return nil, err
+ }
+
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal checkout portal handoff request: %w", err)
@@ -250,6 +299,10 @@ func (c *LicenseServerClient) CreateCheckoutPortalHandoff(ctx context.Context, r
// 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 err := c.ready(); err != nil {
+ return nil, err
+ }
+
if strings.TrimSpace(bearerToken) == "" {
return nil, &LicenseServerError{
StatusCode: http.StatusUnauthorized,
@@ -297,6 +350,10 @@ func (c *LicenseServerClient) BootstrapQuickstart(ctx context.Context, bearerTok
// FetchRevocations polls the revocation feed for events after the given sequence number.
// The feedToken authenticates access to the revocation feed.
func (c *LicenseServerClient) FetchRevocations(ctx context.Context, feedToken string, sinceSeq int64, limit int) (*RevocationFeedResponse, error) {
+ if err := c.ready(); err != nil {
+ return nil, err
+ }
+
if limit <= 0 {
limit = 500
}
diff --git a/pkg/licensing/license_server_client_test.go b/pkg/licensing/license_server_client_test.go
index 0429bb508f..74570902d7 100644
--- a/pkg/licensing/license_server_client_test.go
+++ b/pkg/licensing/license_server_client_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"time"
)
@@ -33,6 +34,17 @@ func TestNewLicenseServerClient(t *testing.T) {
t.Errorf("BaseURL = %q, want env override", c.BaseURL())
}
})
+
+ t.Run("rejects insecure non loopback url", func(t *testing.T) {
+ c := NewLicenseServerClient("http://192.168.1.25:8081")
+ if c.BaseURL() != "" {
+ t.Fatalf("BaseURL = %q, want empty when URL is rejected", c.BaseURL())
+ }
+ _, err := c.GetCheckoutSessionResult(context.Background(), "cs_test_123")
+ if err == nil || !strings.Contains(err.Error(), "must use https unless host is loopback") {
+ t.Fatalf("expected insecure URL error, got %v", err)
+ }
+ })
}
func TestClientActivate(t *testing.T) {
diff --git a/pkg/licensing/upgrade.go b/pkg/licensing/upgrade.go
index 2309ca4855..1ea1acf01a 100644
--- a/pkg/licensing/upgrade.go
+++ b/pkg/licensing/upgrade.go
@@ -1,8 +1,9 @@
package licensing
import (
- "net/url"
"strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
)
// DefaultUpgradeURL is used when no feature-specific URL mapping exists.
@@ -49,19 +50,24 @@ func validateExternalUpgradeURLOverride(raw string) (string, bool) {
return "", false
}
- parsed, err := url.Parse(raw)
+ parsed, err := securityutil.NormalizeAbsoluteHTTPURL(raw)
if err != nil {
return "", false
}
- if !parsed.IsAbs() || strings.TrimSpace(parsed.Host) == "" {
- return "", false
- }
switch strings.ToLower(parsed.Scheme) {
- case "http", "https":
- return parsed.String(), true
+ case "https":
+ parsed.Scheme = "https"
+ case "http":
+ if !securityutil.IsLoopbackHost(parsed.Hostname()) {
+ return "", false
+ }
+ parsed.Scheme = "http"
default:
return "", false
}
+ parsed.Host = strings.ToLower(parsed.Host)
+ parsed.Fragment = ""
+ return parsed.String(), true
}
// UpgradeURLForFeature returns the canonical upgrade URL for a capability key.
diff --git a/pkg/licensing/upgrade_test.go b/pkg/licensing/upgrade_test.go
index 7523201e9e..62bc9bcd06 100644
--- a/pkg/licensing/upgrade_test.go
+++ b/pkg/licensing/upgrade_test.go
@@ -16,11 +16,20 @@ func TestResolveProTrialSignupURL_UsesValidOverride(t *testing.T) {
}
}
+func TestResolveProTrialSignupURL_AllowsLoopbackHTTPOverride(t *testing.T) {
+ const override = "http://127.0.0.1:8080/start-pro-trial?src=test"
+
+ if got := ResolveProTrialSignupURL(override); got != override {
+ t.Fatalf("ResolveProTrialSignupURL() = %q, want %q", got, override)
+ }
+}
+
func TestResolveProTrialSignupURL_RejectsInvalidOverrides(t *testing.T) {
testCases := []string{
"relative/path",
"javascript:alert(1)",
"https://",
+ "http://192.168.1.20/start-pro-trial",
"ftp://example.com/start-pro-trial",
}
@@ -47,11 +56,20 @@ func TestResolvePulseAccountPortalURL_UsesValidOverride(t *testing.T) {
}
}
+func TestResolvePulseAccountPortalURL_AllowsLoopbackHTTPOverride(t *testing.T) {
+ const override = "http://localhost:8080/portal?src=test"
+
+ if got := ResolvePulseAccountPortalURL(override); got != override {
+ t.Fatalf("ResolvePulseAccountPortalURL() = %q, want %q", got, override)
+ }
+}
+
func TestResolvePulseAccountPortalURL_RejectsInvalidOverrides(t *testing.T) {
testCases := []string{
"relative/path",
"javascript:alert(1)",
"https://",
+ "http://10.0.0.25/portal",
"ftp://example.com/portal",
}
diff --git a/pkg/securityutil/httpurl.go b/pkg/securityutil/httpurl.go
index 7e34ea7ac7..ade9cc9ba8 100644
--- a/pkg/securityutil/httpurl.go
+++ b/pkg/securityutil/httpurl.go
@@ -120,6 +120,35 @@ func NormalizePulseHTTPBaseURL(raw string) (*url.URL, error) {
return normalizePulseBaseURL(raw, false)
}
+// NormalizeSecureHTTPBaseURL validates a general-purpose HTTP(S) base URL.
+// HTTPS is required for non-loopback hosts; loopback localhost may use HTTP.
+func NormalizeSecureHTTPBaseURL(raw string) (*url.URL, error) {
+ parsed, err := NormalizeHTTPBaseURL(raw, "")
+ if err != nil {
+ return nil, err
+ }
+
+ switch strings.ToLower(parsed.Scheme) {
+ case "https":
+ parsed.Scheme = "https"
+ case "http":
+ if !IsLoopbackHost(parsed.Hostname()) {
+ return nil, fmt.Errorf("URL %q must use https unless host is loopback", raw)
+ }
+ parsed.Scheme = "http"
+ default:
+ return nil, fmt.Errorf("URL %q has unsupported scheme %q", raw, parsed.Scheme)
+ }
+
+ parsed.Host = strings.ToLower(parsed.Host)
+ parsed.Path = strings.TrimRight(parsed.Path, "/")
+ parsed.RawPath = strings.TrimRight(parsed.RawPath, "/")
+ parsed.RawQuery = ""
+ parsed.Fragment = ""
+
+ return parsed, nil
+}
+
// NormalizePulseWebSocketBaseURL validates a Pulse command-channel base URL.
// Non-loopback hosts are normalized to WSS; loopback localhost may use WS.
func NormalizePulseWebSocketBaseURL(raw string) (*url.URL, error) {