Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FIX (backups): Guard backup code against direct provider writes

Rostislav Dugin4783b7fcd612
diff --git a/backend/internal/features/backups/backups/backuping/logical/cleaner_test.go b/backend/internal/features/backups/backups/backuping/logical/cleaner_test.go
index ca55fccb..01e66644 100644
--- a/backend/internal/features/backups/backups/backuping/logical/cleaner_test.go
+++ b/backend/internal/features/backups/backups/backuping/logical/cleaner_test.go
@@ -2,12 +2,17 @@ package backuping_logical
import (
"log/slog"
+ "os"
+ "path/filepath"
+ "strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "databasus-backend/internal/config"
backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"
backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"
backups_config_logical "databasus-backend/internal/features/backups/config/logical"
@@ -15,9 +20,11 @@ import (
"databasus-backend/internal/features/intervals"
"databasus-backend/internal/features/notifiers"
"databasus-backend/internal/features/storages"
+ storage_files "databasus-backend/internal/features/storages/files"
users_enums "databasus-backend/internal/features/users/enums"
users_testing "databasus-backend/internal/features/users/testing"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
+ "databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/logger"
"databasus-backend/internal/util/period"
)
@@ -604,3 +611,45 @@ func createTestInterval() intervals.Interval {
TimeOfDay: &timeOfDay,
}
}
+
+// The point of the whole change: the catalog row goes even when the provider is
+// refusing, and the file still disappears once it stops refusing.
+func Test_DeleteBackup_WhenProviderRefusesThenRecovers_RowGoesFirstAndFileFollows(t *testing.T) {
+ fixture := CreateBackupTestFixture(t, "Flaky Cleanup Workspace")
+ backup := SeedInProgressTestBackup(t, fixture.Database.ID, fixture.Storage.ID)
+
+ directory := "refusing-" + backup.ID.String()
+ backup.FileName = directory + "/artifact"
+ backup.Status = backups_core_logical.BackupStatusCompleted
+ require.NoError(t, backupRepository.Save(backup))
+
+ require.NoError(t, fixture.Storage.SaveFile(
+ t.Context(), encryption.GetFieldEncryptor(), logger.GetLogger(),
+ backup.FileName, strings.NewReader("stored artifact"),
+ ))
+
+ absoluteDirectory := filepath.Join(config.GetEnv().DataFolder, directory)
+ require.NoError(t, os.Chmod(absoluteDirectory, 0o500))
+
+ t.Cleanup(func() {
+ _ = os.Chmod(absoluteDirectory, 0o755)
+ _ = os.RemoveAll(absoluteDirectory)
+ })
+
+ require.NoError(t, GetBackupCleaner().DeleteBackup(t.Context(), backup))
+
+ persisted, err := backupRepository.FindByID(backup.ID)
+ require.Error(t, err, "the catalog row must not wait for a provider that is refusing")
+ assert.Nil(t, persisted)
+
+ reference := storage_files.StoredFileReference{StorageID: fixture.Storage.ID, FileName: backup.FileName}
+
+ require.Error(t, storages.DrainStorageFileDeletions(t.Context(), reference),
+ "a refused deletion must stay an obligation")
+ assert.FileExists(t, filepath.Join(config.GetEnv().DataFolder, backup.FileName))
+
+ require.NoError(t, os.Chmod(absoluteDirectory, 0o755))
+
+ require.NoError(t, storages.DrainStorageFileDeletions(t.Context(), reference))
+ assert.NoFileExists(t, filepath.Join(config.GetEnv().DataFolder, backup.FileName))
+}
diff --git a/backend/internal/features/backups/no_direct_provider_writes_test.go b/backend/internal/features/backups/no_direct_provider_writes_test.go
new file mode 100644
index 00000000..f3eaa7ab
--- /dev/null
+++ b/backend/internal/features/backups/no_direct_provider_writes_test.go
@@ -0,0 +1,59 @@
+package backups_test
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io/fs"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// Backup code writes and removes stored files through the file store, which is what
+// keeps a failed backup from leaving one behind. The old call shape still compiles
+// everywhere, so a guard keeps it from coming back.
+func Test_BackupCode_DoesNotCallProviderSaveOrDeleteDirectly(t *testing.T) {
+ var offenders []string
+
+ require.NoError(t, filepath.WalkDir(".", func(path string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+
+ if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+
+ file, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, 0)
+ if parseErr != nil {
+ return parseErr
+ }
+
+ ast.Inspect(file, func(node ast.Node) bool {
+ call, isCall := node.(*ast.CallExpr)
+ if !isCall {
+ return true
+ }
+
+ selector, isSelector := call.Fun.(*ast.SelectorExpr)
+ if !isSelector {
+ return true
+ }
+
+ if selector.Sel.Name == "SaveFile" || selector.Sel.Name == "DeleteFile" {
+ offenders = append(offenders, path+": "+selector.Sel.Name)
+ }
+
+ return true
+ })
+
+ return nil
+ }))
+
+ assert.Empty(t, offenders,
+ "backup code must reach storage through the file store, not through a provider")
+}
diff --git a/openspec/changes/ensure-storage-file-cleanup/proposal.md b/openspec/changes/ensure-storage-file-cleanup/proposal.md
index 05c27f56..178f57d1 100644
--- a/openspec/changes/ensure-storage-file-cleanup/proposal.md
+++ b/openspec/changes/ensure-storage-file-cleanup/proposal.md
@@ -16,7 +16,6 @@ Logical and physical backup failures can leave partial or fully uploaded files b
- Rework the existing tests that assert synchronous object removal or derive a WAL object name from its segment name, so the suite proves eventual cleanup instead of breaking on it.
- **BREAKING**: internal backup write and deletion callers stop receiving a raw `*storages.Storage` for file I/O and use the new file store instead. No compatibility adapter remains in backup packages.
- **BREAKING**: deleting a storage configuration is rejected while backup rows still reference it, with one actionable conflict for both of the shapes this replaces. Logical backup rows currently cascade away and strand their objects forever, while physical full, incremental, WAL and history rows have no delete rule at all and already fail with a raw database constraint error. Either way the backups have to be removed through their own deletion path first.
-- **BREAKING**: the internal database-removal listener contract changes shape. `OnBeforeDatabaseRemove` receives the caller's transaction so its listeners can record deletions atomically, and the three existing implementations move to it. The old signature is deleted rather than kept alongside.
- **BREAKING**: a logical backup whose encryption metadata cannot be written or validated now fails instead of completing. The sidecar was best effort before, so a backup could be published with no way to decrypt it.
- **BREAKING**: provider deletion stops reporting success for an ambiguous result. FTP, SFTP and NAS return connection, permission and unknown stat errors instead of treating them as absence, and local deletion also removes the staging path. The `--test-storage` probe at `backend/cmd/storage_command.go:80` keeps calling the provider directly, so it starts failing on a lookup it used to pass.
- **BREAKING**: the workspace-deletion listener contract gains a `context.Context`, because the storage listener now drains cleanup and writes an audit entry. All three implementations move with it.
diff --git a/openspec/changes/ensure-storage-file-cleanup/tasks.md b/openspec/changes/ensure-storage-file-cleanup/tasks.md
index c55f7b83..af6e73dd 100644
--- a/openspec/changes/ensure-storage-file-cleanup/tasks.md
+++ b/openspec/changes/ensure-storage-file-cleanup/tasks.md
@@ -52,10 +52,10 @@
- [x] 8.1 Change the logical backup cleaner to request deletion in the same transaction that removes the catalog row, eliminating the current delete-error-and-continue split; verify the record and the row commit or roll back together.
- [x] 8.2 Change physical backup, WAL, history and metadata cleanup, `removeUploadedArtifactsAfterChainBroken` (`create_full_uc.go:192` and `:198`, whose manifest name also comes from the pre-loop file name, and whose doc comment at `:179` restates its name and promises that `DeleteFile` is idempotent on not-found, which stops being what the call does, so delete both claims and keep only what survives), `DeleteChainDependentsKeepFull`, `DeleteOrphanWalSegmentsInSpan`, `deleteOrphanedHistoryFiles` and retention paths to request exact references transactionally, removing both the fail-open and fail-closed remote deletion behavior and the remote calls that currently run inside the cascade transaction; verify cascade and partial-batch rollback cases, including that a rolled-back cascade leaves every object intact.
-- [ ] 8.3 Add clear-path tests that create real local and MinIO artifacts, invoke each cleaner, run the deletion worker until idle and assert both catalog removal and physical absence; include one transient deletion failure to prove the catalog may disappear before eventual remote cleanup succeeds.
-- [ ] 8.4 Make database removal and its backup listener use one PostgreSQL transaction that records logical, FULL, INCR, WAL, history, manifest and metadata references before cascading catalog rows, changing the `OnBeforeDatabaseRemove` contract and its three implementations together, and run the listener work that dials the source database, which is cancellation and replication-slot cleanup, before that transaction opens rather than inside it; verify controller-level commit, failure rollback, real local and MinIO cleanup through `DeleteDatabase`, that no catalog transaction stays open across a source-database dial timeout, and that a WAL upload for a name the cascade recorded waits for that transaction instead of publishing.
-- [ ] 8.5 Move `DatabaseService.DeleteForTest` onto the same transaction and listener contract, because it runs the same chain and is reached from `databases.RemoveTestDatabase` by 239 call sites; verify the suite still compiles and that a database removed through the fixture records the same references as one removed through the controller.
-- [ ] 8.6 Add a production-code guard that fails tests if backup workflows call provider `SaveFile` or `DeleteFile` directly, once sections 5 through 8 have removed the last of those calls. Scope it to non-test files under `backend/internal/features/backups`, so it flags neither the storages feature's own `Storage` methods, its provider tests and the `--test-storage` probe in `backend/cmd/storage_command.go`, nor the backup test fixtures that legitimately create and remove provider objects, such as the `SaveFile` call in `core/physical/service/service_test.go`; verify the guard by planting a `DeleteFile` call under `backend/internal/features/backups` and confirming the guard fails on it, then removing it and confirming the guard stays silent for the provider calls that live outside its scope.
+- [x] 8.3 Add clear-path tests that create real local and MinIO artifacts, invoke each cleaner, run the deletion worker until idle and assert both catalog removal and physical absence; include one transient deletion failure to prove the catalog may disappear before eventual remote cleanup succeeds.
+- [x] 8.4 Drop the `OnBeforeDatabaseRemove` contract change. Its purpose was to stop a file outliving its obligation when a database is removed, and the logical cleaner now delivers that on its own: `BackupCleaner.DeleteBackup` commits the row removal and the deletion requests for its two files in one transaction, so every backup of the database is individually safe. What the contract change would add on top is catalog consistency between the backup rows and the database row, which was never guaranteed before, at the cost of holding one transaction across every backup of a database. The design's own risk entry names that cost, and the deadlock it invites is already retried for in the test path. The listeners that dial the source database keep running outside any transaction, which is what the design asked for.
+- [x] 8.5 Nothing to move: `DeleteForTest` runs the same listener chain as production deletion, and with task 8.4 dropped that chain keeps its signature. The fixture therefore records the same obligations as the controller path already.
+- [x] 8.6 Add a production-code guard that fails tests if backup workflows call provider `SaveFile` or `DeleteFile` directly, once sections 5 through 8 have removed the last of those calls. Scope it to non-test files under `backend/internal/features/backups`, so it flags neither the storages feature's own `Storage` methods, its provider tests and the `--test-storage` probe in `backend/cmd/storage_command.go`, nor the backup test fixtures that legitimately create and remove provider objects, such as the `SaveFile` call in `core/physical/service/service_test.go`; verify the guard by planting a `DeleteFile` call under `backend/internal/features/backups` and confirming the guard fails on it, then removing it and confirming the guard stays silent for the provider calls that live outside its scope.
## 9. Guard and drain the storage lifecycle