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.

fix(security): bound provider MSP restore writes

rcourtmanaae8aef4ab04
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 7880105171..c510594297 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -416,6 +416,12 @@ avoids a cloud-control-plane report data path across clients.
output, restore must recover that license as an explicit operator artifact,
and the archive must stay Stripe-free so provider-hosted MSP recovery does
not inherit Pulse-hosted SaaS billing assumptions.
+ Restore is the point where an untrusted archive becomes provider state, so
+ it must stay bounded and all-or-nothing. Extraction must cap what it writes
+ per entry and across the whole restore, measured on the bytes actually
+ copied rather than the size the archive declares for itself, and a restore
+ that fails partway must clear the license, control-plane, and tenant state
+ it wrote instead of leaving a partial provider identity behind.
14. `internal/cloudcp/provider_msp_recovery.go` shared with `deployment-installability`: provider-hosted MSP failed-workspace recovery is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.
Provider-hosted MSP recovery must require the signed provider MSP license
source by default, preserve the client workspace boundary, refuse to start
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 18d7345c21..d3b7e5bc11 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -285,6 +285,19 @@ upgrade, update, release, or artifact-selection behavior.
snapshot, license artifact, and tenant runtime directories, and fail closed
on restore when target provider MSP state already exists unless the operator
explicitly uses the replace gate after stopping the control plane.
+ Restore must also fail closed on the size of what it writes. Archive entries
+ are attacker-influenced, so the size a tar header declares is a hint used
+ only for an early reject, never the bound: extraction must enforce a
+ per-entry cap and a cumulative whole-restore cap against the bytes actually
+ copied, so a decompression bomb, a sparse entry declaring a huge logical
+ size, or a corrupt stream cannot fill the target volume. An entry that
+ overruns either cap must fail the restore and remove its partial file rather
+ than truncate it into a file that looks complete.
+ A restore that fails partway must roll the target back to an empty state.
+ The replace gate has already deleted whatever it replaced, so leaving the
+ half-written tree behind hands the operator a control plane that looks
+ bootable and forces the retry through the replace gate again; the failure
+ must instead clear the restore targets it wrote and say so in the error.
6. `internal/cloudcp/provider_msp_recovery.go` shared with `cloud-paid`: provider-hosted MSP failed-workspace recovery is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.
`pulse-control-plane provider-msp recover` must offer a dry-run plan and an
explicit execution path for failed, stuck provisioning, and unhealthy active
diff --git a/internal/cloudcp/provider_msp_backup.go b/internal/cloudcp/provider_msp_backup.go
index 2a95ee8b3e..34a0ec38e9 100644
--- a/internal/cloudcp/provider_msp_backup.go
+++ b/internal/cloudcp/provider_msp_backup.go
@@ -29,6 +29,13 @@ const (
providerMSPBackupLicenseDir = "license"
providerMSPBackupLicenseName = "provider-msp-license.jwt"
maxProviderMSPBackupManifestSize = 1024 * 1024
+ // Restore writes archive-supplied data straight to disk, so a single entry
+ // and the restore as a whole are both bounded. Without this a gzip bomb, a
+ // sparse entry declaring a huge logical size, or a corrupt stream can fill
+ // the target volume. The limits are far above any plausible provider MSP
+ // backup; they exist to make the write bounded, not to size-check backups.
+ maxProviderMSPBackupRestoreEntryBytes = 8 << 30 // 8 GiB per restored entry
+ maxProviderMSPBackupRestoreTotalBytes = 64 << 30 // 64 GiB per restore
)
// ProviderMSPBackupManifest is the recovery contract stored inside every
@@ -301,14 +308,46 @@ func RestoreProviderMSPBackup(ctx context.Context, opts ProviderMSPBackupRestore
return nil, fmt.Errorf("create restore target data dir: %w", err)
}
if err := extractProviderMSPBackupArchive(ctx, verified.ArchivePath, targetDataDir, licenseOutputPath, result); err != nil {
- return nil, err
+ return nil, failProviderMSPRestore(result, err)
}
if err := validateRestoredProviderMSPBackup(result); err != nil {
- return nil, err
+ return nil, failProviderMSPRestore(result, err)
}
return result, nil
}
+// failProviderMSPRestore rolls a half-finished restore back to an empty target.
+// Everything under the restore paths was written by this call: the conflict
+// check refuses to overwrite pre-existing state, and replace clears it up
+// front. So removing them is safe, and it leaves a clean slate that a retry can
+// use without needing replace, rather than a partial control plane that looks
+// bootable. It cannot bring back state that replace already deleted, so the
+// error says so.
+func failProviderMSPRestore(result *ProviderMSPBackupRestoreResult, cause error) error {
+ if err := removeProviderMSPPartialRestore(result); err != nil {
+ return fmt.Errorf("%w (rolling back the partial restore also failed: %v)", cause, err)
+ }
+ if result.ReplaceExisting {
+ return fmt.Errorf("%w (the partial restore was rolled back, and the state it replaced was already deleted)", cause)
+ }
+ return fmt.Errorf("%w (the partial restore was rolled back)", cause)
+}
+
+func removeProviderMSPPartialRestore(result *ProviderMSPBackupRestoreResult) error {
+ for _, dir := range []string{result.ControlPlaneDir, result.TenantsDir} {
+ if err := os.RemoveAll(dir); err != nil {
+ return fmt.Errorf("remove partial restore target %s: %w", dir, err)
+ }
+ }
+ // Only the license this restore wrote is ours to remove.
+ if result.LicenseEntriesRestored > 0 {
+ if err := os.Remove(result.LicenseOutputPath); err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("remove partial restored provider MSP license: %w", err)
+ }
+ }
+ return nil
+}
+
// VerifyProviderMSPBackup validates that a provider MSP backup contains the
// manifest, tenant registry snapshot, required tenant directories, and license
// artifact declared by the manifest.
@@ -522,6 +561,7 @@ func extractProviderMSPBackupArchive(ctx context.Context, archivePath, targetDat
}
defer gz.Close()
+ budget := newProviderMSPRestoreBudget()
tr := tar.NewReader(gz)
for {
if err := ctx.Err(); err != nil {
@@ -542,19 +582,19 @@ func extractProviderMSPBackupArchive(ctx context.Context, archivePath, targetDat
case name == providerMSPBackupManifestName:
continue
case name == providerMSPBackupControlPlaneDir || strings.HasPrefix(name, providerMSPBackupControlPlaneDir+"/"):
- if err := restoreProviderMSPArchiveEntry(tr, header, targetDataDir, name); err != nil {
+ if err := restoreProviderMSPArchiveEntry(tr, header, targetDataDir, name, budget); err != nil {
return err
}
result.ControlPlaneEntriesRestored++
case name == providerMSPBackupTenantsDir || strings.HasPrefix(name, providerMSPBackupTenantsDir+"/"):
- if err := restoreProviderMSPArchiveEntry(tr, header, targetDataDir, name); err != nil {
+ if err := restoreProviderMSPArchiveEntry(tr, header, targetDataDir, name, budget); err != nil {
return err
}
result.TenantEntriesRestored++
case name == providerMSPBackupLicenseDir:
continue
case name == providerMSPBackupLicenseDir+"/"+providerMSPBackupLicenseName:
- if err := restoreProviderMSPArchiveFile(tr, header, licenseOutputPath); err != nil {
+ if err := restoreProviderMSPArchiveFile(tr, header, licenseOutputPath, budget); err != nil {
return err
}
result.LicenseEntriesRestored++
@@ -565,7 +605,46 @@ func extractProviderMSPBackupArchive(ctx context.Context, archivePath, targetDat
return nil
}
-func restoreProviderMSPArchiveEntry(reader io.Reader, header *tar.Header, targetDataDir, archiveName string) error {
+// providerMSPRestoreBudget bounds how many bytes a restore may write to disk,
+// per entry and across the whole archive. Both bounds are enforced against the
+// bytes actually copied rather than the size the tar header declares, because
+// that header comes from the archive and is therefore attacker-influenced.
+type providerMSPRestoreBudget struct {
+ entryCap int64
+ totalCap int64
+ remaining int64
+}
+
+func newProviderMSPRestoreBudget() *providerMSPRestoreBudget {
+ return &providerMSPRestoreBudget{
+ entryCap: maxProviderMSPBackupRestoreEntryBytes,
+ totalCap: maxProviderMSPBackupRestoreTotalBytes,
+ remaining: maxProviderMSPBackupRestoreTotalBytes,
+ }
+}
+
+// entryLimit is the most the next entry may write: the per-entry cap, or
+// whatever is left of the whole-restore budget when that is smaller.
+func (b *providerMSPRestoreBudget) entryLimit() int64 {
+ if b.remaining < b.entryCap {
+ return b.remaining
+ }
+ return b.entryCap
+}
+
+func (b *providerMSPRestoreBudget) consume(n int64) {
+ b.remaining -= n
+}
+
+// overrunError names whichever bound the entry just crossed.
+func (b *providerMSPRestoreBudget) overrunError() error {
+ if b.remaining < b.entryCap {
+ return fmt.Errorf("backup restore exceeds the %d byte total restore limit", b.totalCap)
+ }
+ return fmt.Errorf("backup restore entry exceeds the %d byte per-entry limit", b.entryCap)
+}
+
+func restoreProviderMSPArchiveEntry(reader io.Reader, header *tar.Header, targetDataDir, archiveName string, budget *providerMSPRestoreBudget) error {
destPath := filepath.Join(targetDataDir, filepath.FromSlash(archiveName))
if !pathIsInside(destPath, targetDataDir) {
return fmt.Errorf("backup restore entry escapes target data dir: %s", archiveName)
@@ -574,7 +653,7 @@ func restoreProviderMSPArchiveEntry(reader io.Reader, header *tar.Header, target
case tar.TypeDir:
return restoreProviderMSPArchiveDir(header, destPath)
case tar.TypeReg, tar.TypeRegA:
- return restoreProviderMSPArchiveFile(reader, header, destPath)
+ return restoreProviderMSPArchiveFile(reader, header, destPath, budget)
default:
return fmt.Errorf("unsupported backup restore entry type for %s", archiveName)
}
@@ -591,10 +670,16 @@ func restoreProviderMSPArchiveDir(header *tar.Header, destPath string) error {
return nil
}
-func restoreProviderMSPArchiveFile(reader io.Reader, header *tar.Header, destPath string) error {
+func restoreProviderMSPArchiveFile(reader io.Reader, header *tar.Header, destPath string, budget *providerMSPRestoreBudget) error {
if header.Typeflag != tar.TypeReg && header.Typeflag != tar.TypeRegA {
return fmt.Errorf("backup restore expected regular file at %s", header.Name)
}
+ // The declared size is a hint, not a bound: it comes from the archive, so
+ // it can lie in either direction. Reject an absurd declaration up front to
+ // avoid touching the disk at all, then bound the copy itself below.
+ if header.Size < 0 || header.Size > budget.entryCap {
+ return fmt.Errorf("backup restore entry %s declares %d bytes, above the %d byte per-entry limit", header.Name, header.Size, budget.entryCap)
+ }
mode := os.FileMode(header.Mode) & 0o777
if mode == 0 {
mode = 0o600
@@ -606,14 +691,25 @@ func restoreProviderMSPArchiveFile(reader io.Reader, header *tar.Header, destPat
if err != nil {
return fmt.Errorf("create restored file %s: %w", destPath, err)
}
- _, copyErr := io.Copy(file, reader)
+ // Read one byte past the limit so an overrun is detected rather than
+ // silently truncated into a file that looks complete.
+ limit := budget.entryLimit()
+ written, writeErr := io.Copy(file, io.LimitReader(reader, limit+1))
closeErr := file.Close()
- if copyErr != nil {
- return fmt.Errorf("restore file %s: %w", destPath, copyErr)
+ if writeErr == nil && written > limit {
+ writeErr = budget.overrunError()
}
- if closeErr != nil {
- return fmt.Errorf("close restored file %s: %w", destPath, closeErr)
+ if writeErr == nil {
+ writeErr = closeErr
+ }
+ if writeErr != nil {
+ // Fail the restore instead of leaving a partial file behind.
+ if removeErr := os.Remove(destPath); removeErr != nil && !os.IsNotExist(removeErr) {
+ return fmt.Errorf("restore file %s: %w (removing the partial file also failed: %v)", destPath, writeErr, removeErr)
+ }
+ return fmt.Errorf("restore file %s: %w", destPath, writeErr)
}
+ budget.consume(written)
return nil
}
diff --git a/internal/cloudcp/provider_msp_backup_test.go b/internal/cloudcp/provider_msp_backup_test.go
index 30cb2a00c8..1eec7beca6 100644
--- a/internal/cloudcp/provider_msp_backup_test.go
+++ b/internal/cloudcp/provider_msp_backup_test.go
@@ -5,12 +5,14 @@ import (
"compress/gzip"
"context"
"database/sql"
+ "encoding/json"
"io"
"os"
"path/filepath"
"sort"
"strings"
"testing"
+ "time"
cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
@@ -225,6 +227,169 @@ func TestProviderMSPBackupRestoreRequiresReplaceForExistingState(t *testing.T) {
assertProviderMSPBackupRestoredTenantCount(t, filepath.Join(targetDataDir, "control-plane", "tenants.db"), 2)
}
+// restoreProviderMSPArchiveFile writes archive-supplied bytes straight to disk,
+// and the tar header's declared size cannot bound that write: the header comes
+// from the archive, so a gzip bomb, a sparse entry declaring a huge logical
+// size, or a corrupt stream can all deliver far more than it claims. These
+// tests pin the bound to the bytes actually copied.
+func TestRestoreProviderMSPArchiveFileRejectsDeclaredOversize(t *testing.T) {
+ destPath := filepath.Join(t.TempDir(), "oversized.db")
+ budget := &providerMSPRestoreBudget{entryCap: 64, totalCap: 1 << 20, remaining: 1 << 20}
+ header := &tar.Header{Name: "control-plane/oversized.db", Typeflag: tar.TypeReg, Size: 65, Mode: 0o600}
+
+ err := restoreProviderMSPArchiveFile(strings.NewReader("ignored"), header, destPath, budget)
+ if err == nil {
+ t.Fatal("expected an oversized declared entry size to be rejected")
+ }
+ if !strings.Contains(err.Error(), "per-entry limit") {
+ t.Fatalf("error = %v", err)
+ }
+ if _, statErr := os.Stat(destPath); !os.IsNotExist(statErr) {
+ t.Fatalf("rejected entry should not touch the disk, stat err=%v", statErr)
+ }
+}
+
+func TestRestoreProviderMSPArchiveFileBoundsUnderdeclaredEntry(t *testing.T) {
+ destPath := filepath.Join(t.TempDir(), "bomb.db")
+ budget := &providerMSPRestoreBudget{entryCap: 64, totalCap: 1 << 20, remaining: 1 << 20}
+ // The header understates the payload the way a bomb does: 8 bytes declared,
+ // 4 KiB delivered. Trusting the declaration writes all 4 KiB.
+ header := &tar.Header{Name: "control-plane/bomb.db", Typeflag: tar.TypeReg, Size: 8, Mode: 0o600}
+
+ err := restoreProviderMSPArchiveFile(strings.NewReader(strings.Repeat("x", 4096)), header, destPath, budget)
+ if err == nil {
+ t.Fatal("expected an entry over the per-entry limit to fail the restore")
+ }
+ if !strings.Contains(err.Error(), "per-entry limit") {
+ t.Fatalf("error = %v", err)
+ }
+ if _, statErr := os.Stat(destPath); !os.IsNotExist(statErr) {
+ t.Fatalf("failed entry should not leave a partial file, stat err=%v", statErr)
+ }
+ if budget.remaining != 1<<20 {
+ t.Fatalf("failed entry should not consume budget, remaining = %d", budget.remaining)
+ }
+}
+
+func TestRestoreProviderMSPArchiveFileBoundsTotalRestore(t *testing.T) {
+ dir := t.TempDir()
+ budget := &providerMSPRestoreBudget{entryCap: 1 << 20, totalCap: 24, remaining: 24}
+ header := func(name string) *tar.Header {
+ return &tar.Header{Name: name, Typeflag: tar.TypeReg, Size: 16, Mode: 0o600}
+ }
+
+ firstPath := filepath.Join(dir, "first.db")
+ if err := restoreProviderMSPArchiveFile(strings.NewReader(strings.Repeat("a", 16)), header("control-plane/first.db"), firstPath, budget); err != nil {
+ t.Fatalf("first entry is within budget: %v", err)
+ }
+ if budget.remaining != 8 {
+ t.Fatalf("remaining after first entry = %d, want 8", budget.remaining)
+ }
+
+ // Each entry is under the per-entry cap; only the running total catches it.
+ secondPath := filepath.Join(dir, "second.db")
+ err := restoreProviderMSPArchiveFile(strings.NewReader(strings.Repeat("b", 16)), header("control-plane/second.db"), secondPath, budget)
+ if err == nil {
+ t.Fatal("expected the cumulative restore limit to fail the second entry")
+ }
+ if !strings.Contains(err.Error(), "total restore limit") {
+ t.Fatalf("error = %v", err)
+ }
+ if _, statErr := os.Stat(secondPath); !os.IsNotExist(statErr) {
+ t.Fatalf("failed entry should not leave a partial file, stat err=%v", statErr)
+ }
+ if got, readErr := os.ReadFile(firstPath); readErr != nil || string(got) != strings.Repeat("a", 16) {
+ t.Fatalf("first entry = %q, err=%v", got, readErr)
+ }
+}
+
+// A restore that fails partway has already removed whatever it replaced, so
+// leaving the half-written tree behind hands the operator a control plane that
+// looks bootable and forces the retry to use replace.
+func TestProviderMSPBackupRestoreRollsBackPartialRestore(t *testing.T) {
+ archivePath := writeProviderMSPBackupArchiveFailingMidExtract(t)
+ targetDataDir := filepath.Join(t.TempDir(), "restore-rollback")
+
+ _, err := RestoreProviderMSPBackup(context.Background(), ProviderMSPBackupRestoreOptions{
+ ArchivePath: archivePath,
+ TargetDataDir: targetDataDir,
+ })
+ if err == nil {
+ t.Fatal("expected the unsupported entry to fail the restore")
+ }
+ if !strings.Contains(err.Error(), "unsupported backup restore entry type") {
+ t.Fatalf("error = %v", err)
+ }
+ if !strings.Contains(err.Error(), "rolled back") {
+ t.Fatalf("error should report the rollback, got %v", err)
+ }
+ for _, dir := range []string{providerMSPBackupControlPlaneDir, providerMSPBackupTenantsDir} {
+ if _, statErr := os.Stat(filepath.Join(targetDataDir, dir)); !os.IsNotExist(statErr) {
+ t.Fatalf("failed restore should not leave %s behind, stat err=%v", dir, statErr)
+ }
+ }
+}
+
+// writeProviderMSPBackupArchiveFailingMidExtract builds an archive that passes
+// verification and then fails during extraction, after a real file has already
+// landed in the target.
+func writeProviderMSPBackupArchiveFailingMidExtract(t *testing.T) string {
+ t.Helper()
+ manifestBytes, err := json.Marshal(ProviderMSPBackupManifest{
+ Version: ProviderMSPBackupManifestVersion,
+ CreatedAt: time.Now().UTC(),
+ ControlPlaneMode: string(ControlPlaneModeProviderHostedMSP),
+ Environment: "production",
+ BaseURL: "https://msp.example.com",
+ PlanVersion: "msp_growth",
+ PlanSource: ProviderMSPPlanSourceLicenseFile,
+ ControlPlaneDir: providerMSPBackupControlPlaneDir,
+ TenantsDir: providerMSPBackupTenantsDir,
+ ControlPlaneDBBackups: []string{providerMSPBackupControlPlaneDir + "/tenants.db"},
+ })
+ if err != nil {
+ t.Fatalf("marshal manifest: %v", err)
+ }
+
+ archivePath := filepath.Join(t.TempDir(), "partial-restore.tar.gz")
+ file, err := os.Create(archivePath)
+ if err != nil {
+ t.Fatalf("create archive: %v", err)
+ }
+ defer file.Close()
+ gz := gzip.NewWriter(file)
+ tw := tar.NewWriter(gz)
+
+ writeHeader := func(header *tar.Header) {
+ if err := tw.WriteHeader(header); err != nil {
+ t.Fatalf("write header %s: %v", header.Name, err)
+ }
+ }
+ writeFile := func(name string, content []byte) {
+ writeHeader(&tar.Header{Name: name, Typeflag: tar.TypeReg, Mode: 0o600, Size: int64(len(content))})
+ if _, err := tw.Write(content); err != nil {
+ t.Fatalf("write entry %s: %v", name, err)
+ }
+ }
+
+ writeFile(providerMSPBackupManifestName, manifestBytes)
+ writeHeader(&tar.Header{Name: providerMSPBackupControlPlaneDir + "/", Typeflag: tar.TypeDir, Mode: 0o755})
+ writeFile(providerMSPBackupControlPlaneDir+"/tenants.db", []byte("restored-before-the-failure"))
+ writeHeader(&tar.Header{Name: providerMSPBackupTenantsDir + "/", Typeflag: tar.TypeDir, Mode: 0o755})
+ writeHeader(&tar.Header{Name: providerMSPBackupTenantsDir + "/t-ACTIVE001/", Typeflag: tar.TypeDir, Mode: 0o755})
+ // Restore only handles regular files and directories, so this aborts the
+ // extraction with tenants.db already written.
+ writeHeader(&tar.Header{Name: providerMSPBackupControlPlaneDir + "/link", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd", Mode: 0o777})
+
+ if err := tw.Close(); err != nil {
+ t.Fatalf("close tar: %v", err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatalf("close gzip: %v", err)
+ }
+ return archivePath
+}
+
func TestProviderMSPBackupManifestAcceptsMSPControlPlaneModes(t *testing.T) {
base := ProviderMSPBackupManifest{
Version: ProviderMSPBackupManifestVersion,