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.

Add Pulse Cloud storage guardrails

rcourtman8fa98ad0a314
diff --git a/cmd/pulse-control-plane/main.go b/cmd/pulse-control-plane/main.go
index cbd76a22e1..25e0bcb27c 100644
--- a/cmd/pulse-control-plane/main.go
+++ b/cmd/pulse-control-plane/main.go
@@ -4,9 +4,11 @@ import (
"context"
"fmt"
"os"
+ "strings"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp"
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/spf13/cobra"
)
@@ -49,6 +51,38 @@ func newTenantRuntimeCmd() *cobra.Command {
return cmd
}
+func newCloudCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "cloud",
+ Short: "Audit Pulse Cloud operational readiness",
+ }
+ cmd.AddCommand(newCloudAuditCmd())
+ return cmd
+}
+
+func newCloudAuditCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "audit",
+ Short: "Report hosted tenant, container, proof-tenant, and storage guardrail state",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg, err := cloudcp.LoadConfig()
+ if err != nil {
+ return fmt.Errorf("load control plane config: %w", err)
+ }
+ report, err := cloudcp.AuditCloud(cmd.Context(), cfg)
+ if err != nil {
+ return err
+ }
+ printCloudAuditReport(report)
+ if !report.OK {
+ return fmt.Errorf("cloud audit failed: %s", strings.Join(report.Failures, "; "))
+ }
+ return nil
+ },
+ }
+ return cmd
+}
+
func newTenantRuntimeRolloutCmd() *cobra.Command {
var tenantID string
var image string
@@ -239,8 +273,90 @@ func printTenantRuntimeReconcilePlan(plan *cloudcp.TenantRuntimeContractReconcil
fmt.Printf("summary_rollout=%d\nsummary_noop=%d\nsummary_skip=%d\nsummary_total=%d\n", rolloutCount, noopCount, skipCount, len(plan.Tenants))
}
+func printCloudAuditReport(report *cloudcp.CloudAuditReport) {
+ if report == nil {
+ fmt.Println("audit_ok=false")
+ return
+ }
+ fmt.Printf("audit_ok=%t\n", report.OK)
+ fmt.Printf("tenant_total=%d\n", report.TenantTotal)
+ for _, state := range []registry.TenantState{
+ registry.TenantStateProvisioning,
+ registry.TenantStateActive,
+ registry.TenantStateSuspended,
+ registry.TenantStateCanceled,
+ registry.TenantStateDeleting,
+ registry.TenantStateDeleted,
+ registry.TenantStateFailed,
+ } {
+ fmt.Printf("tenant_%s=%d\n", state, report.TenantCounts[state])
+ }
+ fmt.Printf("tenant_registry_unhealthy_active=%d\n", report.RegistryUnhealthyActive)
+ fmt.Printf("docker_managed_total=%d\n", report.DockerManagedTotal)
+ fmt.Printf("docker_managed_running=%d\n", report.DockerManagedRunning)
+ fmt.Printf("docker_managed_unhealthy=%d\n", report.DockerManagedUnhealthy)
+ if report.DockerUnavailable != "" {
+ fmt.Printf("docker_unavailable=%s\n", report.DockerUnavailable)
+ }
+ if report.Storage != nil {
+ fmt.Printf("storage_guardrails_enabled=%t\n", report.Storage.Enabled)
+ fmt.Printf("storage_ok=%t\n", report.Storage.OK)
+ for _, fs := range report.Storage.Filesystems {
+ status := "ok"
+ if !fs.OK {
+ status = "fail"
+ }
+ fmt.Printf("storage_%s_status=%s\n", fs.Name, status)
+ fmt.Printf("storage_%s_path=%s\n", fs.Name, fs.Path)
+ fmt.Printf("storage_%s_available_bytes=%d\n", fs.Name, fs.AvailableBytes)
+ fmt.Printf("storage_%s_min_available_bytes=%d\n", fs.Name, fs.MinAvailableBytes)
+ fmt.Printf("storage_%s_total_bytes=%d\n", fs.Name, fs.TotalBytes)
+ if fs.Error != "" {
+ fmt.Printf("storage_%s_error=%s\n", fs.Name, fs.Error)
+ }
+ }
+ buildCacheStatus := "ok"
+ if !report.Storage.BuildCache.OK {
+ buildCacheStatus = "fail"
+ }
+ fmt.Printf("docker_build_cache_status=%s\n", buildCacheStatus)
+ fmt.Printf("docker_build_cache_total_bytes=%d\n", report.Storage.BuildCache.TotalBytes)
+ fmt.Printf("docker_build_cache_max_bytes=%d\n", report.Storage.BuildCache.MaxBytes)
+ fmt.Printf("docker_build_cache_reclaimable_bytes=%d\n", report.Storage.BuildCache.ReclaimableBytes)
+ if report.Storage.BuildCache.Error != "" {
+ fmt.Printf("docker_build_cache_error=%s\n", report.Storage.BuildCache.Error)
+ }
+ }
+ fmt.Printf("proof_tenant_stale_count=%d\n", len(report.StaleProofTenants))
+ for _, tenant := range report.StaleProofTenants {
+ fmt.Printf("proof_tenant_stale=%s state=%s account_id=%s email=%s age=%s\n",
+ tenant.TenantID,
+ tenant.State,
+ tenant.AccountID,
+ tenant.Email,
+ tenant.Age.Round(time.Second),
+ )
+ }
+ for _, container := range report.ManagedRuntimeContainers {
+ if container.State == "running" && (container.HealthStatus == "" || container.HealthStatus == "none" || container.HealthStatus == "healthy") {
+ continue
+ }
+ fmt.Printf("docker_unhealthy_container=%s name=%s state=%s health=%s status=%s\n",
+ container.ID,
+ container.Name,
+ container.State,
+ container.HealthStatus,
+ container.Status,
+ )
+ }
+ for _, failure := range report.Failures {
+ fmt.Printf("failure=%s\n", failure)
+ }
+}
+
func init() {
rootCmd.AddCommand(versionCmd)
+ rootCmd.AddCommand(newCloudCmd())
rootCmd.AddCommand(newTenantRuntimeCmd())
}
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 61434f9408..19a7842850 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -140,6 +140,11 @@ cloud-specific enforcement rules.
Hosted tenant container creation must also bound Docker `json-file` logs
through the control-plane Docker manager so tenant runtime logging cannot
fill the live Pulse Cloud host independently of tenant data quotas.
+ Hosted checkout and MSP workspace provisioning must also pass the
+ control-plane storage admission guard before tenant/account mutation: root
+ filesystem, tenant data, Docker runtime store, and Docker build-cache
+ thresholds are part of the Cloud paid readiness contract rather than an
+ operator-only cleanup script.
10. `internal/cloudcp/tenant_runtime_rollout.go` shared with `deployment-installability`: hosted tenant runtime rollout is both a Pulse Cloud runtime contract boundary and a deployment-installability release-rollout boundary.
Hosted tenant runtime reconciliation must treat a registered tenant with
preserved tenant data but no live Docker runtime as a recoverable managed
@@ -147,6 +152,8 @@ cloud-specific enforcement rules.
recreate the canonical tenant container, health-check it, and persist the
new runtime identity before hosted billing/auth surfaces are considered
coherent.
+ Tenant runtime rollout and missing-runtime restore must fail closed on the
+ same storage admission guard before snapshotting or swapping containers.
The real `pulse-pro` license-server legacy checkout issuance, recurring
renewals, manual issue, and legacy exchange flows are part of that same
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 7447ce06f2..7f1327cd37 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -665,6 +665,12 @@ across pretest, Playwright, and posttest. `scripts/hot-dev.sh` must honor that
lock by suppressing source-triggered rebuilds and manual `pulse` binary restart
churn while the owning proof process is still alive. Stale verify locks must
clear themselves automatically once the owning process exits.
+That deployment boundary also owns hosted storage admission: production
+control-plane deployments must mount host root and Docker runtime storage
+read-only for inspection, expose explicit root/data/Docker/build-cache
+thresholds, and provide `pulse-control-plane cloud audit` as the operator proof
+for tenant counts, unhealthy managed containers, disk pressure, and stale
+proof tenants before GA or rollout evidence is accepted.
That same verification contract also applies before Playwright attaches: if a
managed hot-dev session is already running when the verify lock is active, the
integration launcher must restart that session instead of silently attaching to
diff --git a/internal/cloudcp/cloud_audit.go b/internal/cloudcp/cloud_audit.go
new file mode 100644
index 0000000000..7b4a214366
--- /dev/null
+++ b/internal/cloudcp/cloud_audit.go
@@ -0,0 +1,204 @@
+package cloudcp
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ cpDocker "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/docker"
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
+)
+
+type ProofTenantAuditItem struct {
+ TenantID string
+ AccountID string
+ Email string
+ State registry.TenantState
+ CreatedAt time.Time
+ Age time.Duration
+}
+
+type CloudAuditReport struct {
+ OK bool
+ Failures []string
+ Storage *StorageGuardrailReport
+ TenantCounts map[registry.TenantState]int
+ TenantTotal int
+ RegistryUnhealthyActive int
+ DockerManagedTotal int
+ DockerManagedRunning int
+ DockerManagedUnhealthy int
+ DockerUnavailable string
+ StaleProofTenants []ProofTenantAuditItem
+ ManagedRuntimeContainers []cpDocker.RuntimeContainerSummary
+}
+
+func AuditCloud(ctx context.Context, cfg *CPConfig) (*CloudAuditReport, error) {
+ if cfg == nil {
+ return nil, fmt.Errorf("control plane config is required")
+ }
+ report := &CloudAuditReport{
+ OK: true,
+ TenantCounts: make(map[registry.TenantState]int),
+ }
+
+ reg, err := registry.NewTenantRegistry(cfg.ControlPlaneDir())
+ if err != nil {
+ return nil, fmt.Errorf("open tenant registry: %w", err)
+ }
+ defer reg.Close()
+
+ tenants, err := reg.List()
+ if err != nil {
+ return nil, fmt.Errorf("list tenants: %w", err)
+ }
+ report.TenantTotal = len(tenants)
+ for _, tenant := range tenants {
+ if tenant == nil {
+ continue
+ }
+ report.TenantCounts[tenant.State]++
+ if tenant.State == registry.TenantStateActive && !tenant.HealthCheckOK {
+ report.RegistryUnhealthyActive++
+ }
+ }
+ if report.RegistryUnhealthyActive > 0 {
+ report.addFailure(fmt.Sprintf("%d active tenants are unhealthy in the registry", report.RegistryUnhealthyActive))
+ }
+ report.StaleProofTenants = findStaleProofTenants(tenants, cfg.ProofTenantMatchers, cfg.ProofTenantMaxAge, time.Now().UTC())
+ if len(report.StaleProofTenants) > 0 {
+ report.addFailure(fmt.Sprintf("%d proof/canary tenants are older than %s", len(report.StaleProofTenants), cfg.ProofTenantMaxAge))
+ }
+
+ dockerMgr, err := cpDocker.NewManager(cpDocker.ManagerConfig{
+ Image: cfg.PulseImage,
+ Network: cfg.DockerNetwork,
+ BaseDomain: baseDomainFromURL(cfg.BaseURL),
+ TrialActivationPublicKey: cfg.TrialActivationPublicKey,
+ TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
+ MemoryLimit: cfg.TenantMemoryLimit,
+ CPUShares: cfg.TenantCPUShares,
+ TenantLogMaxSize: cfg.TenantLogMaxSize,
+ TenantLogMaxFile: cfg.TenantLogMaxFile,
+ })
+ if err != nil {
+ report.DockerUnavailable = err.Error()
+ report.addFailure("docker manager unavailable: " + err.Error())
+ } else {
+ defer dockerMgr.Close()
+ containers, listErr := dockerMgr.ListManagedRuntimeContainers(ctx)
+ if listErr != nil {
+ report.DockerUnavailable = listErr.Error()
+ report.addFailure("managed tenant container audit failed: " + listErr.Error())
+ } else {
+ report.ManagedRuntimeContainers = containers
+ report.DockerManagedTotal = len(containers)
+ for _, container := range containers {
+ if container.State == "running" {
+ report.DockerManagedRunning++
+ }
+ if runtimeContainerUnhealthy(container) {
+ report.DockerManagedUnhealthy++
+ }
+ }
+ if report.DockerManagedUnhealthy > 0 {
+ report.addFailure(fmt.Sprintf("%d managed tenant containers are not healthy", report.DockerManagedUnhealthy))
+ }
+ }
+ }
+
+ storage, err := CheckStorageGuardrails(ctx, cfg, dockerMgr)
+ if err != nil {
+ return nil, err
+ }
+ report.Storage = storage
+ if !storage.OK {
+ report.addFailure("storage guardrails failed: " + strings.Join(storage.Failures, "; "))
+ }
+ return report, nil
+}
+
+func (r *CloudAuditReport) addFailure(failure string) {
+ if r == nil {
+ return
+ }
+ failure = strings.TrimSpace(failure)
+ if failure == "" {
+ return
+ }
+ r.OK = false
+ r.Failures = append(r.Failures, failure)
+}
+
+func runtimeContainerUnhealthy(container cpDocker.RuntimeContainerSummary) bool {
+ if container.State != "running" {
+ return true
+ }
+ switch strings.ToLower(strings.TrimSpace(container.HealthStatus)) {
+ case "", "none", "healthy":
+ return false
+ default:
+ return true
+ }
+}
+
+func findStaleProofTenants(tenants []*registry.Tenant, matchers []string, maxAge time.Duration, now time.Time) []ProofTenantAuditItem {
+ if maxAge <= 0 {
+ return nil
+ }
+ cutoff := now.Add(-maxAge)
+ items := make([]ProofTenantAuditItem, 0)
+ for _, tenant := range tenants {
+ if tenant == nil || tenant.CreatedAt.IsZero() || tenant.CreatedAt.After(cutoff) {
+ continue
+ }
+ if !matchesProofTenant(tenant, matchers) {
+ continue
+ }
+ createdAt := tenant.CreatedAt.UTC()
+ items = append(items, ProofTenantAuditItem{
+ TenantID: strings.TrimSpace(tenant.ID),
+ AccountID: strings.TrimSpace(tenant.AccountID),
+ Email: strings.TrimSpace(tenant.Email),
+ State: tenant.State,
+ CreatedAt: createdAt,
+ Age: now.Sub(createdAt),
+ })
+ }
+ sort.Slice(items, func(i, j int) bool {
+ if items[i].CreatedAt.Equal(items[j].CreatedAt) {
+ return items[i].TenantID < items[j].TenantID
+ }
+ return items[i].CreatedAt.Before(items[j].CreatedAt)
+ })
+ return items
+}
+
+func matchesProofTenant(tenant *registry.Tenant, matchers []string) bool {
+ if tenant == nil {
+ return false
+ }
+ parts := []string{
+ tenant.ID,
+ tenant.AccountID,
+ tenant.Email,
+ tenant.DisplayName,
+ tenant.StripeCustomerID,
+ tenant.StripeSubscriptionID,
+ tenant.StripePriceID,
+ tenant.PlanVersion,
+ }
+ haystack := strings.ToLower(strings.Join(parts, " "))
+ for _, matcher := range matchers {
+ matcher = strings.ToLower(strings.TrimSpace(matcher))
+ if matcher == "" {
+ continue
+ }
+ if strings.Contains(haystack, matcher) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/cloudcp/config.go b/internal/cloudcp/config.go
index b8c359aa8d..2cafd075a5 100644
--- a/internal/cloudcp/config.go
+++ b/internal/cloudcp/config.go
@@ -9,6 +9,7 @@ import (
"path/filepath"
"strconv"
"strings"
+ "time"
"github.com/joho/godotenv"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
@@ -38,6 +39,16 @@ type CPConfig struct {
TenantLogMaxSize string
TenantLogMaxFile int
AllowDockerlessProvisioning bool
+ StorageGuardrailsEnabled bool
+ StorageRootPath string
+ StorageDataPath string
+ StorageDockerPath string
+ StorageMinRootAvailableBytes int64
+ StorageMinDataAvailableBytes int64
+ StorageMinDockerAvailableBytes int64
+ StorageMaxDockerBuildCacheBytes int64
+ ProofTenantMaxAge time.Duration
+ ProofTenantMatchers []string
StripeWebhookSecret string
StripeAPIKey string
PublicCloudSignupEnabled bool
@@ -69,6 +80,8 @@ func LoadConfig() (*CPConfig, error) {
// Best-effort .env loading (not required)
_ = godotenv.Load()
+ dataDir := envOrDefault("CP_DATA_DIR", "/data")
+ environment := normalizeCPEnvironment(envOrDefault("CP_ENV", "production"))
port, err := envOrDefaultInt("CP_PORT", 8443)
if err != nil {
return nil, err
@@ -109,10 +122,30 @@ func LoadConfig() (*CPConfig, error) {
if err != nil {
return nil, err
}
+ storageMinRootAvailable, err := envOrDefaultBytes("CP_STORAGE_MIN_ROOT_AVAILABLE", 10*1024*1024*1024)
+ if err != nil {
+ return nil, err
+ }
+ storageMinDataAvailable, err := envOrDefaultBytes("CP_STORAGE_MIN_DATA_AVAILABLE", 5*1024*1024*1024)
+ if err != nil {
+ return nil, err
+ }
+ storageMinDockerAvailable, err := envOrDefaultBytes("CP_STORAGE_MIN_DOCKER_AVAILABLE", 10*1024*1024*1024)
+ if err != nil {
+ return nil, err
+ }
+ storageMaxDockerBuildCache, err := envOrDefaultBytes("CP_STORAGE_MAX_DOCKER_BUILD_CACHE", 2*1024*1024*1024)
+ if err != nil {
+ return nil, err
+ }
+ proofTenantMaxAge, err := envOrDefaultDuration("CP_PROOF_TENANT_MAX_AGE", 24*time.Hour)
+ if err != nil {
+ return nil, err
+ }
cfg := &CPConfig{
- DataDir: envOrDefault("CP_DATA_DIR", "/data"),
- Environment: normalizeCPEnvironment(envOrDefault("CP_ENV", "production")),
+ DataDir: dataDir,
+ Environment: environment,
BindAddress: envOrDefault("CP_BIND_ADDRESS", "0.0.0.0"),
Port: port,
AdminKey: strings.TrimSpace(os.Getenv("CP_ADMIN_KEY")),
@@ -133,6 +166,16 @@ func LoadConfig() (*CPConfig, error) {
TenantLogMaxSize: envOrDefault("CP_TENANT_LOG_MAX_SIZE", "10m"),
TenantLogMaxFile: tenantLogMaxFile,
AllowDockerlessProvisioning: envOrDefaultBool("CP_ALLOW_DOCKERLESS_PROVISIONING", false),
+ StorageGuardrailsEnabled: envOrDefaultBool("CP_STORAGE_GUARDRAILS_ENABLED", environment != "development"),
+ StorageRootPath: envOrDefault("CP_STORAGE_ROOT_PATH", "/"),
+ StorageDataPath: envOrDefault("CP_STORAGE_DATA_PATH", dataDir),
+ StorageDockerPath: envOrDefault("CP_STORAGE_DOCKER_PATH", "/var/lib/docker"),
+ StorageMinRootAvailableBytes: storageMinRootAvailable,
+ StorageMinDataAvailableBytes: storageMinDataAvailable,
+ StorageMinDockerAvailableBytes: storageMinDockerAvailable,
+ StorageMaxDockerBuildCacheBytes: storageMaxDockerBuildCache,
+ ProofTenantMaxAge: proofTenantMaxAge,
+ ProofTenantMatchers: parseCSVEnv("CP_PROOF_TENANT_MATCHERS", "proof,canary,rehearsal"),
StripeWebhookSecret: strings.TrimSpace(os.Getenv("STRIPE_WEBHOOK_SECRET")),
StripeAPIKey: strings.TrimSpace(os.Getenv("STRIPE_API_KEY")),
PublicCloudSignupEnabled: envOrDefaultBool("CP_PUBLIC_CLOUD_SIGNUP_ENABLED", false),
@@ -226,6 +269,32 @@ func (c *CPConfig) validate() error {
if c.Environment == "production" && c.AllowDockerlessProvisioning {
return fmt.Errorf("CP_ALLOW_DOCKERLESS_PROVISIONING must be false in production")
}
+ if c.StorageGuardrailsEnabled {
+ if strings.TrimSpace(c.StorageRootPath) == "" {
+ return fmt.Errorf("CP_STORAGE_ROOT_PATH is required when CP_STORAGE_GUARDRAILS_ENABLED=true")
+ }
+ if strings.TrimSpace(c.StorageDataPath) == "" {
+ return fmt.Errorf("CP_STORAGE_DATA_PATH is required when CP_STORAGE_GUARDRAILS_ENABLED=true")
+ }
+ if strings.TrimSpace(c.StorageDockerPath) == "" {
+ return fmt.Errorf("CP_STORAGE_DOCKER_PATH is required when CP_STORAGE_GUARDRAILS_ENABLED=true")
+ }
+ if c.StorageMinRootAvailableBytes <= 0 {
+ return fmt.Errorf("CP_STORAGE_MIN_ROOT_AVAILABLE must be greater than 0")
+ }
+ if c.StorageMinDataAvailableBytes <= 0 {
+ return fmt.Errorf("CP_STORAGE_MIN_DATA_AVAILABLE must be greater than 0")
+ }
+ if c.StorageMinDockerAvailableBytes <= 0 {
+ return fmt.Errorf("CP_STORAGE_MIN_DOCKER_AVAILABLE must be greater than 0")
+ }
+ if c.StorageMaxDockerBuildCacheBytes <= 0 {
+ return fmt.Errorf("CP_STORAGE_MAX_DOCKER_BUILD_CACHE must be greater than 0")
+ }
+ }
+ if c.ProofTenantMaxAge <= 0 {
+ return fmt.Errorf("CP_PROOF_TENANT_MAX_AGE must be greater than 0")
+ }
if c.RequireEmailProvider {
if strings.TrimSpace(c.ResendAPIKey) == "" {
return fmt.Errorf("RESEND_API_KEY is required when CP_REQUIRE_EMAIL_PROVIDER=true")
@@ -347,6 +416,28 @@ func envOrDefaultInt64(key string, fallback int64) (int64, error) {
return fallback, nil
}
+func envOrDefaultBytes(key string, fallback int64) (int64, error) {
+ if v := strings.TrimSpace(os.Getenv(key)); v != "" {
+ n, err := parseByteSize(v)
+ if err != nil {
+ return fallback, fmt.Errorf("%s must be a valid byte size: %w", key, err)
+ }
+ return n, nil
+ }
+ return fallback, nil
+}
+
+func envOrDefaultDuration(key string, fallback time.Duration) (time.Duration, error) {
+ if v := strings.TrimSpace(os.Getenv(key)); v != "" {
+ duration, err := time.ParseDuration(v)
+ if err != nil {
+ return fallback, fmt.Errorf("%s must be a valid duration: %w", key, err)
+ }
+ return duration, nil
+ }
+ return fallback, nil
+}
+
func envOrDefaultBool(key string, fallback bool) bool {
v := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
switch v {
@@ -359,6 +450,73 @@ func envOrDefaultBool(key string, fallback bool) bool {
}
}
+func parseByteSize(raw string) (int64, error) {
+ value := strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(raw), " ", ""))
+ if value == "" {
+ return 0, fmt.Errorf("empty value")
+ }
+ if n, err := strconv.ParseInt(value, 10, 64); err == nil {
+ return n, nil
+ }
+
+ i := 0
+ for i < len(value) {
+ ch := value[i]
+ if (ch >= '0' && ch <= '9') || ch == '.' {
+ i++
+ continue
+ }
+ break
+ }
+ if i == 0 || i == len(value) {
+ return 0, fmt.Errorf("expected number followed by unit")
+ }
+ number, err := strconv.ParseFloat(value[:i], 64)
+ if err != nil {
+ return 0, fmt.Errorf("parse number: %w", err)
+ }
+ if number < 0 {
+ return 0, fmt.Errorf("must not be negative")
+ }
+ multiplier := int64(0)
+ switch value[i:] {
+ case "B":
+ multiplier = 1
+ case "K", "KB", "KIB":
+ multiplier = 1024
+ case "M", "MB", "MIB":
+ multiplier = 1024 * 1024
+ case "G", "GB", "GIB":
+ multiplier = 1024 * 1024 * 1024
+ case "T", "TB", "TIB":
+ multiplier = 1024 * 1024 * 1024 * 1024
+ default:
+ return 0, fmt.Errorf("unsupported unit %q", value[i:])
+ }
+ return int64(number * float64(multiplier)), nil
+}
+
+func parseCSVEnv(key, fallback string) []string {
+ raw := strings.TrimSpace(os.Getenv(key))
+ if raw == "" {
+ raw = fallback
+ }
+ values := make([]string, 0)
+ seen := make(map[string]struct{})
+ for _, entry := range strings.Split(raw, ",") {
+ entry = strings.ToLower(strings.TrimSpace(entry))
+ if entry == "" {
+ continue
+ }
+ if _, ok := seen[entry]; ok {
+ continue
+ }
+ seen[entry] = struct{}{}
+ values = append(values, entry)
+ }
+ return values
+}
+
func parseTrustedProxyCIDRValues(keys ...string) []string {
values := make([]string, 0)
seen := make(map[string]struct{})
diff --git a/internal/cloudcp/config_test.go b/internal/cloudcp/config_test.go
index 6096a871fc..56f9ecc164 100644
--- a/internal/cloudcp/config_test.go
+++ b/internal/cloudcp/config_test.go
@@ -73,6 +73,9 @@ func TestLoadConfig_AllRequired(t *testing.T) {
if cfg.TenantLogMaxFile != 3 {
t.Errorf("TenantLogMaxFile = %d, want 3", cfg.TenantLogMaxFile)
}
+ if cfg.StorageGuardrailsEnabled {
+ t.Errorf("StorageGuardrailsEnabled = true in development, want false")
+ }
}
func TestLoadConfig_CustomValues(t *testing.T) {
@@ -86,6 +89,16 @@ func TestLoadConfig_CustomValues(t *testing.T) {
t.Setenv("CP_BIND_ADDRESS", "127.0.0.1")
t.Setenv("CP_TENANT_LOG_MAX_SIZE", "25m")
t.Setenv("CP_TENANT_LOG_MAX_FILE", "4")
+ t.Setenv("CP_STORAGE_GUARDRAILS_ENABLED", "true")
+ t.Setenv("CP_STORAGE_ROOT_PATH", "/host-root")
+ t.Setenv("CP_STORAGE_DATA_PATH", "/tenant-data")
+ t.Setenv("CP_STORAGE_DOCKER_PATH", "/host-var-lib-docker")
+ t.Setenv("CP_STORAGE_MIN_ROOT_AVAILABLE", "12GiB")
+ t.Setenv("CP_STORAGE_MIN_DATA_AVAILABLE", "6GiB")
+ t.Setenv("CP_STORAGE_MIN_DOCKER_AVAILABLE", "8GiB")
+ t.Setenv("CP_STORAGE_MAX_DOCKER_BUILD_CACHE", "1500MiB")
+ t.Setenv("CP_PROOF_TENANT_MAX_AGE", "6h")
+ t.Setenv("CP_PROOF_TENANT_MATCHERS", "proof,canary,proof")
cfg, err := LoadConfig()
if err != nil {
@@ -106,6 +119,65 @@ func TestLoadConfig_CustomValues(t *testing.T) {
if cfg.TenantLogMaxFile != 4 {
t.Errorf("TenantLogMaxFile = %d, want 4", cfg.TenantLogMaxFile)
}
+ if !cfg.StorageGuardrailsEnabled {
+ t.Errorf("StorageGuardrailsEnabled = false, want true")
+ }
+ if cfg.StorageRootPath != "/host-root" || cfg.StorageDataPath != "/tenant-data" || cfg.StorageDockerPath != "/host-var-lib-docker" {
+ t.Fatalf("storage paths = %q %q %q", cfg.StorageRootPath, cfg.StorageDataPath, cfg.StorageDockerPath)
+ }
+ if cfg.StorageMinRootAvailableBytes != 12*1024*1024*1024 {
+ t.Fatalf("StorageMinRootAvailableBytes = %d", cfg.StorageMinRootAvailableBytes)
+ }
+ if cfg.StorageMinDataAvailableBytes != 6*1024*1024*1024 {
+ t.Fatalf("StorageMinDataAvailableBytes = %d", cfg.StorageMinDataAvailableBytes)
+ }
+ if cfg.StorageMinDockerAvailableBytes != 8*1024*1024*1024 {
+ t.Fatalf("StorageMinDockerAvailableBytes = %d", cfg.StorageMinDockerAvailableBytes)
+ }
+ if cfg.StorageMaxDockerBuildCacheBytes != 1500*1024*1024 {
+ t.Fatalf("StorageMaxDockerBuildCacheBytes = %d", cfg.StorageMaxDockerBuildCacheBytes)
+ }
+ if cfg.ProofTenantMaxAge.String() != "6h0m0s" {
+ t.Fatalf("ProofTenantMaxAge = %s, want 6h", cfg.ProofTenantMaxAge)
+ }
+ if got := strings.Join(cfg.ProofTenantMatchers, ","); got != "proof,canary" {
+ t.Fatalf("ProofTenantMatchers = %q, want proof,canary", got)
+ }
+}
+
+func TestLoadConfig_EnablesStorageGuardrailsByDefaultInProduction(t *testing.T) {
+ setRequiredCPEnv(t)
+ t.Setenv("CP_ENV", "production")
+
+ cfg, err := LoadConfig()
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ if !cfg.StorageGuardrailsEnabled {
+ t.Fatal("StorageGuardrailsEnabled = false, want true")
+ }
+ if cfg.StorageRootPath != "/" {
+ t.Fatalf("StorageRootPath = %q, want /", cfg.StorageRootPath)
+ }
+ if cfg.StorageDataPath != "/data" {
+ t.Fatalf("StorageDataPath = %q, want /data", cfg.StorageDataPath)
+ }
+ if cfg.StorageDockerPath != "/var/lib/docker" {
+ t.Fatalf("StorageDockerPath = %q, want /var/lib/docker", cfg.StorageDockerPath)
+ }
+}
+
+func TestLoadConfig_InvalidStorageByteSize(t *testing.T) {
+ setRequiredCPEnv(t)
+ t.Setenv("CP_STORAGE_MIN_ROOT_AVAILABLE", "not-a-size")
+
+ _, err := LoadConfig()
+ if err == nil {
+ t.Fatal("expected error for invalid storage byte size")
+ }
+ if !strings.Contains(err.Error(), "CP_STORAGE_MIN_ROOT_AVAILABLE must be a valid byte size") {
+ t.Fatalf("unexpected error: %v", err)
+ }
}
func TestLoadConfig_DerivesTrialActivationPublicKey(t *testing.T) {
diff --git a/internal/cloudcp/docker/manager.go b/internal/cloudcp/docker/manager.go
index fe31113ff0..34034dfc38 100644
--- a/internal/cloudcp/docker/manager.go
+++ b/internal/cloudcp/docker/manager.go
@@ -52,6 +52,31 @@ type RuntimeContainerInfo struct {
PublicURL string
}
+type DiskUsageClass struct {
+ ActiveCount int64
+ TotalCount int64
+ Reclaimable int64
+ TotalSize int64
+}
+
+type DiskUsageSnapshot struct {
+ Images DiskUsageClass
+ Containers DiskUsageClass
+ BuildCache DiskUsageClass
+ Volumes DiskUsageClass
+}
+
+type RuntimeContainerSummary struct {
+ ID string
+ Name string
+ Image string
+ ImageID string
+ State string
+ Status string
+ HealthStatus string
+ Created int64
+}
+
const immutableOwnershipPathsEnv = "PULSE_IMMUTABLE_OWNERSHIP_PATHS"
const (
@@ -90,6 +115,84 @@ func (m *Manager) DesiredRuntimeRouting(tenantID string) TenantRuntimeRoutingCon
return CanonicalTenantRuntimeRouting(tenantID, m.cfg.BaseDomain)
}
+func (m *Manager) DiskUsage(ctx context.Context) (*DiskUsageSnapshot, error) {
+ if err := m.ensureDaemonReachable(ctx); err != nil {
+ return nil, err
+ }
+ usage, err := m.cli.DiskUsage(ctx, client.DiskUsageOptions{
+ Containers: true,
+ Images: true,
+ BuildCache: true,
+ Volumes: true,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("read docker disk usage: %w", err)
+ }
+ return &DiskUsageSnapshot{
+ Images: DiskUsageClass{
+ ActiveCount: usage.Images.ActiveCount,
+ TotalCount: usage.Images.TotalCount,
+ Reclaimable: usage.Images.Reclaimable,
+ TotalSize: usage.Images.TotalSize,
+ },
+ Containers: DiskUsageClass{
+ ActiveCount: usage.Containers.ActiveCount,
+ TotalCount: usage.Containers.TotalCount,
+ Reclaimable: usage.Containers.Reclaimable,
+ TotalSize: usage.Containers.TotalSize,
+ },
+ BuildCache: DiskUsageClass{
+ ActiveCount: usage.BuildCache.ActiveCount,
+ TotalCount: usage.BuildCache.TotalCount,
+ Reclaimable: usage.BuildCache.Reclaimable,
+ TotalSize: usage.BuildCache.TotalSize,
+ },
+ Volumes: DiskUsageClass{
+ ActiveCount: usage.Volumes.ActiveCount,
+ TotalCount: usage.Volumes.TotalCount,
+ Reclaimable: usage.Volumes.Reclaimable,
+ TotalSize: usage.Volumes.TotalSize,
+ },
+ }, nil
+}
+
+func (m *Manager) ListManagedRuntimeContainers(ctx context.Context) ([]RuntimeContainerSummary, error) {
+ if err := m.ensureDaemonReachable(ctx); err != nil {
+ return nil, err
+ }
+ filters := client.Filters{}
+ filters = filters.Add("label", "pulse.managed=true")
+ result, err := m.cli.ContainerList(ctx, client.ContainerListOptions{
+ All: true,
+ Filters: filters,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("list managed tenant containers: %w", err)
+ }
+ containers := make([]RuntimeContainerSummary, 0, len(result.Items))
+ for _, item := range result.Items {
+ name := ""
+ if len(item.Names) > 0 {
+ name = strings.TrimPrefix(strings.TrimSpace(item.Names[0]), "/")
+ }
+ healthStatus := string(container.NoHealthcheck)
+ if item.Health != nil {
+ healthStatus = string(item.Health.Status)
+ }
+ containers = append(containers, RuntimeContainerSummary{
+ ID: item.ID,
+ Name: name,
+ Image: item.Image,
+ ImageID: item.ImageID,
+ State: string(item.State),
+ Status: item.Status,
+ HealthStatus: healthStatus,
+ Created: item.Created,
+ })
+ }
+ return containers, nil
+}
+
// IsNotFound reports whether Docker treated an identifier as missing.
func IsNotFound(err error) bool {
return errdefs.IsNotFound(err)
diff --git a/internal/cloudcp/server.go b/internal/cloudcp/server.go
index b8b1d42166..d731d94399 100644
--- a/internal/cloudcp/server.go
+++ b/internal/cloudcp/server.go
@@ -120,6 +120,9 @@ func Run(ctx context.Context, version string) error {
cfg.AllowDockerlessProvisioning,
cpstripe.WithHostedEntitlementService(hostedEntitlements),
cpstripe.WithTrialActivationPrivateKey(cfg.TrialActivationPrivateKey),
+ cpstripe.WithAdmissionCheck(func(checkCtx context.Context) error {
+ return EnforceStorageAdmission(checkCtx, cfg, dockerMgr)
+ }),
)
deps := &Deps{
Config: cfg,
diff --git a/internal/cloudcp/storage_admission.go b/internal/cloudcp/storage_admission.go
new file mode 100644
index 0000000000..aeed059432
--- /dev/null
+++ b/internal/cloudcp/storage_admission.go
@@ -0,0 +1,170 @@
+package cloudcp
+
+import (
+ "context"
+ "fmt"
+ "math"
+ "strings"
+
+ cpDocker "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/docker"
+ "golang.org/x/sys/unix"
+)
+
+type StorageDockerUsageProvider interface {
+ DiskUsage(ctx context.Context) (*cpDocker.DiskUsageSnapshot, error)
+}
+
+type StorageFilesystemReport struct {
+ Name string
+ Path string
+ AvailableBytes int64
+ TotalBytes int64
+ UsedBytes int64
+ MinAvailableBytes int64
+ OK bool
+ Error string
+}
+
+type StorageBuildCacheReport struct {
+ TotalBytes int64
+ ReclaimableBytes int64
+ ActiveCount int64
+ TotalCount int64
+ MaxBytes int64
+ OK bool
+ Error string
+}
+
+type StorageGuardrailReport struct {
+ Enabled bool
+ OK bool
+ Filesystems []StorageFilesystemReport
+ BuildCache StorageBuildCacheReport
+ Failures []string
+}
+
+func EnforceStorageAdmission(ctx context.Context, cfg *CPConfig, dockerUsage StorageDockerUsageProvider) error {
+ report, err := CheckStorageGuardrails(ctx, cfg, dockerUsage)
+ if err != nil {
+ return err
+ }
+ if report.OK {
+ return nil
+ }
+ return fmt.Errorf("storage admission failed: %s", strings.Join(report.Failures, "; "))
+}
+
+func CheckStorageGuardrails(ctx context.Context, cfg *CPConfig, dockerUsage StorageDockerUsageProvider) (*StorageGuardrailReport, error) {
+ if cfg == nil {
+ return nil, fmt.Errorf("control plane config is required")
+ }
+ report := &StorageGuardrailReport{
+ Enabled: cfg.StorageGuardrailsEnabled,
+ OK: true,
+ }
+ if !cfg.StorageGuardrailsEnabled {
+ return report, nil
+ }
+
+ for _, check := range []struct {
+ name string
+ path string
+ min int64
+ }{
+ {name: "root", path: cfg.StorageRootPath, min: cfg.StorageMinRootAvailableBytes},
+ {name: "data", path: cfg.StorageDataPath, min: cfg.StorageMinDataAvailableBytes},
+ {name: "docker", path: cfg.StorageDockerPath, min: cfg.StorageMinDockerAvailableBytes},
+ } {
+ fsReport := checkFilesystemStorage(check.name, check.path, check.min)
+ if !fsReport.OK {
+ report.OK = false
+ if fsReport.Error != "" {
+ report.Failures = append(report.Failures, fmt.Sprintf("%s path %s unavailable: %s", check.name, check.path, fsReport.Error))
+ } else {
+ report.Failures = append(report.Failures, fmt.Sprintf("%s path %s has %d bytes available, below %d byte threshold", check.name, check.path, fsReport.AvailableBytes, fsReport.MinAvailableBytes))
+ }
+ }
+ report.Filesystems = append(report.Filesystems, fsReport)
+ }
+
+ buildCache := StorageBuildCacheReport{
+ MaxBytes: cfg.StorageMaxDockerBuildCacheBytes,
+ OK: true,
+ }
+ if dockerUsage == nil {
+ buildCache.OK = false
+ buildCache.Error = "docker usage provider unavailable"
+ } else {
+ usage, err := dockerUsage.DiskUsage(ctx)
+ if err != nil {
+ buildCache.OK = false
+ buildCache.Error = err.Error()
+ } else if usage != nil {
+ buildCache.TotalBytes = usage.BuildCache.TotalSize
+ buildCache.ReclaimableBytes = usage.BuildCache.Reclaimable
+ buildCache.ActiveCount = usage.BuildCache.ActiveCount
+ buildCache.TotalCount = usage.BuildCache.TotalCount
+ if buildCache.TotalBytes > buildCache.MaxBytes {
+ buildCache.OK = false
+ }
+ }
+ }
+ if !buildCache.OK {
+ report.OK = false
+ if buildCache.Error != "" {
+ report.Failures = append(report.Failures, "docker build cache unavailable: "+buildCache.Error)
+ } else {
+ report.Failures = append(report.Failures, fmt.Sprintf("docker build cache is %d bytes, above %d byte threshold", buildCache.TotalBytes, buildCache.MaxBytes))
+ }
+ }
+ report.BuildCache = buildCache
+ return report, nil
+}
+
+func checkFilesystemStorage(name, path string, minAvailableBytes int64) StorageFilesystemReport {
+ report := StorageFilesystemReport{
+ Name: strings.TrimSpace(name),
+ Path: strings.TrimSpace(path),
+ MinAvailableBytes: minAvailableBytes,
+ OK: true,
+ }
+ if report.Path == "" {
+ report.OK = false
+ report.Error = "path is required"
+ return report
+ }
+ total, available, err := statFilesystemBytes(report.Path)
+ if err != nil {
+ report.OK = false
+ report.Error = err.Error()
+ return report
+ }
+ report.TotalBytes = total
+ report.AvailableBytes = available
+ if total >= available {
+ report.UsedBytes = total - available
+ }
+ if available < minAvailableBytes {
+ report.OK = false
+ }
+ return report
+}
+
+func statFilesystemBytes(path string) (totalBytes, availableBytes int64, err error) {
+ var stat unix.Statfs_t
+ if err := unix.Statfs(path, &stat); err != nil {
+ return 0, 0, err
+ }
+ if stat.Bsize <= 0 {
+ return 0, 0, fmt.Errorf("filesystem block size is zero")
+ }
+ blockSize := uint64(stat.Bsize)
+ return clampUint64ToInt64(uint64(stat.Blocks) * blockSize), clampUint64ToInt64(uint64(stat.Bavail) * blockSize), nil
+}
+
+func clampUint64ToInt64(value uint64) int64 {
+ if value > math.MaxInt64 {
+ return math.MaxInt64
+ }
+ return int64(value)
+}
diff --git a/internal/cloudcp/storage_admission_test.go b/internal/cloudcp/storage_admission_test.go
new file mode 100644
index 0000000000..ca2d4052db
--- /dev/null
+++ b/internal/cloudcp/storage_admission_test.go
@@ -0,0 +1,121 @@
+package cloudcp
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ cpDocker "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/docker"
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
+)
+
+type fakeStorageDockerUsage struct {
+ usage *cpDocker.DiskUsageSnapshot
+ err error
+}
+
+func (f fakeStorageDockerUsage) DiskUsage(context.Context) (*cpDocker.DiskUsageSnapshot, error) {
+ return f.usage, f.err
+}
+
+func TestCheckStorageGuardrailsPassesWithAvailableStorageAndBoundedBuildCache(t *testing.T) {
+ dir := t.TempDir()
+ cfg := &CPConfig{
+ StorageGuardrailsEnabled: true,
+ StorageRootPath: dir,
+ StorageDataPath: dir,
+ StorageDockerPath: dir,
+ StorageMinRootAvailableBytes: 1,
+ StorageMinDataAvailableBytes: 1,
+ StorageMinDockerAvailableBytes: 1,
+ StorageMaxDockerBuildCacheBytes: 1024,
+ }
+
+ report, err := CheckStorageGuardrails(context.Background(), cfg, fakeStorageDockerUsage{
+ usage: &cpDocker.DiskUsageSnapshot{
+ BuildCache: cpDocker.DiskUsageClass{TotalSize: 512, Reclaimable: 128},
+ },
+ })
+ if err != nil {
+ t.Fatalf("CheckStorageGuardrails: %v", err)
+ }
+ if !report.OK {
+ t.Fatalf("report.OK = false, failures = %v", report.Failures)
+ }
+}
+
+func TestCheckStorageGuardrailsFailsWhenFilesystemFallsBelowThreshold(t *testing.T) {
+ dir := t.TempDir()
+ cfg := &CPConfig{
+ StorageGuardrailsEnabled: true,
+ StorageRootPath: dir,
+ StorageDataPath: dir,
+ StorageDockerPath: dir,
+ StorageMinRootAvailableBytes: 1 << 60,
+ StorageMinDataAvailableBytes: 1,
+ StorageMinDockerAvailableBytes: 1,
+ StorageMaxDockerBuildCacheBytes: 1024,
+ }
+
+ report, err := CheckStorageGuardrails(context.Background(), cfg, fakeStorageDockerUsage{
+ usage: &cpDocker.DiskUsageSnapshot{},
+ })
+ if err != nil {
+ t.Fatalf("CheckStorageGuardrails: %v", err)
+ }
+ if report.OK {
+ t.Fatal("report.OK = true, want false")
+ }
+ if got := strings.Join(report.Failures, "; "); !strings.Contains(got, "root path") || !strings.Contains(got, "below") {
+ t.Fatalf("failures = %q, want root threshold failure", got)
+ }
+}
+
+func TestCheckStorageGuardrailsFailsWhenDockerBuildCacheExceedsThreshold(t *testing.T) {
+ dir := t.TempDir()
+ cfg := &CPConfig{
+ StorageGuardrailsEnabled: true,
+ StorageRootPath: dir,
+ StorageDataPath: dir,
+ StorageDockerPath: dir,
+ StorageMinRootAvailableBytes: 1,
+ StorageMinDataAvailableBytes: 1,
+ StorageMinDockerAvailableBytes: 1,
+ StorageMaxDockerBuildCacheBytes: 1024,
+ }
+
+ report, err := CheckStorageGuardrails(context.Background(), cfg, fakeStorageDockerUsage{
+ usage: &cpDocker.DiskUsageSnapshot{
+ BuildCache: cpDocker.DiskUsageClass{TotalSize: 2048, Reclaimable: 2048},
+ },
+ })
+ if err != nil {
+ t.Fatalf("CheckStorageGuardrails: %v", err)
+ }
+ if report.OK {
+ t.Fatal("report.OK = true, want false")
+ }
+ if got := strings.Join(report.Failures, "; "); !strings.Contains(got, "docker build cache") || !strings.Contains(got, "above") {
+ t.Fatalf("failures = %q, want build cache threshold failure", got)
+ }
+}
+
+func TestFindStaleProofTenantsUsesConfiguredMatchersAndAge(t *testing.T) {
+ now := time.Date(2026, 4, 24, 12, 0, 0, 0, time.UTC)
+ old := now.Add(-48 * time.Hour)
+ fresh := now.Add(-1 * time.Hour)
+ tenants := []*registry.Tenant{
+ {ID: "t-OLDPROOF", AccountID: "a_ga_canary_20260424", Email: "[email protected]", State: registry.TenantStateActive, CreatedAt: old},
+ {ID: "t-FRESH", AccountID: "a_ga_canary_20260424", Email: "[email protected]", State: registry.TenantStateActive, CreatedAt: fresh},
+ {ID: "t-CUSTOMER", AccountID: "a_customer", Email: "[email protected]", State: registry.TenantStateActive, CreatedAt: old},
+ }
+
+ stale := findStaleProofTenants(tenants, []string{"canary", "proof"}, 24*time.Hour, now)
+ if len(stale) != 1 {
+ t.Fatalf("len(stale) = %d, want 1 (%v)", len(stale), stale)
+ }
+ if stale[0].TenantID != "t-OLDPROOF" {
+ t.Fatalf("stale[0].TenantID = %q, want t-OLDPROOF", stale[0].TenantID)
+ }
+}
diff --git a/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go b/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go
index 1a4e94aa9d..64919c8784 100644
--- a/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go
+++ b/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go
@@ -3,8 +3,10 @@ package stripe
import (
"bytes"
"context"
+ "errors"
"net/http"
"net/http/httptest"
+ "os"
"path/filepath"
"strings"
"testing"
@@ -232,6 +234,47 @@ func TestCloudLifecycle_CheckoutToBillingToMonitoredSystemLimits(t *testing.T) {
}
}
+func TestCloudLifecycle_AdmissionFailureBlocksCheckoutBeforeTenantOrAccountMutation(t *testing.T) {
+ reg := newStripeTestRegistry(t)
+ tenantsDir := t.TempDir()
+ provisioner := newTestProvisioner(t, reg, tenantsDir, nil, true)
+ provisioner.admissionCheck = func(context.Context) error {
+ return errors.New("storage pressure")
+ }
+
+ err := provisioner.HandleCheckout(context.Background(), CheckoutSession{
+ Customer: "cus_storage_admission",
+ Subscription: "sub_storage_admission",
+ CustomerEmail: "[email protected]",
+ Metadata: map[string]string{"plan_version": "cloud_starter"},
+ })
+ if err == nil || !strings.Contains(err.Error(), "storage pressure") {
+ t.Fatalf("HandleCheckout error = %v, want storage pressure", err)
+ }
+
+ tenants, err := reg.List()
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ if len(tenants) != 0 {
+ t.Fatalf("tenant count = %d, want 0", len(tenants))
+ }
+ accounts, err := reg.ListAccounts()
+ if err != nil {
+ t.Fatalf("ListAccounts: %v", err)
+ }
+ if len(accounts) != 0 {
+ t.Fatalf("account count = %d, want 0", len(accounts))
+ }
+ entries, err := os.ReadDir(tenantsDir)
+ if err != nil {
+ t.Fatalf("ReadDir(%s): %v", tenantsDir, err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("tenant dir count = %d, want 0", len(entries))
+ }
+}
+
// TestCloudLifecycle_SubscriptionUpdateChangesLimits verifies that when a
// Cloud tenant upgrades (e.g., Starter → Power), the subscription.updated
// webhook correctly updates both the tenant record and billing state with
diff --git a/internal/cloudcp/stripe/provisioner.go b/internal/cloudcp/stripe/provisioner.go
index c4ab7489f7..45de71de92 100644
--- a/internal/cloudcp/stripe/provisioner.go
+++ b/internal/cloudcp/stripe/provisioner.go
@@ -39,10 +39,13 @@ type Provisioner struct {
trialActivationPrivateKey string
hostedEntitlements *entitlements.Service
chownFile func(string, int, int) error
+ admissionCheck AdmissionCheck
}
type ProvisionerOption func(*Provisioner)
+type AdmissionCheck func(context.Context) error
+
func WithTrialActivationPrivateKey(privateKey string) ProvisionerOption {
return func(p *Provisioner) {
if p == nil {
@@ -52,6 +55,15 @@ func WithTrialActivationPrivateKey(privateKey string) ProvisionerOption {
}
}
+func WithAdmissionCheck(check AdmissionCheck) ProvisionerOption {
+ return func(p *Provisioner) {
+ if p == nil {
+ return
+ }
+ p.admissionCheck = check
+ }
+}
+
func WithHostedEntitlementService(service *entitlements.Service) ProvisionerOption {
return func(p *Provisioner) {
if p == nil {
@@ -455,6 +467,16 @@ func dockerUnavailableError(err error) bool {
}
}
+func (p *Provisioner) enforceAdmission(ctx context.Context, operation string) error {
+ if p == nil || p.admissionCheck == nil {
+ return nil
+ }
+ if err := p.admissionCheck(ctx); err != nil {
+ return fmt.Errorf("%s admission denied: %w", operation, err)
+ }
+ return nil
+}
+
func (p *Provisioner) ensureAccountOwnerMembership(accountID, email string) error {
accountID = strings.TrimSpace(accountID)
email = strings.ToLower(strings.TrimSpace(email))
@@ -605,6 +627,9 @@ func (p *Provisioner) HandleCheckout(ctx context.Context, session CheckoutSessio
skippedExisting = true
return nil
}
+ if err := p.enforceAdmission(ctx, "hosted checkout provisioning"); err != nil {
+ return err
+ }
// Generate tenant ID
tenantID, err := registry.GenerateTenantID()
@@ -845,6 +870,9 @@ func (p *Provisioner) ProvisionWorkspaceForOwner(ctx context.Context, accountID,
if displayName == "" {
return nil, fmt.Errorf("missing display name")
}
+ if err := p.enforceAdmission(ctx, "hosted workspace provisioning"); err != nil {
+ return nil, err
+ }
tenantID, err := registry.GenerateTenantID()
if err != nil {
diff --git a/internal/cloudcp/stripe/provisioner_rollback_test.go b/internal/cloudcp/stripe/provisioner_rollback_test.go
index 2154cccce0..8773da8a4f 100644
--- a/internal/cloudcp/stripe/provisioner_rollback_test.go
+++ b/internal/cloudcp/stripe/provisioner_rollback_test.go
@@ -5,8 +5,10 @@ import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
+ "errors"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -152,6 +154,84 @@ func TestHandleCheckoutRollbackAllowsRetry(t *testing.T) {
}
}
+func TestHandleCheckoutAdmissionFailureHasNoProvisioningSideEffects(t *testing.T) {
+ reg := newStripeTestRegistry(t)
+ tenantsDir := t.TempDir()
+ p := newTestProvisioner(t, reg, tenantsDir, nil, true)
+ p.admissionCheck = func(context.Context) error {
+ return errors.New("storage pressure")
+ }
+
+ err := p.HandleCheckout(context.Background(), CheckoutSession{
+ Customer: "cus_admission_123",
+ Subscription: "sub_admission_123",
+ CustomerEmail: "[email protected]",
+ })
+ if err == nil || !strings.Contains(err.Error(), "storage pressure") {
+ t.Fatalf("HandleCheckout error = %v, want storage pressure", err)
+ }
+ tenants, listErr := reg.List()
+ if listErr != nil {
+ t.Fatalf("List: %v", listErr)
+ }
+ if len(tenants) != 0 {
+ t.Fatalf("tenant count = %d, want 0", len(tenants))
+ }
+ accounts, listAccountsErr := reg.ListAccounts()
+ if listAccountsErr != nil {
+ t.Fatalf("ListAccounts: %v", listAccountsErr)
+ }
+ if len(accounts) != 0 {
+ t.Fatalf("account count = %d, want 0", len(accounts))
+ }
+ entries, readErr := os.ReadDir(tenantsDir)
+ if readErr != nil {
+ t.Fatalf("ReadDir(%s): %v", tenantsDir, readErr)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("tenant dir count = %d, want 0", len(entries))
+ }
+}
+
+func TestProvisionWorkspaceAdmissionFailureHasNoProvisioningSideEffects(t *testing.T) {
+ reg := newStripeTestRegistry(t)
+ tenantsDir := t.TempDir()
+
+ accountID, err := registry.GenerateAccountID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.CreateAccount(&registry.Account{
+ ID: accountID,
+ Kind: registry.AccountKindMSP,
+ DisplayName: "Acme MSP",
+ }); err != nil {
+ t.Fatalf("CreateAccount: %v", err)
+ }
+
+ p := newTestProvisioner(t, reg, tenantsDir, nil, true)
+ p.admissionCheck = func(context.Context) error {
+ return errors.New("storage pressure")
+ }
+ if _, err := p.ProvisionWorkspace(context.Background(), accountID, "Tenant One"); err == nil || !strings.Contains(err.Error(), "storage pressure") {
+ t.Fatalf("ProvisionWorkspace error = %v, want storage pressure", err)
+ }
+ tenants, listErr := reg.ListByAccountID(accountID)
+ if listErr != nil {
+ t.Fatalf("ListByAccountID: %v", listErr)
+ }
+ if len(tenants) != 0 {
+ t.Fatalf("tenant count = %d, want 0", len(tenants))
+ }
+ entries, readErr := os.ReadDir(tenantsDir)
+ if readErr != nil {
+ t.Fatalf("ReadDir(%s): %v", tenantsDir, readErr)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("tenant dir count = %d, want 0", len(entries))
+ }
+}
+
func TestProvisionWorkspaceSetsHostedRuntimeOwnershipForImmutableFiles(t *testing.T) {
reg := newStripeTestRegistry(t)
tenantsDir := t.TempDir()
diff --git a/internal/cloudcp/tenant_runtime_rollout.go b/internal/cloudcp/tenant_runtime_rollout.go
index 2f2605cbfa..ab3957f1c4 100644
--- a/internal/cloudcp/tenant_runtime_rollout.go
+++ b/internal/cloudcp/tenant_runtime_rollout.go
@@ -96,15 +96,16 @@ type tenantRuntimeRolloutSynchronizer interface {
}
type tenantRuntimeRolloutService struct {
- registry tenantRuntimeRolloutRegistry
- docker tenantRuntimeRolloutDocker
- tenantsDir string
- defaultImage string
- synchronizer tenantRuntimeRolloutSynchronizer
- now func() time.Time
- sleep func(time.Duration)
- healthTimeout time.Duration
- healthPoll time.Duration
+ registry tenantRuntimeRolloutRegistry
+ docker tenantRuntimeRolloutDocker
+ tenantsDir string
+ defaultImage string
+ synchronizer tenantRuntimeRolloutSynchronizer
+ admissionCheck func(context.Context) error
+ now func() time.Time
+ sleep func(time.Duration)
+ healthTimeout time.Duration
+ healthPoll time.Duration
}
var errTenantRuntimeMissing = errors.New("tenant runtime container missing")
@@ -173,6 +174,8 @@ func newTenantRuntimeRolloutServiceFromConfig(
TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
MemoryLimit: cfg.TenantMemoryLimit,
CPUShares: cfg.TenantCPUShares,
+ TenantLogMaxSize: cfg.TenantLogMaxSize,
+ TenantLogMaxFile: cfg.TenantLogMaxFile,
})
if err != nil {
_ = reg.Close()
@@ -184,11 +187,14 @@ func newTenantRuntimeRolloutServiceFromConfig(
_ = reg.Close()
}
service := &tenantRuntimeRolloutService{
- registry: reg,
- docker: dockerMgr,
- tenantsDir: cfg.TenantsDir(),
- defaultImage: strings.TrimSpace(image),
- synchronizer: filesystemTenantRuntimeSynchronizer{},
+ registry: reg,
+ docker: dockerMgr,
+ tenantsDir: cfg.TenantsDir(),
+ defaultImage: strings.TrimSpace(image),
+ synchronizer: filesystemTenantRuntimeSynchronizer{},
+ admissionCheck: func(checkCtx context.Context) error {
+ return EnforceStorageAdmission(checkCtx, cfg, dockerMgr)
+ },
now: func() time.Time { return time.Now().UTC() },
sleep: time.Sleep,
healthTimeout: defaultTenantRuntimeRolloutHealthTimeout,
@@ -282,6 +288,9 @@ func (s *tenantRuntimeRolloutService) Rollout(ctx context.Context, opts TenantRu
}
tenantDataDir := filepath.Join(s.tenantsDir, tenantID)
+ if err := s.enforceAdmission(ctx, "tenant runtime rollout"); err != nil {
+ return nil, err
+ }
snapshotRoot := strings.TrimSpace(opts.SnapshotRoot)
if snapshotRoot == "" {
snapshotRoot = filepath.Join(filepath.Dir(s.tenantsDir), "backups", "rollout")
@@ -396,6 +405,9 @@ func (s *tenantRuntimeRolloutService) recreateMissingRuntime(
}
tenantDataDir := filepath.Join(s.tenantsDir, tenantID)
+ if err := s.enforceAdmission(ctx, "tenant runtime restore"); err != nil {
+ return nil, err
+ }
newContainerID, err := s.docker.CreateAndStart(ctx, tenantID, tenantDataDir)
if err != nil {
return nil, fmt.Errorf("recreate missing tenant runtime for %s using image %s: %w", tenantID, image, err)
@@ -433,6 +445,16 @@ func (s *tenantRuntimeRolloutService) recreateMissingRuntime(
}, nil
}
+func (s *tenantRuntimeRolloutService) enforceAdmission(ctx context.Context, operation string) error {
+ if s == nil || s.admissionCheck == nil {
+ return nil
+ }
+ if err := s.admissionCheck(ctx); err != nil {
+ return fmt.Errorf("%s admission denied: %w", operation, err)
+ }
+ return nil
+}
+
func tenantRuntimeMatchesContract(
live *cpDocker.RuntimeContainerInfo,
canonicalName string,
diff --git a/internal/cloudcp/tenant_runtime_rollout_test.go b/internal/cloudcp/tenant_runtime_rollout_test.go
index a7ccfdf256..6915f275d1 100644
--- a/internal/cloudcp/tenant_runtime_rollout_test.go
+++ b/internal/cloudcp/tenant_runtime_rollout_test.go
@@ -2,9 +2,11 @@ package cloudcp
import (
"context"
+ "errors"
"fmt"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -367,6 +369,62 @@ func TestTenantRuntimeRollout_RecreatesMissingRuntimeFromTenantData(t *testing.T
}
}
+func TestTenantRuntimeRollout_AdmissionFailureStopsBeforeSnapshotOrContainerSwap(t *testing.T) {
+ tenant := &registry.Tenant{ID: "t-ADMIT01", ContainerID: "old-container"}
+ reg := &fakeTenantRuntimeRolloutRegistry{tenant: tenant}
+ docker := newFakeTenantRuntimeRolloutDocker()
+ routing := docker.DesiredRuntimeRouting(tenant.ID)
+ docker.addContainer(&cpDocker.RuntimeContainerInfo{
+ ID: "old-container",
+ Name: tenantRuntimeContainerName(tenant.ID),
+ ImageRef: "pulse-runtime:old",
+ ImageID: "sha256:old",
+ Running: true,
+ RouteHost: routing.Host,
+ PublicURL: routing.PublicURL,
+ })
+ sync := &fakeTenantRuntimeRolloutSynchronizer{}
+ service := newTestTenantRuntimeRolloutService(reg, docker, sync, newFakeTenantRuntimeRolloutClock())
+ service.admissionCheck = func(context.Context) error {
+ return errors.New("storage pressure")
+ }
+
+ _, err := service.Rollout(context.Background(), TenantRuntimeRolloutOptions{
+ TenantID: tenant.ID,
+ Image: "pulse-runtime:new",
+ })
+ if err == nil || !strings.Contains(err.Error(), "storage pressure") {
+ t.Fatalf("Rollout error = %v, want storage pressure", err)
+ }
+ if len(sync.snapshots) != 0 {
+ t.Fatalf("snapshot count = %d, want 0", len(sync.snapshots))
+ }
+ if len(docker.stopCalls) != 0 || len(docker.renameCalls) != 0 || len(docker.createCalls) != 0 {
+ t.Fatalf("docker mutated before admission failure: stops=%v renames=%v creates=%v", docker.stopCalls, docker.renameCalls, docker.createCalls)
+ }
+}
+
+func TestTenantRuntimeRollout_AdmissionFailureStopsMissingRuntimeRestore(t *testing.T) {
+ tenant := &registry.Tenant{ID: "t-ADMIT02", ContainerID: "removed-container"}
+ reg := &fakeTenantRuntimeRolloutRegistry{tenant: tenant}
+ docker := newFakeTenantRuntimeRolloutDocker()
+ service := newTestTenantRuntimeRolloutService(reg, docker, &fakeTenantRuntimeRolloutSynchronizer{}, newFakeTenantRuntimeRolloutClock())
+ service.admissionCheck = func(context.Context) error {
+ return errors.New("storage pressure")
+ }
+
+ _, err := service.Rollout(context.Background(), TenantRuntimeRolloutOptions{
+ TenantID: tenant.ID,
+ Image: "pulse-runtime:stable",
+ })
+ if err == nil || !strings.Contains(err.Error(), "storage pressure") {
+ t.Fatalf("Rollout error = %v, want storage pressure", err)
+ }
+ if len(docker.createCalls) != 0 {
+ t.Fatalf("create call count = %d, want 0", len(docker.createCalls))
+ }
+}
+
func TestTenantRuntimeContractReconcilePlan_AllTenantsClassifiesNoopRolloutAndSkip(t *testing.T) {
tenantNoop := &registry.Tenant{ID: "t-NOOP12345", ContainerID: "noop-live"}
tenantDrift := &registry.Tenant{ID: "t-Drift1234", ContainerID: "drift-live"}