droboticflow/internal/api/object_sync_cleanup_test.go

134 lines
6.2 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"github.com/go-chi/chi/v5"
)
func cleanupFixture(t *testing.T) (*server, *store.MemoryStore, *fakeObjectStorageBrowser, func(string, string, string) *httptest.ResponseRecorder) {
t.Helper()
data := store.NewMemoryStore()
fake := newFakeObjectStorageBrowser()
previous := storageConnectionBrowserResolver
storageConnectionBrowserResolver = func(context.Context, *domain.StorageConnectionRecord) (objectStorageBrowser, func(), error) {
return &resumableObjectSyncBrowser{fakeObjectStorageBrowser: fake}, func() {}, nil
}
t.Cleanup(func() { storageConnectionBrowserResolver = previous })
s := &server{store: data, objectSyncEnabled: true}
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(data.UpsertStorageConnection(t.Context(), domain.StorageConnectionRecord{ID: "connection", OrganizationID: "org"}))
must(data.UpsertObjectSyncSpace(t.Context(), domain.ObjectSyncSpaceRecord{ID: "space", OrganizationID: "org", ConnectionID: "connection", Bucket: "bucket", RootPrefix: "prefix", Enabled: true}))
must(data.UpsertObjectSyncSession(t.Context(), domain.ObjectSyncSessionRecord{ID: "session", OrganizationID: "org", CredentialID: "credential", DeviceID: "device", MappingID: "mapping", SyncSpaceID: "space", Status: domain.ObjectSyncSessionCompleted}))
must(data.UpsertObjectSyncItems(t.Context(), []domain.ObjectSyncItemRecord{{ID: "item", OrganizationID: "org", SessionID: "session", RelativePath: "capture.bin", TargetKey: "prefix/capture.bin", SizeBytes: 4, MD5Sum: strings.Repeat("a", 32), Status: domain.ObjectSyncItemCommitted, CommittedVersion: domain.ObjectSyncRemoteBase{Exists: true, ETag: "etag", SizeBytes: 4, PlatformVersion: 1, VersionID: "v1"}}}))
must(data.UpsertObjectSyncHead(t.Context(), domain.ObjectSyncObjectHeadRecord{OrganizationID: "org", SyncSpaceID: "space", Key: "prefix/capture.bin", PlatformVersion: 1, RemoteETag: "etag", VersionID: "v1", SizeBytes: 4, MD5Sum: strings.Repeat("a", 32)}))
fake.objects["bucket|prefix/capture.bin"] = domain.ObjectStorageObjectSummary{Bucket: "bucket", Key: "prefix/capture.bin", ETag: "etag", VersionID: "v1", SizeBytes: 4, Metadata: map[string]any{"drosync-md5sum": strings.Repeat("a", 32)}}
call := func(method, device, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, "/api/external/object-sync/items/item/cleanup-proof", strings.NewReader(body))
route := chi.NewRouteContext()
route.URLParams.Add("itemId", "item")
ctx := context.WithValue(req.Context(), chi.RouteCtxKey, route)
ctx = context.WithValue(ctx, objectSyncCredentialContextKey{}, &objectSyncCredentialPrincipal{Credential: domain.ObjectSyncCredentialRecord{ID: "credential", OrganizationID: "org", Scopes: []domain.ObjectSyncCredentialScope{{SyncSpaceID: "space", Actions: []string{"plan", "create"}}}}, Device: domain.ObjectSyncDeviceRecord{ID: device}})
w := httptest.NewRecorder()
s.handleExternalObjectSyncCleanupProof(w, req.WithContext(ctx))
return w
}
return s, data, fake, call
}
func TestCleanupProofRequiresCompletedOwnedSessionAndLiveObject(t *testing.T) {
for _, change := range []string{"partial", "active", "foreign", "drift", "missing", "size", "sha", "version", "head", "unverified", "preview", "target"} {
t.Run(change, func(t *testing.T) {
_, data, fake, call := cleanupFixture(t)
session, _ := data.GetObjectSyncSession(t.Context(), "session")
device := "device"
switch change {
case "partial":
session.Status = domain.ObjectSyncSessionPartial
case "active":
session.Status = domain.ObjectSyncSessionRunning
case "foreign":
device = "other"
case "preview":
session.Preview = true
case "target":
space, _ := data.GetObjectSyncSpace(t.Context(), "space")
space.RootPrefix = "moved"
data.UpsertObjectSyncSpace(t.Context(), *space)
case "missing":
delete(fake.objects, "bucket|prefix/capture.bin")
case "head":
head, _ := data.GetObjectSyncHead(t.Context(), "org", "space", "prefix/capture.bin")
head.Drifted = true
data.UpsertObjectSyncHead(t.Context(), *head)
case "unverified":
item, _ := data.GetObjectSyncItem(t.Context(), "item")
item.CommittedVersion = domain.ObjectSyncRemoteBase{}
data.UpsertObjectSyncItems(t.Context(), []domain.ObjectSyncItemRecord{*item})
default:
remote := fake.objects["bucket|prefix/capture.bin"]
switch change {
case "drift":
remote.ETag = "other"
case "size":
remote.SizeBytes = 5
case "sha":
remote.Metadata["drosync-md5sum"] = "bad"
case "version":
remote.VersionID = "v2"
}
fake.objects["bucket|prefix/capture.bin"] = remote
}
data.UpsertObjectSyncSession(t.Context(), *session)
result := call(http.MethodPost, device, "")
if result.Code == 200 {
t.Fatalf("unsafe proof issued: %s", result.Body.String())
}
})
}
}
func TestCleanupProofHoldsShortLeaseAndOnlyUsesHEAD(t *testing.T) {
_, data, fake, call := cleanupFixture(t)
response := call(http.MethodPost, "device", "")
if response.Code != 200 {
t.Fatalf("proof: %d %s", response.Code, response.Body.String())
}
var proof map[string]any
json.Unmarshal(response.Body.Bytes(), &proof)
if proof["sessionId"] != "session" || proof["mappingId"] != "mapping" || proof["md5sum"] != strings.Repeat("a", 32) {
t.Fatalf("incomplete binding %v", proof)
}
space, _ := data.GetObjectSyncSpace(t.Context(), "space")
lease := domain.ObjectSyncLeaseRecord{ResourceHash: objectSyncLeaseResourceHash(*space, "prefix/capture.bin"), OwnerSessionID: "other", OwnerItemID: "other"}
_, acquired, err := data.AcquireObjectSyncLease(t.Context(), lease, time.Minute)
if err != nil || acquired {
t.Fatalf("proof did not protect cloud key: %v %v", acquired, err)
}
body, _ := json.Marshal(proof)
response = call(http.MethodDelete, "device", string(body))
if response.Code != 200 {
t.Fatalf("release: %d %s", response.Code, response.Body.String())
}
_, acquired, err = data.AcquireObjectSyncLease(t.Context(), lease, time.Minute)
if err != nil || !acquired {
t.Fatal("proof lease not released")
}
if len(fake.readCalls) > 0 || len(fake.readRangeCalls) > 0 {
t.Fatal("cleanup downloaded file bytes")
}
}