From 7b932d1e243ec7b159e22b041c2327072cac3d47 Mon Sep 17 00:00:00 2001 From: Nikolai Emil Damm Date: Wed, 25 Nov 2026 13:33:43 +0100 Subject: [PATCH 1/6] fix(email): read the restore source from the encrypted claim The mail server serves its store from email-data-encrypted (storage class email-encrypted) since the encrypted-storage cutover. The recovery source proof still required private-mail-data on longhorn-wffc, so every restore proof stopped at preflight on today's cluster. Bind the data volume to the encrypted claim and refuse a read-only data mount. The original claim stays mounted read-only as the rollback and is not the store this proof backs up. Part of #6256 Co-Authored-By: Claude Opus 5.5 --- .../cleanup_test.go | 2 +- .../kubernetes_test.go | 2 +- .../verify-email-data-recovery/observation.go | 4 +- .../observation_lifecycle_test.go | 2 +- .../verify-email-data-recovery/scope_test.go | 1 + scripts/verify-email-data-recovery/source.go | 16 +++++-- .../verify-email-data-recovery/source_test.go | 46 +++++++++++++++++-- .../transfer_test.go | 2 +- 8 files changed, 61 insertions(+), 14 deletions(-) diff --git a/scripts/verify-email-data-recovery/cleanup_test.go b/scripts/verify-email-data-recovery/cleanup_test.go index b52014c34c..049ea19001 100644 --- a/scripts/verify-email-data-recovery/cleanup_test.go +++ b/scripts/verify-email-data-recovery/cleanup_test.go @@ -131,7 +131,7 @@ func cleanupFixture(t *testing.T, blocked bool) (*recoveryDriver, *cleanupAPI, c t.Fatal(err) } a.objects[cleanupKey("Pod", "private-mail", "private-mail-0")] = pod - a.objects[cleanupKey("PersistentVolumeClaim", "private-mail", "private-mail-data")] = sourcePVC + a.objects[cleanupKey("PersistentVolumeClaim", "private-mail", servingClaim)] = sourcePVC a.objects[cleanupKey("PersistentVolume", "", d.source.pv)] = pv for path, key := range map[string]string{ "/api/v1/namespaces/" + i.namespace + "/pods/reader": cleanupKey("Pod", i.namespace, "reader"), diff --git a/scripts/verify-email-data-recovery/kubernetes_test.go b/scripts/verify-email-data-recovery/kubernetes_test.go index 217e7bb961..08ee089df1 100644 --- a/scripts/verify-email-data-recovery/kubernetes_test.go +++ b/scripts/verify-email-data-recovery/kubernetes_test.go @@ -80,7 +80,7 @@ func newBoundaryDriver() (*recoveryDriver, *boundaryAPI) { func TestServingAndForeignResourcesAreRefusedBeforeKubernetesWrite(t *testing.T) { d, a := newBoundaryDriver() - for _, o := range []object{{"kind": "PersistentVolumeClaim", "metadata": object{"name": "private-mail-data", "namespace": "private-mail"}}, {"kind": "Secret", "metadata": object{"name": "storage-key", "namespace": "another"}}} { + for _, o := range []object{{"kind": "PersistentVolumeClaim", "metadata": object{"name": "private-mail-data", "namespace": "private-mail"}}, {"kind": "PersistentVolumeClaim", "metadata": object{"name": servingClaim, "namespace": "private-mail"}}, {"kind": "Secret", "metadata": object{"name": "storage-key", "namespace": "another"}}} { if _, err := d.create(context.Background(), o); err == nil { t.Fatal("foreign mutation was allowed") } diff --git a/scripts/verify-email-data-recovery/observation.go b/scripts/verify-email-data-recovery/observation.go index 69a0b0e538..9009cbf773 100644 --- a/scripts/verify-email-data-recovery/observation.go +++ b/scripts/verify-email-data-recovery/observation.go @@ -47,7 +47,7 @@ func (o observationReadOnly) call(ctx context.Context, input []byte, args ...str if o.parity { allowedReads = append(allowedReads, []string{"get", "Pod", "private-mail-0", "--ignore-not-found=true", "-o=json", "--namespace=private-mail"}, - []string{"get", "PersistentVolumeClaim", "private-mail-data", "--ignore-not-found=true", "-o=json", "--namespace=private-mail"}, + []string{"get", "PersistentVolumeClaim", servingClaim, "--ignore-not-found=true", "-o=json", "--namespace=private-mail"}, []string{"get", "PersistentVolumeClaim", "data", "--ignore-not-found=true", "-o=json", "--namespace=" + target.namespace}, ) if o.servingVolume != "" { @@ -252,7 +252,7 @@ func bindObservationParity(ctx context.Context, d *recoveryDriver, reads observa if _, err = d.owned(ctx, ref); err != nil { return "reader-claim" } - claim, found, err = d.lookup(ctx, "PersistentVolumeClaim", "private-mail-data", "private-mail") + claim, found, err = d.lookup(ctx, "PersistentVolumeClaim", servingClaim, "private-mail") reads.servingVolume = text(child(claim, "spec"), "volumeName") if err != nil || !found || !kubernetesName.MatchString(reads.servingVolume) { return "source-identity" diff --git a/scripts/verify-email-data-recovery/observation_lifecycle_test.go b/scripts/verify-email-data-recovery/observation_lifecycle_test.go index 482ec2bdce..f50707507e 100644 --- a/scripts/verify-email-data-recovery/observation_lifecycle_test.go +++ b/scripts/verify-email-data-recovery/observation_lifecycle_test.go @@ -75,7 +75,7 @@ func (a *observedReaderAPI) call(_ context.Context, input []byte, args ...string } return json.Marshal(a.pod) case "PersistentVolumeClaim": - if args[2] == "private-mail-data" && a.servingClaim != nil { + if args[2] == servingClaim && a.servingClaim != nil { return json.Marshal(a.servingClaim) } if args[2] == "data" && a.readerClaim != nil { diff --git a/scripts/verify-email-data-recovery/scope_test.go b/scripts/verify-email-data-recovery/scope_test.go index d7a0b1891d..3e454422d9 100644 --- a/scripts/verify-email-data-recovery/scope_test.go +++ b/scripts/verify-email-data-recovery/scope_test.go @@ -77,6 +77,7 @@ func TestRecoveryWritesAreLimitedToTheirOwnResources(t *testing.T) { } for _, ref := range [][3]string{ {"PersistentVolumeClaim", "private-mail", "private-mail-data"}, + {"PersistentVolumeClaim", "private-mail", servingClaim}, {"Pod", "private-mail", "private-mail-0"}, {"Secret", "private-mail", "private-mail-admin"}, {"Secret", "velero", "velero-repo-credentials"}, diff --git a/scripts/verify-email-data-recovery/source.go b/scripts/verify-email-data-recovery/source.go index 53bf358e54..4e63bdee24 100644 --- a/scripts/verify-email-data-recovery/source.go +++ b/scripts/verify-email-data-recovery/source.go @@ -9,6 +9,14 @@ import ( var kubernetesName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) +// The server serves its store from the encrypted claim (#5387). The original +// unencrypted claim stays mounted read-only by the copy step as the rollback; +// it is not the data volume this proof backs up and restores. +const ( + servingClaim = "email-data-encrypted" + servingStorageClass = "email-encrypted" +) + // Both serving profiles use the reviewed bundle. Bind runtime identities in a // fixed name order so source retention detects replacement and restart drift. func servingProfile(pod object, expectedImage string) ([2]sourceContainer, error) { @@ -52,7 +60,7 @@ func servingProfile(pod object, expectedImage string) ([2]sourceContainer, error func proveServingSource(pod, pvc, pv object, expectedImage string) (sourceIdentity, error) { pm, cm, vm := child(pod, "metadata"), child(pvc, "metadata"), child(pv, "metadata") fail := func() (sourceIdentity, error) { return sourceIdentity{}, errors.New("serving-source") } - if text(pm, "name") != "private-mail-0" || text(pm, "namespace") != "private-mail" || text(pm, "uid") == "" || pm["deletionTimestamp"] != nil || text(cm, "name") != "private-mail-data" || text(cm, "namespace") != "private-mail" || text(cm, "uid") == "" || cm["deletionTimestamp"] != nil || text(vm, "uid") == "" || vm["deletionTimestamp"] != nil { + if text(pm, "name") != "private-mail-0" || text(pm, "namespace") != "private-mail" || text(pm, "uid") == "" || pm["deletionTimestamp"] != nil || text(cm, "name") != servingClaim || text(cm, "namespace") != "private-mail" || text(cm, "uid") == "" || cm["deletionTimestamp"] != nil || text(vm, "uid") == "" || vm["deletionTimestamp"] != nil { return fail() } if text(child(pm, "labels"), "statefulset.kubernetes.io/pod-name") != "private-mail-0" { @@ -79,14 +87,14 @@ func proveServingSource(pod, pvc, pv object, expectedImage string) (sourceIdenti } found := false for _, volume := range items(child(pod, "spec"), "volumes") { - if text(volume, "name") == "data" && text(child(volume, "persistentVolumeClaim"), "claimName") == "private-mail-data" { + if text(volume, "name") == "data" && text(child(volume, "persistentVolumeClaim"), "claimName") == servingClaim && child(volume, "persistentVolumeClaim")["readOnly"] != true { found = true } } cs, vs := child(pvc, "spec"), child(pv, "spec") name := text(cs, "volumeName") claimRef, csi := child(vs, "claimRef"), child(vs, "csi") - if !found || !kubernetesName.MatchString(name) || text(cs, "storageClassName") != "longhorn-wffc" || text(child(child(cs, "resources"), "requests"), "storage") != "2Gi" || text(child(pvc, "status"), "phase") != "Bound" || text(vm, "name") != name || text(child(pv, "status"), "phase") != "Bound" || text(claimRef, "uid") != text(cm, "uid") || text(claimRef, "namespace") != "private-mail" || text(claimRef, "name") != "private-mail-data" || text(csi, "driver") != "driver.longhorn.io" || text(csi, "volumeHandle") != name { + if !found || !kubernetesName.MatchString(name) || text(cs, "storageClassName") != servingStorageClass || text(child(child(cs, "resources"), "requests"), "storage") != "2Gi" || text(child(pvc, "status"), "phase") != "Bound" || text(vm, "name") != name || text(child(pv, "status"), "phase") != "Bound" || text(claimRef, "uid") != text(cm, "uid") || text(claimRef, "namespace") != "private-mail" || text(claimRef, "name") != servingClaim || text(csi, "driver") != "driver.longhorn.io" || text(csi, "volumeHandle") != name { return fail() } reclaim := text(vs, "persistentVolumeReclaimPolicy") @@ -106,7 +114,7 @@ func (d *recoveryDriver) readSource(ctx context.Context) (sourceIdentity, error) return sourceIdentity{}, err } } - pvc, found, err := d.lookup(ctx, "PersistentVolumeClaim", "private-mail-data", "private-mail") + pvc, found, err := d.lookup(ctx, "PersistentVolumeClaim", servingClaim, "private-mail") if err != nil || !found { return sourceIdentity{}, errors.New("source-claim") } diff --git a/scripts/verify-email-data-recovery/source_test.go b/scripts/verify-email-data-recovery/source_test.go index 13ca18a8fc..c3dfb9cecf 100644 --- a/scripts/verify-email-data-recovery/source_test.go +++ b/scripts/verify-email-data-recovery/source_test.go @@ -7,14 +7,52 @@ import ( "time" ) +// servingFixture is the production shape since the encrypted-storage cutover: +// the data volume is the encrypted claim and the original claim stays mounted +// read-only as the rollback. func servingFixture() (object, object, object) { - pod := object{"metadata": object{"name": "private-mail-0", "namespace": "private-mail", "uid": "serving-pod-uid", "labels": object{"statefulset.kubernetes.io/pod-name": "private-mail-0"}, "ownerReferences": []any{object{"kind": "StatefulSet", "name": "private-mail", "uid": "statefulset-uid", "controller": true}}}, "spec": object{"containers": []any{object{"name": "private-mail", "image": fixtureImage}}, "volumes": []any{object{"name": "data", "persistentVolumeClaim": object{"claimName": "private-mail-data"}}}}, "status": object{"phase": "Running", "conditions": []any{object{"type": "Ready", "status": "True"}}}} + pod := object{"metadata": object{"name": "private-mail-0", "namespace": "private-mail", "uid": "serving-pod-uid", "labels": object{"statefulset.kubernetes.io/pod-name": "private-mail-0"}, "ownerReferences": []any{object{"kind": "StatefulSet", "name": "private-mail", "uid": "statefulset-uid", "controller": true}}}, "spec": object{"containers": []any{object{"name": "private-mail", "image": fixtureImage}}, "volumes": []any{object{"name": "data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted"}}, object{"name": "legacy-data", "persistentVolumeClaim": object{"claimName": "private-mail-data", "readOnly": true}}}}, "status": object{"phase": "Running", "conditions": []any{object{"type": "Ready", "status": "True"}}}} child(pod, "status")["containerStatuses"] = []any{object{"name": "private-mail", "imageID": "runtime-mail", "ready": true, "restartCount": float64(0)}} - pvc := object{"metadata": object{"name": "private-mail-data", "namespace": "private-mail", "uid": "serving-claim-uid"}, "spec": object{"volumeName": "serving-volume", "storageClassName": "longhorn-wffc", "resources": object{"requests": object{"storage": "2Gi"}}}, "status": object{"phase": "Bound"}} - pv := object{"metadata": object{"name": "serving-volume", "uid": "serving-pv-uid"}, "spec": object{"claimRef": object{"namespace": "private-mail", "name": "private-mail-data", "uid": "serving-claim-uid"}, "persistentVolumeReclaimPolicy": "Delete", "csi": object{"driver": "driver.longhorn.io", "volumeHandle": "serving-volume"}}, "status": object{"phase": "Bound"}} + pvc := object{"metadata": object{"name": "email-data-encrypted", "namespace": "private-mail", "uid": "serving-claim-uid"}, "spec": object{"volumeName": "serving-volume", "storageClassName": "email-encrypted", "resources": object{"requests": object{"storage": "2Gi"}}}, "status": object{"phase": "Bound"}} + pv := object{"metadata": object{"name": "serving-volume", "uid": "serving-pv-uid"}, "spec": object{"claimRef": object{"namespace": "private-mail", "name": "email-data-encrypted", "uid": "serving-claim-uid"}, "persistentVolumeReclaimPolicy": "Retain", "csi": object{"driver": "driver.longhorn.io", "volumeHandle": "serving-volume"}}, "status": object{"phase": "Bound"}} return pod, pvc, pv } +// The store moved to the encrypted claim on the cutover. The pre-cutover shape, +// a read-only data mount and the rollback claim are not the serving store. +func TestTheEncryptedClaimIsTheServingSource(t *testing.T) { + pod, pvc, pv := servingFixture() + if _, err := proveServingSource(pod, pvc, pv, fixtureImage); err != nil { + t.Fatal("the encrypted serving store was refused:", err) + } + mutations := map[string]func(object, object, object){ + "pre-cutover-claim": func(p, c, v object) { + child(items(child(p, "spec"), "volumes")[0], "persistentVolumeClaim")["claimName"] = "private-mail-data" + child(c, "metadata")["name"] = "private-mail-data" + child(c, "spec")["storageClassName"] = "longhorn-wffc" + child(child(v, "spec"), "claimRef")["name"] = "private-mail-data" + }, + "unencrypted-class": func(_, c, _ object) { child(c, "spec")["storageClassName"] = "longhorn-wffc" }, + "rollback-as-data": func(p, _, _ object) { + volumes := child(p, "spec")["volumes"].([]any) + volumes[0], volumes[1] = object{"name": "data", "persistentVolumeClaim": object{"claimName": "private-mail-data", "readOnly": true}}, object{"name": "legacy-data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted"}} + }, + "read-only-data": func(p, _, _ object) { + child(items(child(p, "spec"), "volumes")[0], "persistentVolumeClaim")["readOnly"] = true + }, + "volume-of-another-claim": func(_, _, v object) { child(child(v, "spec"), "claimRef")["name"] = "private-mail-data" }, + } + for name, mutate := range mutations { + t.Run(name, func(t *testing.T) { + p, c, v := servingFixture() + mutate(p, c, v) + if _, err := proveServingSource(p, c, v, fixtureImage); err == nil { + t.Fatal("a store other than the encrypted serving claim was accepted") + } + }) + } +} + func proxyServingFixture() (object, object, object) { p, c, v := servingFixture() child(p, "spec")["containers"] = append(child(p, "spec")["containers"].([]any), object{"name": "client-proxy", "image": fixtureImage}) @@ -122,7 +160,7 @@ func TestServingSourceLiveReadOnly(t *testing.T) { func TestServingSourceIsBoundAcrossPodClaimAndBackend(t *testing.T) { pod, pvc, pv := servingFixture() source, err := proveServingSource(pod, pvc, pv, fixtureImage) - if err != nil || source.podUID != "serving-pod-uid" || source.claimUID != "serving-claim-uid" || source.pv != "serving-volume" || source.pvUID != "serving-pv-uid" || source.reclaim != "Delete" { + if err != nil || source.podUID != "serving-pod-uid" || source.claimUID != "serving-claim-uid" || source.pv != "serving-volume" || source.pvUID != "serving-pv-uid" || source.reclaim != "Retain" { t.Fatal("serving source identity was not preserved") } } diff --git a/scripts/verify-email-data-recovery/transfer_test.go b/scripts/verify-email-data-recovery/transfer_test.go index b28eb290ae..83b51d3d37 100644 --- a/scripts/verify-email-data-recovery/transfer_test.go +++ b/scripts/verify-email-data-recovery/transfer_test.go @@ -39,7 +39,7 @@ func TestRestoredStorageMustBeSeparateEncryptedAndBoundToCreatedClaim(t *testing t.Fatal("plaintext restored storage was accepted") } child(volume, "spec")["encrypted"] = true - child(pv, "spec")["claimRef"] = object{"namespace": "private-mail", "name": "private-mail-data", "uid": "source-claim-uid"} + child(pv, "spec")["claimRef"] = object{"namespace": "private-mail", "name": servingClaim, "uid": "source-claim-uid"} if proveRestoredStorage(pvc, pv, volume, i, "target-claim-uid", "source-volume", false) == nil { t.Fatal("serving volume was accepted as isolated storage") } From 5b0a276f68818810b169c8dafc52c33d7f760140 Mon Sep 17 00:00:00 2001 From: Nikolai Emil Damm Date: Wed, 25 Nov 2026 13:44:25 +0100 Subject: [PATCH 2/6] fix(email): inventory the recovery namespace as today's cluster fills it The fresh-copy disposal stopped on 2026-11-13 at its complete inventory. On today's cluster that inventory refused every namespace and the fresh recovery path no longer read it at all: - Kubescape's storage serves scan records through a remotely aggregated API, which the shared inventory refused outright. For an Email recovery namespace only, accept its exact v1beta1 registration backed by kubescape/storage and its workload record kinds. The storage omits list versions and some record UIDs, so its records are bound by resource and name; a computed GeneratedNetworkPolicy must mirror a stored NetworkNeighborhood. Image records and any other remote API still refuse. - One complete inventory now needs 576 reads (128 served versions, 312 collections), above the 512-read bound. Raise it to 1024. - Kyverno's default-limitrange and default-resourcequota and trust-manager's cloudflare-origin-ca ConfigMap are in every namespace. Recognize them by kind, served resource, generate labels bound to the created namespace UID, and the controlling Bundle UID; anything else retains the namespace. - Wire the complete inventory into the fresh recovery through the dispatch's private credential, and refuse to start without it. Events, Kyverno reports named after a known UID and Cilium's endpoint for the created reader are accepted by exact kind and resource. Part of #6256 Co-Authored-By: Claude Opus 5.5 --- internal/namespaceinventory/coverage.go | 4 +- internal/namespaceinventory/credentials.go | 35 ++ .../namespaceinventory/credentials_test.go | 63 ++++ internal/namespaceinventory/inventory.go | 49 ++- internal/namespaceinventory/inventory_test.go | 165 ++++++-- internal/namespaceinventory/scan_records.go | 82 ++++ internal/namespaceinventory/transport.go | 8 +- scripts/verify-email-data-recovery/README.md | 19 + scripts/verify-email-data-recovery/cleanup.go | 11 +- .../cleanup_test.go | 2 +- .../complete_inventory.go | 143 +++++++ .../complete_inventory_test.go | 351 ++++++++++++++++++ .../verify-email-data-recovery/kubernetes.go | 8 + scripts/verify-email-data-recovery/main.go | 2 +- .../namespace_policies.go | 53 ++- scripts/verify-email-data-recovery/run.go | 5 + 16 files changed, 946 insertions(+), 54 deletions(-) create mode 100644 internal/namespaceinventory/scan_records.go create mode 100644 scripts/verify-email-data-recovery/complete_inventory.go create mode 100644 scripts/verify-email-data-recovery/complete_inventory_test.go diff --git a/internal/namespaceinventory/coverage.go b/internal/namespaceinventory/coverage.go index 38cdeb641a..d42b84f45e 100644 --- a/internal/namespaceinventory/coverage.go +++ b/internal/namespaceinventory/coverage.go @@ -79,7 +79,9 @@ func (r *reader) nativeCoverage(ctx context.Context, resources discovery) ([]ser if remote && (item.Spec.Service.Name == "" || item.Spec.Service.Namespace == "") { return nil, errors.New("aggregated API service binding is incomplete") } - if remote && required[gv] { + // An Email recovery namespace is removed by its own invocation, not + // guarded by admission. Kubescape's derived scan records may go with it. + if remote && required[gv] && (!r.scanRecords || !scanStorage(item)) { return nil, errors.New("namespace deletion admission is unverified for a remote API backend") } result = append(result, serviceRegistration{item.Metadata.Name, item.Metadata.UID, gv, item.Metadata.ResourceVersion, remote}) diff --git a/internal/namespaceinventory/credentials.go b/internal/namespaceinventory/credentials.go index 7b8164a911..fe8a6b4392 100644 --- a/internal/namespaceinventory/credentials.go +++ b/internal/namespaceinventory/credentials.go @@ -66,6 +66,41 @@ func LoadProtectedClient(getenv func(string) string) (*http.Client, *url.URL, er return newProductionClient(config) } +var emailRecoveryCredentialPath = regexp.MustCompile(`^/dev/shm/email-data-recovery\.[A-Za-z0-9]+/kubeconfig$`) + +// LoadEmailRecoveryClient reads only the private memory-backed credential of +// the confirmed first-attempt Email recovery dispatch. It shares credential +// validation, never authorization, with the benchmark observer. +func LoadEmailRecoveryClient(getenv func(string) string) (*http.Client, *url.URL, error) { + for key, want := range map[string]string{ + "GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/main", + "GITHUB_REPOSITORY": "devantler-tech/platform", "GITHUB_RUN_ATTEMPT": "1", "RUNNER_ENVIRONMENT": "github-hosted", + "GITHUB_ACTOR": "devantler", + "GITHUB_WORKFLOW_REF": "devantler-tech/platform/.github/workflows/verify-email-data-recovery.yaml@refs/heads/main", + "EMAIL_DATA_RECOVERY_CONFIRM": "verify-email-data-recovery", + } { + if getenv(key) != want { + return nil, nil, errors.New("protected Email recovery dispatch is unverified") + } + } + if !sourcePattern.MatchString(getenv("GITHUB_SHA")) || !runPattern.MatchString(getenv("GITHUB_RUN_ID")) { + return nil, nil, errors.New("email recovery source and run are required") + } + path := getenv("KUBECONFIG") + if !emailRecoveryCredentialPath.MatchString(path) || filepath.Clean(path) != path { + return nil, nil, errors.New("fixed private Email recovery kubeconfig is required") + } + raw, err := readPrivateKubeconfig(path) + if err != nil { + return nil, nil, err + } + config, err := clientcmd.Load(raw) + if err != nil { + return nil, nil, errors.New("protected Email recovery kubeconfig could not be decoded") + } + return newProductionClient(config) +} + // LoadBenchmarkAdmissionClient admits the protected V1 benchmark, native seed, // or the explicitly confirmed recovery of originalRun. The caller must first // join the selected address to its serving process and verified Hetzner server. diff --git a/internal/namespaceinventory/credentials_test.go b/internal/namespaceinventory/credentials_test.go index 2693d00d8f..2b127fc147 100644 --- a/internal/namespaceinventory/credentials_test.go +++ b/internal/namespaceinventory/credentials_test.go @@ -131,6 +131,69 @@ func TestCredentialLoaderRefusesOutsideProtectedDispatch(t *testing.T) { } } +func emailRecoveryDispatch() map[string]string { + return map[string]string{ + "GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/main", + "GITHUB_REPOSITORY": "devantler-tech/platform", "GITHUB_RUN_ATTEMPT": "1", "RUNNER_ENVIRONMENT": "github-hosted", + "GITHUB_ACTOR": "devantler", + "GITHUB_WORKFLOW_REF": "devantler-tech/platform/.github/workflows/verify-email-data-recovery.yaml@refs/heads/main", + "EMAIL_DATA_RECOVERY_CONFIRM": "verify-email-data-recovery", + "GITHUB_SHA": "0123456789abcdef0123456789abcdef01234567", "GITHUB_RUN_ID": "45123456789", + "KUBECONFIG": "/dev/shm/email-data-recovery.Ab12Cd34/kubeconfig", + } +} + +// The Email loader admits only its own confirmed dispatch and private path; +// every refusal happens before a credential file is read. +func TestEmailRecoveryLoaderRefusesOutsideItsConfirmedDispatch(t *testing.T) { + for _, change := range []struct{ key, value string }{ + {"GITHUB_WORKFLOW_REF", "devantler-tech/platform/.github/workflows/observe-longhorn-namespace-inventory.yaml@refs/heads/main"}, + {"GITHUB_ACTOR", "another"}, + {"GITHUB_RUN_ATTEMPT", "2"}, + {"EMAIL_DATA_RECOVERY_CONFIRM", "observe-email-data-recovery"}, + {"GITHUB_SHA", "main"}, + {"KUBECONFIG", "/dev/shm/longhorn-namespace-inventory.Ab12Cd34/kubeconfig"}, + {"KUBECONFIG", "/dev/shm/email-data-recovery.Ab12Cd34/../kubeconfig"}, + } { + env := emailRecoveryDispatch() + env[change.key] = change.value + if client, _, err := LoadEmailRecoveryClient(func(key string) string { return env[key] }); err == nil || client != nil { + t.Fatalf("Email loader admitted %s=%s", change.key, change.value) + } + } +} + +func TestEmailRecoveryLoaderBuildsTheFixedClient(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("the protected credential directory is Linux memory-backed storage") + } + server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("loader contacted an API") })) + t.Cleanup(server.Close) + directory, err := os.MkdirTemp("/dev/shm", "email-data-recovery.") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := os.RemoveAll(directory); err != nil { + t.Error(err) + } + }) + raw, err := clientcmd.Write(*fixtureConfig(server)) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(directory, "kubeconfig") + if err := os.WriteFile(path, raw, 0600); err != nil { + t.Fatal(err) + } + env := emailRecoveryDispatch() + env["KUBECONFIG"] = path + client, endpoint, err := LoadEmailRecoveryClient(func(key string) string { return env[key] }) + if err != nil || client == nil || endpoint == nil || endpoint.String() != server.URL { + t.Fatal("confirmed Email dispatch could not construct its fixed client:", err) + } +} + func TestBenchmarkDirectClientPinsAddressAndNeverFollowsRedirect(t *testing.T) { server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("the old endpoint must not receive direct-client credentials") diff --git a/internal/namespaceinventory/inventory.go b/internal/namespaceinventory/inventory.go index 5c876cf0ed..721a4f12f9 100644 --- a/internal/namespaceinventory/inventory.go +++ b/internal/namespaceinventory/inventory.go @@ -19,8 +19,12 @@ type Binding struct{ Name, Namespace, UID, Kind, Resource string } // Inventory holds the observed bindings. They remain private until a caller // explicitly copies them into its private journal. Default JSON serialization -// never publishes object identities. -type Inventory struct{ bindings map[string]Binding } +// never publishes object identities. Accepted Kubescape scan records are kept +// apart by resource and name, since the storage omits some of their UIDs. +type Inventory struct { + bindings map[string]Binding + scanRecords map[string]string +} // Bindings returns a copy of the observed bindings ordered by UID. func (i Inventory) Bindings() []Binding { @@ -101,24 +105,27 @@ func CalibrateLonghornSystem(ctx context.Context, client *http.Client, endpoint return result, nil } -// ObserveRetainedEmailRecovery inventories only the fixed retained diagnostic -// copy. A complete inventory alone never authorizes removing any resource. -func ObserveRetainedEmailRecovery(ctx context.Context, client *http.Client, endpoint *url.URL, uid string) (Inventory, error) { - return observeNamespace(ctx, client, endpoint, "email-data-recovery-41561215415", uid) +// ObserveEmailRecovery inventories one fresh Email recovery namespace. It also +// reads the scan records Kubescape's aggregated storage keeps there, accepting +// only the exact registration and record kinds in scan_records.go. A complete +// inventory alone never authorizes removing any resource. +func ObserveEmailRecovery(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string) (Inventory, error) { + if !emailRecoveryPattern.MatchString(namespace) { + return Inventory{}, errors.New("a fresh Email recovery namespace is required") + } + return observeNamespaceWith(ctx, client, endpoint, namespace, uid, true) } -// ObserveFreshRetainedEmailRecovery inventories the fixed fresh restore with -// its separately witnessed namespace identity. -func ObserveFreshRetainedEmailRecovery(ctx context.Context, client *http.Client, endpoint *url.URL, uid string) (Inventory, error) { - return observeNamespace(ctx, client, endpoint, "email-data-recovery-42818236850", uid) +func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string) (Inventory, error) { + return observeNamespaceWith(ctx, client, endpoint, namespace, uid, false) } -func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string) (Inventory, error) { +func observeNamespaceWith(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string, scanRecords bool) (Inventory, error) { if endpoint == nil { return Inventory{}, errors.New("authenticated API root is required") } root := *endpoint - fixed := namespace == "longhorn-system" || namespace == "email-data-recovery-41561215415" || namespace == "email-data-recovery-42818236850" + fixed := namespace == "longhorn-system" || (scanRecords && emailRecoveryPattern.MatchString(namespace)) if client == nil || root.Scheme != "https" || root.Host == "" || root.Opaque != "" || root.ForceQuery || root.User != nil || root.RawQuery != "" || root.Fragment != "" || (root.Path != "" && root.Path != "/") || (!namespacePattern.MatchString(namespace) && !fixed) || len(namespace) > 63 || uid == "" || len(uid) > 128 { return Inventory{}, errors.New("fixed benchmark namespace and authenticated API root are required") } @@ -127,7 +134,7 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR if err := observationActive(ctx); err != nil { return Inventory{}, err } - r := reader{client: *client, endpoint: &root, namespace: namespace, uid: uid} + r := reader{client: *client, endpoint: &root, namespace: namespace, uid: uid, scanRecords: scanRecords} r.client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } if r.client.Timeout == 0 || r.client.Timeout > 20*time.Second { r.client.Timeout = 20 * time.Second @@ -143,14 +150,17 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR if err != nil { return Inventory{}, err } - result := Inventory{bindings: map[string]Binding{}} + result := Inventory{bindings: map[string]Binding{}, scanRecords: map[string]string{}} for _, resource := range resources.resources { raw, err := r.get(ctx, resource.prefix+"/namespaces/"+namespace+"/"+resource.name, metadataListAccept) if err != nil { return Inventory{}, err } + // Kubescape's storage sets no list resourceVersion; a continuation or + // remainder still marks its collection as partial. + records := r.scanRecords && resource.prefix == "/apis/"+scanGroupVersion var actual partialList - if decode(raw, &actual, metadataFields) != nil || actual.APIVersion != "meta.k8s.io/v1" || actual.Kind != "PartialObjectMetadataList" || actual.Metadata.ResourceVersion == "" || actual.Metadata.Continue != "" || actual.Metadata.Remaining != nil && *actual.Metadata.Remaining != 0 || actual.Items == nil { + if decode(raw, &actual, metadataFields) != nil || actual.APIVersion != "meta.k8s.io/v1" || actual.Kind != "PartialObjectMetadataList" || (actual.Metadata.ResourceVersion == "" && !records) || actual.Metadata.Continue != "" || actual.Metadata.Remaining != nil && *actual.Metadata.Remaining != 0 || actual.Items == nil { return Inventory{}, errors.New("namespace collection is partial or not metadata-only") } // The native metadata converter leaves Items nil for a complete empty @@ -159,6 +169,12 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR if json.Unmarshal(actual.Items, &items) != nil { return Inventory{}, errors.New("namespace collection items are malformed") } + if records { + if err := scanRecordList(resource, namespace, items, result.scanRecords); err != nil { + return Inventory{}, err + } + continue + } seenItems := map[string]bool{} for _, item := range items { m := item.Metadata @@ -185,6 +201,9 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR result.bindings[m.UID] = binding } } + if err := scanRecordsComplete(result.scanRecords); err != nil { + return Inventory{}, err + } checked, err := r.discovery(ctx) if err != nil || !reflect.DeepEqual(checked, resources) { return Inventory{}, errors.New("served namespace resources changed during inventory") diff --git a/internal/namespaceinventory/inventory_test.go b/internal/namespaceinventory/inventory_test.go index 60995894a6..83b6ed7f57 100644 --- a/internal/namespaceinventory/inventory_test.go +++ b/internal/namespaceinventory/inventory_test.go @@ -81,50 +81,74 @@ func TestFixedLonghornCalibrationReadsMetadataWithoutRetirementAuthority(t *test } } -func TestRetainedEmailInventoryCoversAllServedKinds(t *testing.T) { - result, err := observeFixtureInNamespace(t, "", "email-data-recovery-41561215415") +const testEmailNamespace = "email-data-recovery-45123456789" + +func TestEmailInventoryCoversAllServedKinds(t *testing.T) { + result, err := observeFixtureInNamespace(t, "", testEmailNamespace) if err != nil || len(result.Bindings()) != 2 { - t.Fatalf("fixed Email inventory failed: %v", err) + t.Fatalf("Email inventory failed: %v", err) } - for _, failure := range []string{"continued list", "changed discovery", "namespace replaced", "full Secret response", "duplicate UID"} { - result, err = observeFixtureInNamespace(t, failure, "email-data-recovery-41561215415") + for _, failure := range []string{"continued list", "changed discovery", "namespace replaced", "full Secret response", "duplicate UID", "remote deletable API"} { + result, err = observeFixtureInNamespace(t, failure, testEmailNamespace) if err == nil || len(result.Bindings()) != 0 { t.Fatalf("incomplete Email inventory accepted: %s", failure) } } - if result, err = Observe(context.Background(), nil, nil, "email-data-recovery-41561215416", "uid"); err == nil || len(result.Bindings()) != 0 { - t.Fatal("arbitrary Email namespace admitted by general benchmark API") - } -} - -func TestFreshRetainedEmailInventoryHasItsOwnFixedNamespace(t *testing.T) { - const namespace = "email-data-recovery-42818236850" - result, err := observeFixtureInNamespace(t, "", namespace) - if err != nil || len(result.Bindings()) != 2 { - t.Fatalf("fixed fresh Email inventory failed: %v", err) - } - result, err = observeFixtureInNamespace(t, "namespace replaced", namespace) - if err == nil || len(result.Bindings()) != 0 { - t.Fatal("a replaced fresh namespace was accepted") - } requests := 0 client := &http.Client{Transport: transportFunc(func(*http.Request) (*http.Response, error) { requests++ return nil, errors.New("unexpected request") })} endpoint := &url.URL{Scheme: "https", Host: "reviewed.invalid"} - if namespacePattern.MatchString(namespace) { - t.Fatal("fresh recovery namespace overlaps the benchmark namespace grammar") + for _, namespace := range []string{"email-data-recovery-123456", "email-data-recovery-0123456789", "email-data-recovery-1234567x", "longhorn-system", testNamespace} { + if result, err = ObserveEmailRecovery(context.Background(), client, endpoint, namespace, "uid"); err == nil || requests != 0 || len(result.Bindings()) != 0 { + t.Fatalf("a namespace outside the Email recovery grammar was admitted: %s", namespace) + } + } + if namespacePattern.MatchString(testEmailNamespace) { + t.Fatal("Email recovery namespace overlaps the benchmark namespace grammar") + } + if result, err = Observe(context.Background(), client, endpoint, testEmailNamespace, "uid"); err == nil || requests != 0 || len(result.Bindings()) != 0 { + t.Fatal("Email namespace admitted by the benchmark API") } - if result, err = Observe(context.Background(), client, endpoint, namespace, "uid"); err == nil || requests != 0 || len(result.Bindings()) != 0 { - t.Fatal("fresh namespace admitted by the benchmark API") +} + +// Kubescape's storage is a remote API backend. Only an Email recovery +// inventory accepts its exact registration and record kinds; its profile +// records carry no UID and its computed views no version. +func TestEmailInventoryAcceptsOnlyKubescapeScanRecords(t *testing.T) { + result, err := observeFixtureInNamespace(t, "scan records", testEmailNamespace) + if err != nil || len(result.Bindings()) != 2 || len(result.scanRecords) != 3 { + t.Fatalf("Kubescape scan records prevented a complete Email inventory: bindings=%d records=%d error=%v", len(result.Bindings()), len(result.scanRecords), err) + } + for _, failure := range []string{"scan records from another service", "scan records under another version", "scan image record", "scan record of a mislabelled kind", "scan continued list", "scan foreign namespace", "scan record without version", "scan duplicate record", "scan view without source"} { + t.Run(failure, func(t *testing.T) { + result, err := observeFixtureInNamespace(t, failure, testEmailNamespace) + if err == nil || len(result.Bindings()) != 0 || len(result.scanRecords) != 0 { + t.Fatal("an unaccepted scan record or registration was admitted") + } + }) + } + if result, err = observeFixture(t, "scan records"); err == nil || len(result.Bindings()) != 0 { + t.Fatal("the benchmark inventory admitted a remote API backend") + } +} + +// productionCollections makes one fixture inventory need about 614 reads, +// above the 576 production needed on 2026-11-25 (see requestLimit). +const productionCollections = 600 + +func TestInventoryCompletesOnAProductionSizedAPI(t *testing.T) { + result, err := observeFixtureInNamespace(t, "production-sized discovery", testEmailNamespace) + if err != nil || len(result.Bindings()) != 2 { + t.Fatalf("a production-sized API exceeded the inventory bounds: %v", err) } } // One stored Event is served by core v1 and events.k8s.io under the same UID. // That alias is one object; any other identity difference stays a conflict. func TestEventAliasesAreOneObject(t *testing.T) { - result, err := observeFixtureInNamespace(t, "event alias", "email-data-recovery-41561215415") + result, err := observeFixtureInNamespace(t, "event alias", testEmailNamespace) if err != nil { t.Fatalf("Event aliases were read as conflicting identities: %v", err) } @@ -137,7 +161,7 @@ func TestEventAliasesAreOneObject(t *testing.T) { if len(result.Bindings()) != 3 || events != 1 { t.Fatalf("want secret, widget and one Event, got %d bindings with %d Events", len(result.Bindings()), events) } - if result, err = observeFixtureInNamespace(t, "event alias renamed", "email-data-recovery-41561215415"); err == nil || len(result.Bindings()) != 0 { + if result, err = observeFixtureInNamespace(t, "event alias renamed", testEmailNamespace); err == nil || len(result.Bindings()) != 0 { t.Fatal("two different Events with one UID were accepted") } } @@ -164,6 +188,10 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento expires := &atomic.Int64{} expires.Store(time.Now().Add(time.Minute).UnixNano()) seen := map[string]int{} + scanFixture, scanVersion := strings.HasPrefix(failure, "scan"), "v1beta1" + if failure == "scan records under another version" { + scanVersion = "v1beta2" + } server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { respond := func(body string) { if _, err := fmt.Fprint(w, body); err != nil && failure == "" { @@ -189,7 +217,72 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento if failure == "remote deletable API" { service = `,"service":{"name":"remote","namespace":"system"}` } - respond(fmt.Sprintf(`{"apiVersion":"apiregistration.k8s.io/v1","kind":"APIServiceList","metadata":{"resourceVersion":"1","continue":%q},"items":[{"metadata":{"name":"v1.example.io","uid":"api-service","resourceVersion":%q},"spec":{"group":"example.io","version":"v1"%s}}]}`, continuation, rv, service)) + scan := "" + if scanFixture { + scanService := "storage" + if failure == "scan records from another service" { + scanService = "other" + } + scan = fmt.Sprintf(`,{"metadata":{"name":"%s.spdx.softwarecomposition.kubescape.io","uid":"scan-service","resourceVersion":"3"},"spec":{"group":"spdx.softwarecomposition.kubescape.io","version":%q,"service":{"name":%q,"namespace":"kubescape"}}}`, scanVersion, scanVersion, scanService) + } + respond(fmt.Sprintf(`{"apiVersion":"apiregistration.k8s.io/v1","kind":"APIServiceList","metadata":{"resourceVersion":"1","continue":%q},"items":[{"metadata":{"name":"v1.example.io","uid":"api-service","resourceVersion":%q},"spec":{"group":"example.io","version":"v1"%s}}%s]}`, continuation, rv, service, scan)) + return + } + scanPrefix := "/apis/spdx.softwarecomposition.kubescape.io/" + scanVersion + if scanFixture && r.URL.Path == scanPrefix { + profileKind := "ContainerProfile" + if failure == "scan record of a mislabelled kind" { + profileKind = "SBOMSyft" + } + respond(fmt.Sprintf(`{"apiVersion":"v1","kind":"APIResourceList","groupVersion":"spdx.softwarecomposition.kubescape.io/%s","resources":[{"name":"containerprofiles","kind":%q,"namespaced":true,"verbs":["get","list","delete"]},{"name":"networkneighborhoods","kind":"NetworkNeighborhood","namespaced":true,"verbs":["get","list","delete"]},{"name":"generatednetworkpolicies","kind":"GeneratedNetworkPolicy","namespaced":true,"verbs":["get","list","delete"]},{"name":"sbomsyfts","kind":"SBOMSyft","namespaced":true,"verbs":["get","list","delete"]}]}`, scanVersion, profileKind)) + return + } + if scanFixture && strings.HasPrefix(r.URL.Path, scanPrefix+"/namespaces/"+testNamespace+"/") { + if r.Header.Get("Accept") != metadataListAccept || r.URL.RawQuery != "limit=256" { + t.Error("scan record read was not fixed, complete and metadata-only") + } + // Hand-checked shapes from the production storage: no list version, + // no UID on profile records, neither UID nor version on a computed view. + resource := strings.TrimPrefix(r.URL.Path, scanPrefix+"/namespaces/"+testNamespace+"/") + item := func(name, namespace, version string) string { + if version != "" { + version = fmt.Sprintf(`,"resourceVersion":%q`, version) + } + return fmt.Sprintf(`{"apiVersion":"meta.k8s.io/v1","kind":"PartialObjectMetadata","metadata":{"name":%q,"namespace":%q%s,"labels":{"kubescape.io/workload-name":"reader"}}}`, name, namespace, version) + } + listMetadata, items := "{}", []string{} + switch resource { + case "containerprofiles": + namespace, version := testNamespace, "5" + if failure == "scan foreign namespace" { + namespace = "another" + } + if failure == "scan record without version" { + version = "" + } + items = append(items, item("pod-reader-reader", namespace, version)) + if failure == "scan duplicate record" { + items = append(items, item("pod-reader-reader", namespace, version)) + } + if failure == "scan continued list" { + listMetadata = `{"continue":"2165703"}` + } + case "networkneighborhoods": + items = append(items, item("pod-reader", testNamespace, "6")) + case "generatednetworkpolicies": + name := "pod-reader" + if failure == "scan view without source" { + name = "pod-other" + } + items = append(items, item(name, testNamespace, "")) + case "sbomsyfts": + if failure == "scan image record" { + items = append(items, item("image-digest", testNamespace, "7")) + } + default: + t.Errorf("unapproved scan record target: %s", r.URL.Path) + } + respond(fmt.Sprintf(`{"apiVersion":"meta.k8s.io/v1","kind":"PartialObjectMetadataList","metadata":%s,"items":[%s]}`, listMetadata, strings.Join(items, ","))) return } if r.URL.Path == "/api/v1/namespaces/"+testNamespace { @@ -225,6 +318,9 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento if strings.HasPrefix(failure, "event alias") { events = `,{"name":"events.k8s.io","versions":[{"groupVersion":"events.k8s.io/v1","version":"v1"}]}` } + if scanFixture { + events += fmt.Sprintf(`,{"name":"spdx.softwarecomposition.kubescape.io","versions":[{"groupVersion":"spdx.softwarecomposition.kubescape.io/%s","version":%q}]}`, scanVersion, scanVersion) + } respond(`{"apiVersion":"v1","kind":"APIGroupList","groups":[{"name":"example.io","versions":[{"groupVersion":"example.io/v1","version":"v1"},{"groupVersion":"example.io/v2","version":"v2"}]}` + events + `]}`) return } @@ -261,6 +357,13 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento if strings.HasPrefix(failure, "event alias") && gv == "v1" { body = strings.Replace(body, `"resources":[`, `"resources":[{"name":"events","kind":"Event","namespaced":true,"verbs":["get","list","delete"]},`, 1) } + if failure == "production-sized discovery" && gv == "v1" { + var many strings.Builder + for index := range productionCollections { + fmt.Fprintf(&many, `{"name":"things%d","kind":"Thing%d","namespaced":true,"verbs":["get","list","delete"]},`, index, index) + } + body = strings.Replace(body, `"resources":[`, `"resources":[`+many.String(), 1) + } respond(body) return } @@ -280,7 +383,7 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento respond(`{"apiVersion":"v1","kind":"SecretList","metadata":{"resourceVersion":"8"},"items":[]}`) return } - if failure == "native empty list" { + if failure == "native empty list" || (failure == "production-sized discovery" && strings.Contains(r.URL.Path, "/things")) { respond(`{"apiVersion":"meta.k8s.io/v1","kind":"PartialObjectMetadataList","metadata":{"resourceVersion":"8"},"items":null}`) return } @@ -337,10 +440,8 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento switch namespace { case "longhorn-system": result, err = CalibrateLonghornSystem(ctx, server.Client(), endpoint, "namespace-uid") - case "email-data-recovery-41561215415": - result, err = ObserveRetainedEmailRecovery(ctx, server.Client(), endpoint, "namespace-uid") - case "email-data-recovery-42818236850": - result, err = ObserveFreshRetainedEmailRecovery(ctx, server.Client(), endpoint, "namespace-uid") + case testEmailNamespace: + result, err = ObserveEmailRecovery(ctx, server.Client(), endpoint, namespace, "namespace-uid") default: result, err = Observe(ctx, server.Client(), endpoint, testNamespace, "namespace-uid") } diff --git a/internal/namespaceinventory/scan_records.go b/internal/namespaceinventory/scan_records.go new file mode 100644 index 0000000000..77a68c820d --- /dev/null +++ b/internal/namespaceinventory/scan_records.go @@ -0,0 +1,82 @@ +package namespaceinventory + +import ( + "errors" + "regexp" +) + +// emailRecoveryPattern is the namespace of one fresh Email recovery invocation, +// named after its workflow run. +var emailRecoveryPattern = regexp.MustCompile(`^email-data-recovery-[1-9][0-9]{6,19}$`) + +// Kubescape's storage serves the scan records it keeps about each namespace's +// objects through one remotely aggregated API. They are derived from objects in +// the namespace and are removed with it. Only this exact registration and these +// record kinds are accepted, and only for an Email recovery namespace. +const ( + scanGroup = "spdx.softwarecomposition.kubescape.io" + scanVersion = "v1beta1" + scanGroupVersion = scanGroup + "/" + scanVersion + scanService = "storage" + scanNamespace = "kubescape" +) + +// scanRecordKinds maps each accepted record resource to its kind. The storage's +// other namespaced resources (SBOMs, vulnerability manifests and VEX documents) +// describe images and belong to the Kubescape namespace, so an item there is +// refused rather than accepted as a scan record. +var scanRecordKinds = map[string]string{ + "applicationprofiles": "ApplicationProfile", + "containerprofiles": "ContainerProfile", + "generatednetworkpolicies": "GeneratedNetworkPolicy", + "networkneighborhoods": "NetworkNeighborhood", + "vulnerabilitymanifestsummaries": "VulnerabilityManifestSummary", + "workloadconfigurationscans": "WorkloadConfigurationScan", + "workloadconfigurationscansummaries": "WorkloadConfigurationScanSummary", +} + +// scanStorage reports the one accepted remote registration. +func scanStorage(item apiService) bool { + s := item.Spec.Service + return item.Metadata.Name == scanVersion+"."+scanGroup && item.Spec.Group == scanGroup && item.Spec.Version == scanVersion && + s != nil && s.Name == scanService && s.Namespace == scanNamespace +} + +// scanRecordList validates one metadata-only Kubescape collection. The storage +// sets no list resourceVersion, and it omits UIDs on its profile records, so +// these records are bound by resource and name, never adopted as bindings. +// GeneratedNetworkPolicy items are computed views with no stored version; each +// must mirror a NetworkNeighborhood record of the same name. +func scanRecordList(resource servedResource, namespace string, items []partialObject, records map[string]string) error { + kind, accepted := scanRecordKinds[resource.name] + if len(items) == 0 { + return nil + } + if !accepted || resource.kind != kind { + return errors.New("namespace holds a scan record of an unaccepted kind") + } + for _, item := range items { + m := item.Metadata + key := resource.name + "/" + m.Name + if item.APIVersion != "meta.k8s.io/v1" || item.Kind != "PartialObjectMetadata" || m.Namespace != namespace || len(m.Name) > 253 || !namePattern.MatchString(m.Name) || len(m.UID) > 128 || (m.ResourceVersion == "" && resource.name != "generatednetworkpolicies") || records[key] != "" { + return errors.New("namespace scan record identity is incomplete") + } + records[key] = kind + } + return nil +} + +// scanRecordsComplete requires every computed network policy view to mirror a +// stored NetworkNeighborhood, after every collection was read. +func scanRecordsComplete(records map[string]string) error { + for key, kind := range records { + if kind != "GeneratedNetworkPolicy" { + continue + } + name := key[len("generatednetworkpolicies/"):] + if records["networkneighborhoods/"+name] != "NetworkNeighborhood" { + return errors.New("a computed scan record has no stored source") + } + } + return nil +} diff --git a/internal/namespaceinventory/transport.go b/internal/namespaceinventory/transport.go index 82e4a2d619..b07e9f3f80 100644 --- a/internal/namespaceinventory/transport.go +++ b/internal/namespaceinventory/transport.go @@ -16,7 +16,11 @@ const metadataObjectAccept = "application/json;as=PartialObjectMetadata;g=meta.k const metadataListAccept = "application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1" const responseLimit = 1024 * 1024 const totalLimit = 16 * 1024 * 1024 -const requestLimit = 512 + +// requestLimit bounds one observation. Production needed 576 reads on +// 2026-11-25: two discovery passes over 128 served versions (130 reads each), +// 312 namespaced collections, and four namespace and APIService reads. +const requestLimit = 1024 var namespacePattern = regexp.MustCompile(`^longhorn-benchmark-(v1|v2)-[1-9][0-9]{0,18}$`) var namePattern = regexp.MustCompile(`^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$`) @@ -28,6 +32,8 @@ type reader struct { endpoint *url.URL namespace, uid string requests, bytes int + // scanRecords admits Kubescape's storage registration and its records. + scanRecords bool } func observationActive(ctx context.Context) error { diff --git a/scripts/verify-email-data-recovery/README.md b/scripts/verify-email-data-recovery/README.md index f1186ba09a..f67fa6ae2b 100644 --- a/scripts/verify-email-data-recovery/README.md +++ b/scripts/verify-email-data-recovery/README.md @@ -42,6 +42,25 @@ Cleanup recognizes only the four platform-generated network policies whose specs match this checkout and whose Kyverno labels name the created namespace UID and expected rule. Standard and Cilium policies are both inventoried; unknown policies or changed specs retain the namespace and recovery key. +It also recognizes what the platform adds to every namespace: Kyverno's +`default-limitrange` and `default-resourcequota`, bound by their generate +labels to the created namespace UID and to the `add-default-limitrange` and +`add-ns-quota` rules, and trust-manager's `cloudflare-origin-ca` ConfigMap, +bound to its controlling Bundle's UID with its single CA key. + +Before every disposal step that could remove the namespace, the driver also +reads its complete inventory: every namespaced, deletable resource of every +served API version, metadata only, through the dispatch's private credential. +Each object must be one this invocation created, with its created UID, or one +of the platform objects above. Runtime records about those objects are +accepted by exact kind and served resource: Events, Kyverno policy and +ephemeral reports named after a known object's UID, and Cilium's endpoint for +the created reader. Kubescape's storage is a remote aggregated API; only its +exact `v1beta1.spdx.softwarecomposition.kubescape.io` registration, backed by +`kubescape/storage`, and its workload scan-record kinds are accepted, and only +for this invocation's namespace. Any other object, kind, registration or failed +read retains the namespace and its key. Without the private credential no +recovery starts. Any failed, ambiguous or interrupted operation is unverified. The driver retains uncertain resources and keys for inspection instead of retrying, adopting a diff --git a/scripts/verify-email-data-recovery/cleanup.go b/scripts/verify-email-data-recovery/cleanup.go index e14205bd92..61d85976ac 100644 --- a/scripts/verify-email-data-recovery/cleanup.go +++ b/scripts/verify-email-data-recovery/cleanup.go @@ -232,7 +232,7 @@ func (d *recoveryDriver) namespaceInventory(ctx context.Context) error { return err } } - resources, err := d.list(ctx, "pods,persistentvolumeclaims,secrets,configmaps,services,serviceaccounts,deployments.apps,statefulsets.apps,daemonsets.apps,jobs.batch,cronjobs.batch,ciliumnetworkpolicies.cilium.io,networkpolicies.networking.k8s.io", d.i.namespace, "") + resources, err := d.list(ctx, "pods,persistentvolumeclaims,secrets,configmaps,services,serviceaccounts,deployments.apps,statefulsets.apps,daemonsets.apps,jobs.batch,cronjobs.batch,ciliumnetworkpolicies.cilium.io,networkpolicies.networking.k8s.io,limitranges,resourcequotas", d.i.namespace, "") if err != nil { return err } @@ -248,6 +248,15 @@ func (d *recoveryDriver) namespaceInventory(ctx context.Context) error { if policy, ok := d.namespacePolicies[kind+"/"+name]; ok && policy.matches(o, namespace.uid) { continue } + if generatedLimit(o, namespace.uid) { + continue + } + if kind == "ConfigMap" && name == trustBundle { + bundle, found, e := d.lookup(ctx, "bundles.trust.cert-manager.io", trustBundle, "") + if e == nil && found && text(child(bundle, "metadata"), "name") == trustBundle && trustBundleConfigMap(o, text(child(bundle, "metadata"), "uid")) { + continue + } + } ref, e := d.ref(kind, name, d.i.namespace) if e != nil || text(m, "uid") != ref.uid || text(child(m, "labels"), recoveryLabel) != d.i.run { return errors.New("foreign-namespace-resource") diff --git a/scripts/verify-email-data-recovery/cleanup_test.go b/scripts/verify-email-data-recovery/cleanup_test.go index 049ea19001..d70f243e19 100644 --- a/scripts/verify-email-data-recovery/cleanup_test.go +++ b/scripts/verify-email-data-recovery/cleanup_test.go @@ -32,7 +32,7 @@ func (a *cleanupAPI) call(_ context.Context, input []byte, args ...string) ([]by } if strings.Contains(kind, ",") { out := []any{} - resourceNames := map[string]string{"Pod": "pods", "PersistentVolumeClaim": "persistentvolumeclaims", "Secret": "secrets", "ConfigMap": "configmaps", "Service": "services", "ServiceAccount": "serviceaccounts", "Deployment": "deployments.apps", "StatefulSet": "statefulsets.apps", "DaemonSet": "daemonsets.apps", "Job": "jobs.batch", "CronJob": "cronjobs.batch", "CiliumNetworkPolicy": "ciliumnetworkpolicies.cilium.io", "NetworkPolicy": "networkpolicies.networking.k8s.io"} + resourceNames := map[string]string{"Pod": "pods", "PersistentVolumeClaim": "persistentvolumeclaims", "Secret": "secrets", "ConfigMap": "configmaps", "Service": "services", "ServiceAccount": "serviceaccounts", "Deployment": "deployments.apps", "StatefulSet": "statefulsets.apps", "DaemonSet": "daemonsets.apps", "Job": "jobs.batch", "CronJob": "cronjobs.batch", "CiliumNetworkPolicy": "ciliumnetworkpolicies.cilium.io", "NetworkPolicy": "networkpolicies.networking.k8s.io", "LimitRange": "limitranges", "ResourceQuota": "resourcequotas"} for _, o := range a.objects { if resource, known := resourceNames[text(o, "kind")]; known && text(child(o, "metadata"), "namespace") == ns && strings.Contains(","+kind+",", ","+resource+",") { out = append(out, o) diff --git a/scripts/verify-email-data-recovery/complete_inventory.go b/scripts/verify-email-data-recovery/complete_inventory.go new file mode 100644 index 0000000000..937adc11f2 --- /dev/null +++ b/scripts/verify-email-data-recovery/complete_inventory.go @@ -0,0 +1,143 @@ +package main + +import ( + "context" + "errors" + "regexp" + + "github.com/devantler-tech/platform/internal/namespaceinventory" +) + +// ownedResources is the served resource of each kind this invocation creates +// in its namespace. +var ownedResources = map[string]string{"Pod": "pods", "PersistentVolumeClaim": "persistentvolumeclaims", "Secret": "secrets", "ConfigMap": "configmaps", "CiliumNetworkPolicy": "ciliumnetworkpolicies.cilium.io"} + +var ephemeralReportName = regexp.MustCompile(`^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-[a-z0-9]{5}$`) + +// useCompleteInventory binds the complete namespace inventory to the confirmed +// dispatch's private credential. It reads nothing until cleanup asks for it. +func (d *recoveryDriver) useCompleteInventory(env func(string) string) error { + client, endpoint, err := namespaceinventory.LoadEmailRecoveryClient(env) + if err != nil { + return errors.New("inventory-credential") + } + d.completeNamespaceInventory = func(ctx context.Context) error { + namespace, err := d.ref("Namespace", d.i.namespace, "") + if err != nil { + return err + } + inventory, err := namespaceinventory.ObserveEmailRecovery(ctx, client, endpoint, d.i.namespace, namespace.uid) + if err != nil { + return errors.New("complete-inventory") + } + return d.classifyInventory(ctx, inventory.Bindings()) + } + return nil +} + +// classifyInventory accepts the complete set of objects the namespace serves +// only when each one is either created by this invocation with its created UID, +// or one of the exact objects the platform adds to every namespace. Kubescape's +// scan records were already accepted, by kind and group, by the inventory. A +// missing owned object means the inventory is not the namespace's. +func (d *recoveryDriver) classifyInventory(ctx context.Context, bindings []namespaceinventory.Binding) error { + // Reports may describe any object here or one this invocation created and + // removed; reports and events never vouch for each other. + known := map[string]bool{} + for uid := range d.created { + known[uid] = true + } + for _, b := range bindings { + if !inventoryRecord(b) { + known[b.UID] = true + } + } + seen := map[string]bool{} + for _, b := range bindings { + if b.Namespace != d.i.namespace || b.UID == "" { + return errors.New("inventory-foreign") + } + if b.Kind == "Event" && (b.Resource == "events" || b.Resource == "events.events.k8s.io") { + continue + } + key := ownedReference{kind: b.Kind, name: b.Name, namespace: b.Namespace}.key() + if seen[key] { + return errors.New("inventory-duplicate-name") + } + seen[key] = true + if ref, owned := d.refs[key]; owned { + if ref.uid != b.UID || ownedResources[b.Kind] != b.Resource { + return errors.New("inventory-replaced") + } + continue + } + accepted, err := d.platformObject(ctx, b, known) + if err != nil { + return err + } + if !accepted { + return errors.New("inventory-foreign") + } + } + for key, ref := range d.refs { + if ref.namespace == d.i.namespace && !seen[key] { + return errors.New("inventory-missing") + } + } + return nil +} + +// inventoryRecord reports kinds that only record facts about other objects. +func inventoryRecord(b namespaceinventory.Binding) bool { + return b.Kind == "Event" || b.Kind == "PolicyReport" || b.Kind == "EphemeralReport" +} + +// platformObject recognises what the platform adds to every namespace. Their +// contents are verified by the namespace's typed inventory; kinds here are +// matched with their served resource, never by name alone. +func (d *recoveryDriver) platformObject(ctx context.Context, b namespaceinventory.Binding, known map[string]bool) (bool, error) { + switch b.Kind + "/" + b.Resource { + case "ServiceAccount/serviceaccounts": + return b.Name == "default", nil + case "ConfigMap/configmaps": + return b.Name == "kube-root-ca.crt" || b.Name == trustBundle, nil + case "LimitRange/limitranges", "ResourceQuota/resourcequotas": + _, generated := generatedLimits[b.Kind+"/"+b.Name] + return generated, nil + case "CiliumNetworkPolicy/ciliumnetworkpolicies.cilium.io", "NetworkPolicy/networkpolicies.networking.k8s.io": + _, generated := d.namespacePolicies[b.Kind+"/"+b.Name] + return generated, nil + case "PolicyReport/policyreports.wgpolicyk8s.io": + // Kyverno names a report after the UID of the object it describes. + return known[b.Name], nil + case "EphemeralReport/ephemeralreports.reports.kyverno.io": + match := ephemeralReportName.FindStringSubmatch(b.Name) + return match != nil && known[match[1]], nil + case "CiliumEndpoint/ciliumendpoints.cilium.io": + return d.readerEndpoint(ctx, b) + } + return false, nil +} + +// readerEndpoint accepts Cilium's endpoint for this invocation's reader Pod +// only, bound by its owner's created UID, which outlives the Pod's removal. +func (d *recoveryDriver) readerEndpoint(ctx context.Context, b namespaceinventory.Binding) (bool, error) { + if b.Name != "reader" { + return false, nil + } + endpoint, found, err := d.lookup(ctx, "ciliumendpoints.cilium.io", b.Name, b.Namespace) + if err != nil { + return false, errors.New("inventory-endpoint") + } + if !found { + // Removed after the complete read; a later inventory sees it absent. + return true, nil + } + m := child(endpoint, "metadata") + owners := items(m, "ownerReferences") + if text(endpoint, "apiVersion") != "cilium.io/v2" || text(endpoint, "kind") != "CiliumEndpoint" || text(m, "uid") != b.UID || len(owners) != 1 { + return false, nil + } + owner := owners[0] + return text(owner, "apiVersion") == "v1" && text(owner, "kind") == "Pod" && text(owner, "name") == "reader" && d.created[text(owner, "uid")], nil +} diff --git a/scripts/verify-email-data-recovery/complete_inventory_test.go b/scripts/verify-email-data-recovery/complete_inventory_test.go new file mode 100644 index 0000000000..1d5333f7bf --- /dev/null +++ b/scripts/verify-email-data-recovery/complete_inventory_test.go @@ -0,0 +1,351 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "strings" + "testing" + + "github.com/devantler-tech/platform/internal/namespaceinventory" + "gopkg.in/yaml.v3" +) + +const fixtureBundleUID = "f75759ba-2d74-4227-8033-a255cd544258" + +// platformNamespaceFixture holds what production adds to every namespace +// besides the four generated network policies, in the shapes read on +// 2026-11-25: Kyverno's LimitRange and ResourceQuota and trust-manager's CA +// bundle ConfigMap. +func platformNamespaceFixture(namespace, namespaceUID string) []object { + generated := func(policy, rule string) object { + return object{"app.kubernetes.io/managed-by": "kyverno", "generate.kyverno.io/policy-name": policy, "generate.kyverno.io/policy-namespace": "", "generate.kyverno.io/rule-name": rule, "generate.kyverno.io/trigger-group": "", "generate.kyverno.io/trigger-kind": "Namespace", "generate.kyverno.io/trigger-namespace": "", "generate.kyverno.io/trigger-uid": namespaceUID, "generate.kyverno.io/trigger-version": "v1"} + } + return []object{ + {"apiVersion": "v1", "kind": "LimitRange", "metadata": object{"name": "default-limitrange", "namespace": namespace, "uid": "generated-limitrange", "labels": generated("add-default-limitrange", "generate-limitrange"), "annotations": object{"generate.kyverno.io/provenance": "{}"}}, "spec": object{"limits": []any{object{"default": object{"cpu": "500m", "memory": "512Mi"}, "defaultRequest": object{"cpu": "15m", "memory": "128Mi"}, "type": "Container"}}}}, + {"apiVersion": "v1", "kind": "ResourceQuota", "metadata": object{"name": "default-resourcequota", "namespace": namespace, "uid": "generated-resourcequota", "labels": generated("add-ns-quota", "generate-resourcequota"), "annotations": object{"generate.kyverno.io/provenance": "{}"}}, "spec": object{"hard": object{"requests.cpu": "8", "requests.memory": "16Gi"}}, "status": object{}}, + {"apiVersion": "v1", "kind": "ConfigMap", "metadata": object{"name": "cloudflare-origin-ca", "namespace": namespace, "uid": "trust-bundle-configmap", "labels": object{"trust.cert-manager.io/bundle": "cloudflare-origin-ca"}, "annotations": object{"trust.cert-manager.io/hash": "fixture"}, "ownerReferences": []any{object{"apiVersion": "trust.cert-manager.io/v1alpha1", "kind": "Bundle", "name": "cloudflare-origin-ca", "uid": fixtureBundleUID, "controller": true, "blockOwnerDeletion": true}}}, "data": object{"ca-certificates.crt": "-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n"}}, + } +} + +// platformCleanupFixture adds every object the platform puts in a namespace. +func platformCleanupFixture(t *testing.T) (*recoveryDriver, *cleanupAPI, context.Context) { + t.Helper() + d, api, ctx := cleanupFixture(t, false) + namespace, _ := d.ref("Namespace", d.i.namespace, "") + objects := append(generatedNamespacePolicyFixture(d.i.namespace, namespace.uid), platformNamespaceFixture(d.i.namespace, namespace.uid)...) + for _, o := range objects { + api.objects[cleanupKey(text(o, "kind"), d.i.namespace, text(child(o, "metadata"), "name"))] = o + } + api.objects[cleanupKey("bundles.trust.cert-manager.io", "", trustBundle)] = object{"apiVersion": "trust.cert-manager.io/v1alpha1", "kind": "Bundle", "metadata": object{"name": trustBundle, "uid": fixtureBundleUID}} + return d, api, ctx +} + +func TestCleanupRecognizesWhatThePlatformAddsToEveryNamespace(t *testing.T) { + d, api, ctx := platformCleanupFixture(t) + if err := d.cleanupRestore(ctx); err != nil { + t.Fatalf("platform-generated objects prevented owned namespace disposal: %s", err) + } + if _, exists := api.objects[cleanupKey("Namespace", "", d.i.namespace)]; exists { + t.Fatal("the verified disposable namespace was retained") + } +} + +func TestCleanupRetainsChangedPlatformObjects(t *testing.T) { + limit := cleanupKey("LimitRange", "", "default-limitrange") + quota := cleanupKey("ResourceQuota", "", "default-resourcequota") + bundle := cleanupKey("ConfigMap", "", trustBundle) + mutations := map[string]struct { + target string + mutate func(object) + }{ + "limit-of-another-namespace": {limit, func(o object) { + child(child(o, "metadata"), "labels")["generate.kyverno.io/trigger-uid"] = "another-namespace-uid" + }}, + "limit-of-another-policy": {limit, func(o object) { + child(child(o, "metadata"), "labels")["generate.kyverno.io/policy-name"] = "add-ns-quota" + }}, + "limit-with-an-owner": {limit, func(o object) { + child(o, "metadata")["ownerReferences"] = []any{object{"apiVersion": "v1", "kind": "Pod", "name": "foreign", "uid": "foreign"}} + }}, + "limit-not-from-kyverno": {limit, func(o object) { + child(child(o, "metadata"), "labels")["app.kubernetes.io/managed-by"] = "another-manager" + }}, + "quota-of-another-rule": {quota, func(o object) { + child(child(o, "metadata"), "labels")["generate.kyverno.io/rule-name"] = "generate-limitrange" + }}, + "quota-with-unknown-content": {quota, func(o object) { o["data"] = object{"unexpected": "value"} }}, + "bundle-with-another-key": {bundle, func(o object) { child(o, "data")["extra"] = "value" }}, + "bundle-with-binary-data": {bundle, func(o object) { o["binaryData"] = object{"blob": "AA=="} }}, + "bundle-of-another-owner": {bundle, func(o object) { + items(child(o, "metadata"), "ownerReferences")[0]["uid"] = "another-bundle-uid" + }}, + "bundle-without-controller": {bundle, func(o object) { + items(child(o, "metadata"), "ownerReferences")[0]["controller"] = false + }}, + "bundle-with-another-label": {bundle, func(o object) { + child(child(o, "metadata"), "labels")["app"] = "foreign" + }}, + } + for name, mutation := range mutations { + t.Run(name, func(t *testing.T) { + d, api, ctx := platformCleanupFixture(t) + parts := strings.SplitN(mutation.target, "/", 3) + key := cleanupKey(parts[0], d.i.namespace, parts[2]) + mutation.mutate(api.objects[key]) + if d.cleanupRestore(ctx) == nil { + t.Fatal("a changed platform object allowed namespace disposal") + } + for _, retained := range []string{key, cleanupKey("Namespace", "", d.i.namespace), cleanupKey("Secret", d.i.namespace, "storage-key")} { + if _, found := api.objects[retained]; !found { + t.Fatal("an uncertain object or the recovery custody was removed") + } + } + }) + } + t.Run("missing-bundle", func(t *testing.T) { + d, api, ctx := platformCleanupFixture(t) + delete(api.objects, cleanupKey("bundles.trust.cert-manager.io", "", trustBundle)) + if d.cleanupRestore(ctx) == nil { + t.Fatal("a CA bundle ConfigMap without its Bundle allowed namespace disposal") + } + }) +} + +// The generated-limit table must name the rules the repository declares, so a +// rename fails here instead of retaining every restored copy. +func TestGeneratedLimitsMatchTheirDeclaredPolicies(t *testing.T) { + declared := map[string][2]string{} + for _, path := range []string{"add-default-limitrange.yaml", "add-ns-quota.yaml"} { + data, err := os.ReadFile("../../k8s/bases/infrastructure/cluster-policies/best-practices/" + path) + if err != nil { + t.Fatal(err) + } + var policy object + if err := yaml.NewDecoder(bytes.NewReader(data)).Decode(&policy); err != nil { + t.Fatal(err) + } + for _, rule := range items(child(policy, "spec"), "rules") { + generate := child(rule, "generate") + if text(generate, "apiVersion") != "v1" || text(generate, "namespace") != "{{request.object.metadata.name}}" || generate["synchronize"] != true { + continue + } + key := text(generate, "kind") + "/" + text(generate, "name") + if _, seen := declared[key]; !seen { + declared[key] = [2]string{text(child(policy, "metadata"), "name"), text(rule, "name")} + } + } + } + for key, rule := range generatedLimits { + if declared[key] != rule { + t.Fatalf("%s is generated by %v in the repository, not %v", key, declared[key], rule) + } + } +} + +// inventoryBindings is the complete inventory of the fixture namespace, with +// the records the platform adds while a reader runs. +func inventoryBindings(d *recoveryDriver, api *cleanupAPI) []namespaceinventory.Binding { + resources := map[string]string{"Pod": "pods", "PersistentVolumeClaim": "persistentvolumeclaims", "Secret": "secrets", "ConfigMap": "configmaps", "ServiceAccount": "serviceaccounts", "CiliumNetworkPolicy": "ciliumnetworkpolicies.cilium.io", "NetworkPolicy": "networkpolicies.networking.k8s.io", "LimitRange": "limitranges", "ResourceQuota": "resourcequotas", "CiliumEndpoint": "ciliumendpoints.cilium.io"} + var bindings []namespaceinventory.Binding + for _, o := range api.objects { + m := child(o, "metadata") + if text(m, "namespace") == d.i.namespace { + bindings = append(bindings, namespaceinventory.Binding{Name: text(m, "name"), Namespace: d.i.namespace, UID: text(m, "uid"), Kind: text(o, "kind"), Resource: resources[text(o, "kind")]}) + } + } + return append(bindings, + namespaceinventory.Binding{Name: "reader.18a1", Namespace: d.i.namespace, UID: "event-uid", Kind: "Event", Resource: "events"}, + namespaceinventory.Binding{Name: "reader.18a1", Namespace: d.i.namespace, UID: "event-uid", Kind: "Event", Resource: "events.events.k8s.io"}, + namespaceinventory.Binding{Name: "service-account-uid", Namespace: d.i.namespace, UID: "report-uid", Kind: "PolicyReport", Resource: "policyreports.wgpolicyk8s.io"}, + namespaceinventory.Binding{Name: fixtureReaderUID + "-k2x9q", Namespace: d.i.namespace, UID: "ephemeral-uid", Kind: "EphemeralReport", Resource: "ephemeralreports.reports.kyverno.io"}, + ) +} + +const fixtureReaderUID = "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0" + +// completeInventoryFixture is a running reader's namespace: every platform +// object, the default ServiceAccount and Cilium's endpoint for the reader. +func completeInventoryFixture(t *testing.T) (*recoveryDriver, *cleanupAPI, context.Context) { + t.Helper() + d, api, ctx := platformCleanupFixture(t) + reader := api.objects[cleanupKey("Pod", d.i.namespace, "reader")] + child(reader, "metadata")["uid"] = fixtureReaderUID + ref := d.refs[cleanupKey("Pod", d.i.namespace, "reader")] + ref.uid = fixtureReaderUID + d.refs[ref.key()] = ref + d.created = map[string]bool{} + for _, owned := range d.refs { + d.created[owned.uid] = true + } + api.objects[cleanupKey("ServiceAccount", d.i.namespace, "default")] = object{"apiVersion": "v1", "kind": "ServiceAccount", "metadata": object{"name": "default", "namespace": d.i.namespace, "uid": "service-account-uid"}} + api.objects[cleanupKey("ciliumendpoints.cilium.io", d.i.namespace, "reader")] = object{"apiVersion": "cilium.io/v2", "kind": "CiliumEndpoint", "metadata": object{"name": "reader", "namespace": d.i.namespace, "uid": "endpoint-uid", "ownerReferences": []any{object{"apiVersion": "v1", "kind": "Pod", "name": "reader", "uid": fixtureReaderUID}}}} + return d, api, ctx +} + +func TestCompleteInventoryAcceptsOwnedAndPlatformObjectsOnly(t *testing.T) { + d, api, ctx := completeInventoryFixture(t) + if err := d.classifyInventory(ctx, inventoryBindings(d, api)); err != nil { + t.Fatalf("a namespace holding only owned and platform objects was refused: %s", err) + } + foreign := func(kind, resource, name, uid string) func([]namespaceinventory.Binding) []namespaceinventory.Binding { + return func(b []namespaceinventory.Binding) []namespaceinventory.Binding { + return append(b, namespaceinventory.Binding{Name: name, Namespace: d.i.namespace, UID: uid, Kind: kind, Resource: resource}) + } + } + replace := func(kind string, change func(*namespaceinventory.Binding)) func([]namespaceinventory.Binding) []namespaceinventory.Binding { + return func(b []namespaceinventory.Binding) []namespaceinventory.Binding { + for i := range b { + if b[i].Kind == kind { + change(&b[i]) + } + } + return b + } + } + mutations := map[string]func([]namespaceinventory.Binding) []namespaceinventory.Binding{ + "role-binding": foreign("RoleBinding", "rolebindings.rbac.authorization.k8s.io", "reader", "foreign"), + "unknown-custom-object": foreign("Widget", "widgets.example.io", "widget", "foreign"), + "another-limit-range": foreign("LimitRange", "limitranges", "another-limitrange", "foreign"), + "limit-from-another-api": foreign("LimitRange", "limitranges.example.io", "default-limitrange", "foreign"), + "another-config-map": foreign("ConfigMap", "configmaps", "another", "foreign"), + "another-service-account": foreign("ServiceAccount", "serviceaccounts", "reader", "foreign"), + "report-on-unknown-uid": foreign("PolicyReport", "policyreports.wgpolicyk8s.io", "11111111-1111-4111-8111-111111111111", "foreign"), + "report-on-a-report": foreign("PolicyReport", "policyreports.wgpolicyk8s.io", "report-uid", "foreign"), + "ephemeral-unknown-uid": foreign("EphemeralReport", "ephemeralreports.reports.kyverno.io", "11111111-1111-4111-8111-111111111111-k2x9q", "foreign"), + "ephemeral-malformed": foreign("EphemeralReport", "ephemeralreports.reports.kyverno.io", fixtureReaderUID, "foreign"), + "endpoint-of-another-pod": foreign("CiliumEndpoint", "ciliumendpoints.cilium.io", "foreign", "foreign"), + "event-from-another-api": foreign("Event", "events.example.io", "reader.2", "foreign"), + "replaced-owned-secret": replace("Secret", func(b *namespaceinventory.Binding) { + if b.Name == "storage-key" { + b.UID = "replacement" + } + }), + "owned-kind-from-another-api": replace("Pod", func(b *namespaceinventory.Binding) { b.Resource = "pods.example.io" }), + "object-in-another-namespace": replace("LimitRange", func(b *namespaceinventory.Binding) { b.Namespace = "another" }), + "missing-owned-object": func(b []namespaceinventory.Binding) []namespaceinventory.Binding { + var kept []namespaceinventory.Binding + for _, binding := range b { + if binding.Kind != "Secret" { + kept = append(kept, binding) + } + } + return kept + }, + "duplicate-name": func(b []namespaceinventory.Binding) []namespaceinventory.Binding { + for _, binding := range b { + if binding.Kind == "ServiceAccount" { + binding.UID = "second" + return append(b, binding) + } + } + return b + }, + } + for name, mutate := range mutations { + t.Run(name, func(t *testing.T) { + d, api, ctx := completeInventoryFixture(t) + if d.classifyInventory(ctx, mutate(inventoryBindings(d, api))) == nil { + t.Fatal("an object that is neither owned nor platform-added was accepted") + } + }) + } + endpoint := map[string]func(object){ + "another-owner": func(o object) { items(child(o, "metadata"), "ownerReferences")[0]["uid"] = "another-pod" }, + "another-kind": func(o object) { items(child(o, "metadata"), "ownerReferences")[0]["kind"] = "Deployment" }, + "two-owners": func(o object) { + child(o, "metadata")["ownerReferences"] = append(child(o, "metadata")["ownerReferences"].([]any), object{"kind": "Pod"}) + }, + "replaced-object": func(o object) { child(o, "metadata")["uid"] = "replacement" }, + "another-api-kind": func(o object) { o["apiVersion"] = "cilium.io/v3" }, + } + for name, mutate := range endpoint { + t.Run("endpoint-"+name, func(t *testing.T) { + d, api, ctx := completeInventoryFixture(t) + // The inventory was read first; the endpoint read follows it. + bindings := inventoryBindings(d, api) + mutate(api.objects[cleanupKey("ciliumendpoints.cilium.io", d.i.namespace, "reader")]) + if d.classifyInventory(ctx, bindings) == nil { + t.Fatal("an endpoint not bound to the created reader was accepted") + } + }) + } + t.Run("endpoint-read-fails", func(t *testing.T) { + d, api, ctx := completeInventoryFixture(t) + d.k = failingReads{base: api, resource: "ciliumendpoints.cilium.io"} + if d.classifyInventory(ctx, inventoryBindings(d, api)) == nil { + t.Fatal("an unreadable endpoint was accepted") + } + }) +} + +type failingReads struct { + base kubernetes + resource string +} + +func (f failingReads) call(ctx context.Context, input []byte, args ...string) ([]byte, error) { + if len(args) > 1 && args[0] == "get" && args[1] == f.resource { + return nil, errors.New("read-failed") + } + return f.base.call(ctx, input, args...) +} + +// A report about the reader stays attributable after the reader is removed. +func TestCompleteInventoryKeepsRemovedOwnedObjectsAttributable(t *testing.T) { + d, api, ctx := completeInventoryFixture(t) + reader := cleanupKey("Pod", d.i.namespace, "reader") + delete(api.objects, reader) + delete(api.objects, cleanupKey("ciliumendpoints.cilium.io", d.i.namespace, "reader")) + delete(d.refs, reader) + if err := d.classifyInventory(ctx, inventoryBindings(d, api)); err != nil { + t.Fatalf("a report about the removed reader was refused: %s", err) + } + d.created = map[string]bool{} + if d.classifyInventory(ctx, inventoryBindings(d, api)) == nil { + t.Fatal("a report about an object this invocation never created was accepted") + } +} + +// No restore may start without the complete inventory that disposal needs, and +// the refusal comes before any controller or credential read. +func TestRecoveryRefusesToStartWithoutTheCompleteInventory(t *testing.T) { + t.Chdir("../..") + image, err := loadRecoveryImage() + if err != nil { + t.Fatal(err) + } + pod, pvc, pv := servingFixture() + items(child(pod, "spec"), "containers")[0]["image"] = image + reads := &sourceOnlyAPI{objects: map[string]object{"Pod": pod, "PersistentVolumeClaim": pvc, "PersistentVolume": pv}} + env := confirmedInvocation() + i, err := authorizeDataRecovery(func(k string) string { return env[k] }) + if err != nil { + t.Fatal(err) + } + d := &recoveryDriver{i: i, k: reads, env: func(k string) string { return env[k] }, refs: map[string]ownedReference{}, stage: "preflight"} + if _, err := d.preflight(context.Background()); err == nil || err.Error() != "inventory-credential" { + t.Fatalf("recovery started without the complete inventory credential: %v", err) + } + if reads.other != 0 || reads.source != 3 { + t.Fatalf("preflight read beyond the source before refusing: source=%d other=%d", reads.source, reads.other) + } +} + +type sourceOnlyAPI struct { + objects map[string]object + source, other int +} + +func (a *sourceOnlyAPI) call(_ context.Context, _ []byte, args ...string) ([]byte, error) { + if len(args) > 2 && args[0] == "get" { + if o, found := a.objects[args[1]]; found { + a.source++ + return json.Marshal(o) + } + } + a.other++ + return nil, errors.New("unexpected-read") +} diff --git a/scripts/verify-email-data-recovery/kubernetes.go b/scripts/verify-email-data-recovery/kubernetes.go index dc8fb3bee4..55807aff53 100644 --- a/scripts/verify-email-data-recovery/kubernetes.go +++ b/scripts/verify-email-data-recovery/kubernetes.go @@ -71,6 +71,7 @@ func veleroReadResource(kind string) string { type recoveryDriver struct { i invocation k kubernetes + env func(string) string refs map[string]ownedReference uncertain bool started bool @@ -81,6 +82,9 @@ type recoveryDriver struct { source sourceIdentity namespacePolicies map[string]namespacePolicy completeNamespaceInventory func(context.Context) error + // created holds the UID of every object this invocation created, including + // those it has since removed, so reports about them stay attributable. + created map[string]bool // protection is set only for disposal of a retained copy; see verifyProtection. protection protectionPoint } @@ -146,6 +150,10 @@ func (d *recoveryDriver) create(ctx context.Context, o object) (ownedReference, return ref, errors.New("create-identity") } d.refs[ref.key()] = ref + if d.created == nil { + d.created = map[string]bool{} + } + d.created[ref.uid] = true if !admittedRecoveryObject(o, actual) { d.uncertain = true return ref, errors.New("admission") diff --git a/scripts/verify-email-data-recovery/main.go b/scripts/verify-email-data-recovery/main.go index ad81d96b08..0baef80644 100644 --- a/scripts/verify-email-data-recovery/main.go +++ b/scripts/verify-email-data-recovery/main.go @@ -33,7 +33,7 @@ func runRecovery(ctx context.Context, env func(string) string, k kubernetes, out _, _ = fmt.Fprintln(output, "EMAIL_DATA_RECOVERY=UNVERIFIED stage=dispatch cleanup=NOT_STARTED") return 2 } - d := &recoveryDriver{i: i, k: k, refs: map[string]ownedReference{}, stage: "preflight"} + d := &recoveryDriver{i: i, k: k, env: env, refs: map[string]ownedReference{}, stage: "preflight"} runCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) defer cancel() if err = d.execute(runCtx); err != nil { diff --git a/scripts/verify-email-data-recovery/namespace_policies.go b/scripts/verify-email-data-recovery/namespace_policies.go index 6553c711c3..42067b420d 100644 --- a/scripts/verify-email-data-recovery/namespace_policies.go +++ b/scripts/verify-email-data-recovery/namespace_policies.go @@ -71,8 +71,14 @@ func loadNamespacePolicies() (map[string]namespacePolicy, error) { } func (p namespacePolicy) matches(o object, namespaceUID string) bool { + return reflect.DeepEqual(child(o, "spec"), p.spec) && kyvernoGenerated(o, p.api, "add-default-deny", p.rule, namespaceUID) +} + +// kyvernoGenerated binds an unowned object to the Kyverno rule that generated +// it for exactly this namespace, by the generate labels Kyverno writes. +func kyvernoGenerated(o object, api, policy, rule, namespaceUID string) bool { m := child(o, "metadata") - if namespaceUID == "" || text(m, "uid") == "" || text(o, "apiVersion") != p.api || m["deletionTimestamp"] != nil || len(items(m, "ownerReferences")) != 0 || !reflect.DeepEqual(child(o, "spec"), p.spec) { + if namespaceUID == "" || text(m, "uid") == "" || text(o, "apiVersion") != api || m["deletionTimestamp"] != nil || len(items(m, "ownerReferences")) != 0 { return false } for key := range o { @@ -81,7 +87,7 @@ func (p namespacePolicy) matches(o object, namespaceUID string) bool { } } labels := child(m, "labels") - for key, expected := range map[string]string{"app.kubernetes.io/managed-by": "kyverno", "generate.kyverno.io/policy-name": "add-default-deny", "generate.kyverno.io/policy-namespace": "", "generate.kyverno.io/rule-name": p.rule, "generate.kyverno.io/trigger-group": "", "generate.kyverno.io/trigger-kind": "Namespace", "generate.kyverno.io/trigger-namespace": "", "generate.kyverno.io/trigger-uid": namespaceUID, "generate.kyverno.io/trigger-version": "v1"} { + for key, expected := range map[string]string{"app.kubernetes.io/managed-by": "kyverno", "generate.kyverno.io/policy-name": policy, "generate.kyverno.io/policy-namespace": "", "generate.kyverno.io/rule-name": rule, "generate.kyverno.io/trigger-group": "", "generate.kyverno.io/trigger-kind": "Namespace", "generate.kyverno.io/trigger-namespace": "", "generate.kyverno.io/trigger-uid": namespaceUID, "generate.kyverno.io/trigger-version": "v1"} { actual, ok := labels[key].(string) if !ok || actual != expected { return false @@ -89,3 +95,46 @@ func (p namespacePolicy) matches(o object, namespaceUID string) bool { } return true } + +// Kyverno also generates one LimitRange and one ResourceQuota in every +// namespace (add-default-limitrange and add-ns-quota). They hold no data and +// constrain only this namespace, so they are recognised by exact kind, name and +// generate labels; TestGeneratedLimitsMatchTheirDeclaredPolicies keeps this +// table equal to those policies. +var generatedLimits = map[string][2]string{ + "LimitRange/default-limitrange": {"add-default-limitrange", "generate-limitrange"}, + "ResourceQuota/default-resourcequota": {"add-ns-quota", "generate-resourcequota"}, +} + +func generatedLimit(o object, namespaceUID string) bool { + rule, ok := generatedLimits[text(o, "kind")+"/"+text(child(o, "metadata"), "name")] + return ok && kyvernoGenerated(o, "v1", rule[0], rule[1], namespaceUID) +} + +// trust-manager distributes the platform CA bundle to every namespace as one +// ConfigMap owned by its cluster-scoped Bundle. It holds only public CA +// certificates under its single target key. +const trustBundle = "cloudflare-origin-ca" + +func trustBundleConfigMap(o object, bundleUID string) bool { + m := child(o, "metadata") + owners := items(m, "ownerReferences") + if bundleUID == "" || text(o, "apiVersion") != "v1" || text(o, "kind") != "ConfigMap" || text(m, "name") != trustBundle || text(m, "uid") == "" || m["deletionTimestamp"] != nil || len(owners) != 1 { + return false + } + owner := owners[0] + if text(owner, "apiVersion") != "trust.cert-manager.io/v1alpha1" || text(owner, "kind") != "Bundle" || text(owner, "name") != trustBundle || text(owner, "uid") != bundleUID || owner["controller"] != true { + return false + } + if labels := child(m, "labels"); len(labels) != 1 || labels["trust.cert-manager.io/bundle"] != trustBundle { + return false + } + for key := range o { + if key != "apiVersion" && key != "kind" && key != "metadata" && key != "data" { + return false + } + } + data := child(o, "data") + _, certificates := data["ca-certificates.crt"].(string) + return len(data) == 1 && certificates +} diff --git a/scripts/verify-email-data-recovery/run.go b/scripts/verify-email-data-recovery/run.go index aa7efff38f..0ec95d6cdf 100644 --- a/scripts/verify-email-data-recovery/run.go +++ b/scripts/verify-email-data-recovery/run.go @@ -55,6 +55,11 @@ func (d *recoveryDriver) preflight(ctx context.Context) (string, error) { if err != nil { return "", err } + // Disposal needs the complete inventory; without its credential no + // recovery starts, rather than leaving a copy that cannot be removed. + if err = d.useCompleteInventory(d.env); err != nil { + return "", err + } velero, found, err := d.lookup(ctx, "Deployment", "velero", "velero") if err != nil || !found { return "", errors.New("backup-controller") From 078b428dbc310b3fb3965a216837c46242a1e459 Mon Sep 17 00:00:00 2001 From: Nikolai Emil Damm Date: Wed, 25 Nov 2026 13:52:45 +0100 Subject: [PATCH 3/6] feat(email): prove the restored store holds every category, by count only The proof read back one diagnostic message. Issue #6256 asks to show the mailboxes, messages, calendars, tasks and account settings without exposing their content. Take a store census through read-only JMAP methods before the backup, after it, and from the restored copy: mailbox and message totals, calendars, calendar objects by JSCalendar type (Event or Task; CalDAV VTODO reads as Task), sending identities, Sieve filter scripts and the vacation response. Only identities, totals and types are read; the counts stay in memory. An unchanged source requires equal restored counts, a source that changed during the backup bounds them by its two readings, and an unknown type, short page or changed query refuses the census. The receipt names each category VERIFIED, or EMPTY where the source held none, and never a count. The native fixture now runs the census against the pinned server. Checked locally against the pinned production image in recovery mode: a live file-level copy of a store reopens with an identical census. Part of #6256 Co-Authored-By: Claude Opus 5.5 --- scripts/verify-email-data-recovery/README.md | 37 ++- scripts/verify-email-data-recovery/census.go | 218 ++++++++++++++ .../verify-email-data-recovery/census_test.go | 270 ++++++++++++++++++ .../verify-email-data-recovery/kubernetes.go | 2 + scripts/verify-email-data-recovery/mailbox.go | 21 +- scripts/verify-email-data-recovery/main.go | 24 +- .../verify-email-data-recovery/native_test.go | 13 + scripts/verify-email-data-recovery/run.go | 18 ++ 8 files changed, 591 insertions(+), 12 deletions(-) create mode 100644 scripts/verify-email-data-recovery/census.go create mode 100644 scripts/verify-email-data-recovery/census_test.go diff --git a/scripts/verify-email-data-recovery/README.md b/scripts/verify-email-data-recovery/README.md index f67fa6ae2b..d9201d2d2d 100644 --- a/scripts/verify-email-data-recovery/README.md +++ b/scripts/verify-email-data-recovery/README.md @@ -3,13 +3,28 @@ The confirmed `Verify Email Mailbox Data Recovery` workflow runs only from an immutable main revision, on its first attempt, in the protected production environment. It shares the production deployment lock. It does not move the -serving claim or activate encrypted production storage. +serving claim. +The server serves its store from the encrypted claim `email-data-encrypted` +(storage class `email-encrypted`); the original `private-mail-data` claim stays +mounted read-only as the rollback and is not the store this proof restores. The driver verifies the serving pod, claim and backend identity, then imports one uniquely identified diagnostic message into an unsubscribed test mailbox. JMAP import does not submit an outgoing message. The current account credential stays in runner memory and is never installed in the restored pod. +The driver also takes a census of the account's store before and after the +backup and again from the restored copy: mailboxes, messages, calendars with +their events, tasks, and account settings (sending identities, Sieve filter +scripts and the vacation response). It reads identities, counts and object +types only, never content, and keeps the counts in memory. An unchanged source +requires equal restored counts; a source that changed while the backup ran +bounds each restored count by its two readings. Reading calendars and +identities makes the server create its default calendar and identity if the +account has none; the first census runs before the backup, so the restore must +hold them too. The receipt names each category `VERIFIED`, or `EMPTY` where +the source held none (for example, no tasks), and never a count. + A fresh Velero filesystem backup selects the Email pod and includes its related claim, which the controller needs to capture persistent data. Scratch-volume receipts may coexist; acceptance requires the exact data-volume receipt, not @@ -95,16 +110,24 @@ encrypted scratch claim. The observer compares the one diagnostic from the protected run's creation window on both copies. Its receipt reports message parity. -The pass receipt covers message recovery, encrypted disposable storage, source -retention and disposal of the restored copy. It does not establish an independent -cluster rebuild, archive migration, transport delivery, OIDC, or production -storage activation. Those retain their separate acceptance gates. +The pass receipt covers message recovery, the store census, encrypted disposable +storage, source retention and disposal of the restored copy. It does not +establish an independent cluster rebuild, archive migration, transport delivery +or OIDC. Those retain their separate acceptance gates. + +The backup is file level: Velero's node agent reads the mounted, already +decrypted store and Kopia encrypts it into the backup bucket under the Velero +repository password. Restoring it needs that password and read access to the +bucket, not the serving volume's Longhorn key (`email-storage-key`); the copy is +written to a new volume encrypted with a new diagnostic key. The in-cluster +restore uses the running cluster's repository credential, so this workflow does +not show that an independently held copy of that password opens the backup. Local validation is `go test -race ./scripts/verify-email-data-recovery`, `go vet` and the package's normal lint check. The native Email configuration fixture also runs the real driver client against the pinned server to exercise message -import, content validation and safe cleanup. Production recovery remains -unverified until the confirmed protected workflow itself passes. +import, content validation, the store census and safe cleanup. Production +recovery remains unverified until the confirmed protected workflow itself passes. The native restored server also uses the reader's generated capability settings, proving that the pinned executable can start with its required file capability. diff --git a/scripts/verify-email-data-recovery/census.go b/scripts/verify-email-data-recovery/census.go new file mode 100644 index 0000000000..af81d923d4 --- /dev/null +++ b/scripts/verify-email-data-recovery/census.go @@ -0,0 +1,218 @@ +package main + +import ( + "context" + "errors" +) + +// storeCensus counts what one account's store holds, without reading any +// content: mailboxes, messages, calendars with their events and tasks, and the +// account settings (sending identities, Sieve filter scripts and the vacation +// response). It stays in process memory; receipts carry only closed verdicts. +type storeCensus struct { + mailboxes, messages, calendars, events, tasks, identities, sieveScripts int + vacation bool +} + +// calendarPage stays well inside the server's 500-object read limit. +const calendarPage = 256 + +// censusBound refuses an implausible store rather than paging without end. +const censusBound = 1 << 20 + +func queryTotal(result object) (int, error) { + total, ok := result["total"].(float64) + ids, listed := result["ids"].([]any) + if !ok || !listed || total < 0 || total > censusBound || total != float64(int(total)) || text(result, "queryState") == "" { + return 0, errors.New("census-total") + } + if len(ids) > int(total) { + return 0, errors.New("census-total") + } + return int(total), nil +} + +func (c *mailboxClient) count(ctx context.Context, method string) (int, error) { + result, err := c.call(ctx, method, object{"calculateTotal": true, "limit": 1}) + if err != nil { + return 0, err + } + return queryTotal(result) +} + +// listAll reads every object of one type by identity only. +func (c *mailboxClient) listAll(ctx context.Context, method string) (int, error) { + result, err := c.call(ctx, method, object{"ids": nil, "properties": []any{"id"}}) + if err != nil { + return 0, err + } + list, ok := result["list"].([]any) + if !ok || len(items(result, "list")) != len(list) || text(result, "state") == "" || !noneMissing(result) { + return 0, errors.New("census-list") + } + return len(list), nil +} + +// noneMissing requires a /get answer's notFound list to be present and empty. +// It holds identifiers, not objects, so it is read as a raw list. +func noneMissing(result object) bool { + missing, ok := result["notFound"].([]any) + return ok && len(missing) == 0 +} + +// calendarObjects pages through every calendar object by identity and type. +// Stalwart serves an event as JSCalendar Event and a task as Task; any other +// type, a changed query or a short page refuses the census. +func (c *mailboxClient) calendarObjects(ctx context.Context) (events, tasks int, err error) { + total, state := -1, "" + for position := 0; ; position += calendarPage { + page, err := c.call(ctx, "CalendarEvent/query", object{"calculateTotal": true, "position": position, "limit": calendarPage}) + if err != nil { + return 0, 0, err + } + pageTotal, err := queryTotal(page) + if err != nil || (total >= 0 && (pageTotal != total || text(page, "queryState") != state)) || page["position"] != float64(position) { + return 0, 0, errors.New("census-calendar-query") + } + total, state = pageTotal, text(page, "queryState") + ids, _ := page["ids"].([]any) + if len(ids) == 0 { + break + } + objects, err := c.call(ctx, "CalendarEvent/get", object{"ids": ids, "properties": []any{"id", "@type"}}) + if err != nil { + return 0, 0, err + } + list := items(objects, "list") + if raw, _ := objects["list"].([]any); len(list) != len(ids) || len(raw) != len(ids) || !noneMissing(objects) { + return 0, 0, errors.New("census-calendar-objects") + } + requested := map[any]bool{} + for _, id := range ids { + requested[id] = true + } + for _, o := range list { + if id := text(o, "id"); !requested[id] { + return 0, 0, errors.New("census-calendar-objects") + } + delete(requested, text(o, "id")) + switch text(o, "@type") { + case "Event": + events++ + case "Task": + tasks++ + default: + return 0, 0, errors.New("census-calendar-type") + } + } + if position+len(ids) >= total { + break + } + } + if events+tasks != total { + return 0, 0, errors.New("census-calendar-total") + } + return events, tasks, nil +} + +// census reads the account's complete store census. Reading calendars and +// identities makes the server create its default calendar and identity if +// the account has none; the source census runs before the backup, so those +// defaults are part of what the restore must hold. +func (c *mailboxClient) census(ctx context.Context) (storeCensus, error) { + var s storeCensus + var err error + if s.mailboxes, err = c.count(ctx, "Mailbox/query"); err != nil { + return s, err + } + if s.messages, err = c.count(ctx, "Email/query"); err != nil { + return s, err + } + if s.calendars, err = c.listAll(ctx, "Calendar/get"); err != nil { + return s, err + } + if s.events, s.tasks, err = c.calendarObjects(ctx); err != nil { + return s, err + } + if s.identities, err = c.listAll(ctx, "Identity/get"); err != nil { + return s, err + } + if s.sieveScripts, err = c.count(ctx, "SieveScript/query"); err != nil { + return s, err + } + result, err := c.call(ctx, "VacationResponse/get", object{"ids": []any{"singleton"}, "properties": []any{"id"}}) + if err != nil { + return s, err + } + list := items(result, "list") + s.vacation = len(list) == 1 && text(list[0], "id") == "singleton" + if !s.vacation { + return s, errors.New("census-vacation") + } + return s, nil +} + +// censusVerdicts compares the restored census with the source's, read before +// and after the backup. Unchanged sources require equal counts; a source that +// changed during the backup bounds each restored count by its two readings. +// Each verdict is VERIFIED, or EMPTY where the source held nothing to restore. +func censusVerdicts(before, after, restored storeCensus) (map[string]string, error) { + within := func(field func(storeCensus) int) bool { + low, high := field(before), field(after) + if low > high { + low, high = high, low + } + return field(restored) >= low && field(restored) <= high + } + verdict := func(present bool, fields ...func(storeCensus) int) (string, bool) { + for _, field := range fields { + if !within(field) { + return "", false + } + } + if present { + return "VERIFIED", true + } + return "EMPTY", true + } + held := func(fields ...func(storeCensus) int) bool { + for _, field := range fields { + if field(before) > 0 || field(after) > 0 { + return true + } + } + return false + } + mailboxes := func(s storeCensus) int { return s.mailboxes } + messages := func(s storeCensus) int { return s.messages } + calendars := func(s storeCensus) int { return s.calendars } + events := func(s storeCensus) int { return s.events } + tasks := func(s storeCensus) int { return s.tasks } + identities := func(s storeCensus) int { return s.identities } + scripts := func(s storeCensus) int { return s.sieveScripts } + verdicts := map[string]string{} + for name, check := range map[string][]func(storeCensus) int{ + "mailboxes": {mailboxes}, + "messages": {messages}, + "calendars": {calendars, events}, + "tasks": {tasks}, + "settings": {identities, scripts}, + } { + result, ok := verdict(held(check...), check...) + if !ok { + return nil, errors.New("census-" + name) + } + verdicts[name] = result + } + // The marker message and its mailbox were created before the backup. + if verdicts["mailboxes"] != "VERIFIED" || verdicts["messages"] != "VERIFIED" { + return nil, errors.New("census-marker") + } + // Account settings always include the vacation response; the restored + // account also authenticated with the source credential to be read. + if !before.vacation || !after.vacation || !restored.vacation { + return nil, errors.New("census-settings") + } + verdicts["settings"] = "VERIFIED" + return verdicts, nil +} diff --git a/scripts/verify-email-data-recovery/census_test.go b/scripts/verify-email-data-recovery/census_test.go new file mode 100644 index 0000000000..0fa1e0c15f --- /dev/null +++ b/scripts/verify-email-data-recovery/census_test.go @@ -0,0 +1,270 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// censusStore is a JMAP account in the response shapes the pinned server +// returned for a disposable user on 2026-11-25. +type censusStore struct { + mailboxes, messages, calendars, identities, scripts int + objects []string // JSCalendar @type per calendar object + vacation bool + mutate func(method string, args, result object) + methods []string +} + +func (s *censusStore) serve(t *testing.T) *mailboxClient { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body object + if json.NewDecoder(r.Body).Decode(&body) != nil { + http.Error(w, "request", http.StatusBadRequest) + return + } + call := body["methodCalls"].([]any)[0].([]any) + method, args := call[0].(string), call[1].(map[string]any) + s.methods = append(s.methods, method) + using := body["using"].([]any) + if len(using) != 2 || using[0] != "urn:ietf:params:jmap:core" || using[1] != mailboxMethods[method] { + t.Errorf("%s did not declare exactly its capability", method) + } + query := func(total int) object { + ids := []any{} + position, _ := args["position"].(float64) + limit, _ := args["limit"].(float64) + for i := int(position); i < total && i < int(position)+int(limit); i++ { + ids = append(ids, fmt.Sprintf("id%d", i)) + } + return object{"queryState": "q1", "canCalculateChanges": true, "position": position, "ids": ids, "total": float64(total)} + } + listed := func(count int) object { + list := []any{} + for i := range count { + list = append(list, object{"id": fmt.Sprintf("id%d", i)}) + } + return object{"state": "s1", "list": list, "notFound": []any{}} + } + var result object + switch method { + case "Mailbox/query": + result = query(s.mailboxes) + case "Email/query": + result = query(s.messages) + case "SieveScript/query": + result = query(s.scripts) + case "CalendarEvent/query": + result = query(len(s.objects)) + case "Calendar/get": + result = listed(s.calendars) + case "Identity/get": + result = listed(s.identities) + case "CalendarEvent/get": + list := []any{} + for _, id := range args["ids"].([]any) { + var index int + _, _ = fmt.Sscanf(id.(string), "id%d", &index) + list = append(list, object{"id": id, "@type": s.objects[index]}) + } + result = object{"state": "s1", "list": list, "notFound": []any{}} + case "VacationResponse/get": + result = object{"state": "s1", "list": []any{}, "notFound": []any{"singleton"}} + if s.vacation { + result = object{"state": "s1", "list": []any{object{"id": "singleton"}}, "notFound": []any{}} + } + default: + t.Errorf("census called %s", method) + } + result["accountId"] = "company-account" + if s.mutate != nil { + s.mutate(method, args, result) + } + encoded, _ := json.Marshal(object{"methodResponses": []any{[]any{method, result, "proof"}}}) + _, _ = w.Write(encoded) + })) + t.Cleanup(server.Close) + client, err := newMailboxClient(server.URL, "fixture-only") + if err != nil { + t.Fatal(err) + } + client.account = "company-account" + return client +} + +func censusFixture() *censusStore { + objects := make([]string, 300) + for i := range objects { + objects[i] = "Event" + if i%7 == 0 { + objects[i] = "Task" + } + } + return &censusStore{mailboxes: 9, messages: 1234, calendars: 2, identities: 1, scripts: 1, objects: objects, vacation: true} +} + +func TestCensusCountsEveryCategoryByIdentityOnly(t *testing.T) { + store := censusFixture() + census, err := store.serve(t).census(context.Background()) + if err != nil { + t.Fatalf("census failed: %v", err) + } + if census != (storeCensus{mailboxes: 9, messages: 1234, calendars: 2, events: 257, tasks: 43, identities: 1, sieveScripts: 1, vacation: true}) { + t.Fatalf("census miscounted: %+v", census) + } + pages := 0 + for _, method := range store.methods { + if strings.HasSuffix(method, "/set") || strings.HasSuffix(method, "/import") { + t.Fatalf("census wrote through %s", method) + } + if method == "CalendarEvent/get" { + pages++ + } + } + if pages != 2 { + t.Fatalf("300 calendar objects were read in %d pages, want 2", pages) + } +} + +func TestCensusRefusesIncompleteOrUnknownAnswers(t *testing.T) { + for name, mutate := range map[string]func(string, object, object){ + "unknown-calendar-type": func(method string, _, result object) { + if method == "CalendarEvent/get" { + items(result, "list")[0]["@type"] = "Group" + } + }, + "short-calendar-page": func(method string, _, result object) { + if method == "CalendarEvent/get" { + result["list"] = result["list"].([]any)[1:] + } + }, + "duplicate-calendar-object": func(method string, _, result object) { + if method == "CalendarEvent/get" { + list := result["list"].([]any) + list[1] = list[0] + } + }, + "calendar-object-not-found": func(method string, _, result object) { + if method == "CalendarEvent/get" { + result["notFound"] = []any{"id0"} + } + }, + "query-changed-between-pages": func(method string, args, result object) { + if method == "CalendarEvent/query" && args["position"] != float64(0) { + result["queryState"] = "q2" + } + }, + "total-changed-between-pages": func(method string, args, result object) { + if method == "CalendarEvent/query" && args["position"] != float64(0) { + result["total"] = float64(301) + } + }, + "missing-total": func(_ string, _, result object) { delete(result, "total") }, + "fractional-total": func(_ string, _, result object) { result["total"] = 1.5 }, + "negative-total": func(_ string, _, result object) { result["total"] = float64(-1) }, + "missing-list-state": func(_ string, _, result object) { delete(result, "state") }, + "listed-not-found": func(method string, _, result object) { + if method == "Identity/get" { + result["notFound"] = []any{"id9"} + } + }, + "missing-vacation": func(method string, _, result object) { + if method == "VacationResponse/get" { + result["list"] = []any{} + } + }, + "foreign-account": func(method string, _, result object) { + if method == "SieveScript/query" { + result["accountId"] = "another-account" + } + }, + } { + t.Run(name, func(t *testing.T) { + store := censusFixture() + store.mutate = mutate + if _, err := store.serve(t).census(context.Background()); err == nil { + t.Fatal("an incomplete or unknown census answer was accepted") + } + }) + } +} + +func TestCensusVerdictsBindTheRestoreToTheSource(t *testing.T) { + source := storeCensus{mailboxes: 9, messages: 1234, calendars: 2, events: 257, tasks: 43, identities: 1, sieveScripts: 1, vacation: true} + verdicts, err := censusVerdicts(source, source, source) + if err != nil { + t.Fatalf("an equal restore was refused: %v", err) + } + for _, category := range []string{"messages", "mailboxes", "calendars", "tasks", "settings"} { + if verdicts[category] != "VERIFIED" { + t.Fatalf("%s was not verified", category) + } + } + empty := source + empty.tasks = 0 + if verdicts, err = censusVerdicts(empty, empty, empty); err != nil || verdicts["tasks"] != "EMPTY" { + t.Fatal("an account without tasks was not reported as empty") + } + arrived := source + arrived.messages += 2 + between := source + between.messages++ + for _, restored := range []storeCensus{source, between, arrived} { + if _, err = censusVerdicts(source, arrived, restored); err != nil { + t.Fatal("a restore taken while mail arrived was refused") + } + } + for name, change := range map[string]func(*storeCensus){ + "lost-message": func(s *storeCensus) { s.messages-- }, + "extra-message": func(s *storeCensus) { s.messages++ }, + "lost-mailbox": func(s *storeCensus) { s.mailboxes-- }, + "lost-calendar": func(s *storeCensus) { s.calendars-- }, + "lost-event": func(s *storeCensus) { s.events-- }, + "lost-task": func(s *storeCensus) { s.tasks-- }, + "lost-identity": func(s *storeCensus) { s.identities-- }, + "lost-filter": func(s *storeCensus) { s.sieveScripts-- }, + "lost-vacation": func(s *storeCensus) { s.vacation = false }, + "event-as-a-task": func(s *storeCensus) { s.events--; s.tasks++ }, + } { + t.Run(name, func(t *testing.T) { + restored := source + change(&restored) + if _, err := censusVerdicts(source, source, restored); err == nil { + t.Fatal("a restore that differs from an unchanged source was accepted") + } + }) + } + if _, err = censusVerdicts(source, arrived, storeCensus{mailboxes: 9, messages: 1237, calendars: 2, events: 257, tasks: 43, identities: 1, sieveScripts: 1, vacation: true}); err == nil { + t.Fatal("a restore outside the source's two readings was accepted") + } + noMarker := storeCensus{calendars: 1, identities: 1, vacation: true} + if _, err = censusVerdicts(noMarker, noMarker, noMarker); err == nil { + t.Fatal("a store without the diagnostic message and mailbox was verified") + } +} + +func TestReceiptRequiresTheRestoredCensus(t *testing.T) { + if _, err := recoveryReceipt(nil); err == nil { + t.Fatal("a pass receipt was issued without the restored census") + } + verdicts := map[string]string{"messages": "VERIFIED", "mailboxes": "VERIFIED", "calendars": "VERIFIED", "tasks": "EMPTY", "settings": "VERIFIED"} + receipt, err := recoveryReceipt(verdicts) + if err != nil || receipt != "EMAIL_DATA_RECOVERY=PASS messages=VERIFIED mailboxes=VERIFIED calendars=VERIFIED tasks=EMPTY settings=VERIFIED storage=ENCRYPTED source=RETAINED restore_cleanup=VERIFIED backup=RETAINED_24H" { + t.Fatalf("unexpected receipt %q: %v", receipt, err) + } + for _, change := range []struct{ category, verdict string }{{"messages", "EMPTY"}, {"mailboxes", "EMPTY"}, {"settings", "EMPTY"}, {"calendars", "1234"}, {"tasks", ""}, {"extra", "VERIFIED"}} { + changed := map[string]string{} + for k, v := range verdicts { + changed[k] = v + } + changed[change.category] = change.verdict + if _, err := recoveryReceipt(changed); err == nil { + t.Fatalf("receipt accepted %s=%q", change.category, change.verdict) + } + } +} diff --git a/scripts/verify-email-data-recovery/kubernetes.go b/scripts/verify-email-data-recovery/kubernetes.go index 55807aff53..b75ee3c6b6 100644 --- a/scripts/verify-email-data-recovery/kubernetes.go +++ b/scripts/verify-email-data-recovery/kubernetes.go @@ -85,6 +85,8 @@ type recoveryDriver struct { // created holds the UID of every object this invocation created, including // those it has since removed, so reports about them stay attributable. created map[string]bool + // verdicts are the closed census results of a verified restore. + verdicts map[string]string // protection is set only for disposal of a retained copy; see verifyProtection. protection protectionPoint } diff --git a/scripts/verify-email-data-recovery/mailbox.go b/scripts/verify-email-data-recovery/mailbox.go index 8fd0f78057..e069924853 100644 --- a/scripts/verify-email-data-recovery/mailbox.go +++ b/scripts/verify-email-data-recovery/mailbox.go @@ -59,10 +59,23 @@ func (c *mailboxClient) request(ctx context.Context, method, path, contentType s } return data, nil } + +// mailboxMethods names the JMAP capability of each method this client may +// call. Every method outside the marker lifecycle only reads. +var mailboxMethods = map[string]string{ + "Email/get": jmapMail, "Email/query": jmapMail, "Email/import": jmapMail, "Email/set": jmapMail, + "Mailbox/get": jmapMail, "Mailbox/set": jmapMail, "Mailbox/query": jmapMail, + "Calendar/get": "urn:ietf:params:jmap:calendars", "CalendarEvent/query": "urn:ietf:params:jmap:calendars", "CalendarEvent/get": "urn:ietf:params:jmap:calendars", + "Identity/get": "urn:ietf:params:jmap:submission", + "VacationResponse/get": "urn:ietf:params:jmap:vacationresponse", + "SieveScript/query": "urn:ietf:params:jmap:sieve", +} + +const jmapMail = "urn:ietf:params:jmap:mail" + func (c *mailboxClient) call(ctx context.Context, method string, args object) (object, error) { - switch method { - case "Email/get", "Email/query", "Email/import", "Email/set", "Mailbox/get", "Mailbox/set": - default: + capability, ok := mailboxMethods[method] + if !ok { return nil, errors.New("mailbox-method") } if !mailboxIDPattern.MatchString(c.account) { @@ -75,7 +88,7 @@ func (c *mailboxClient) call(ctx context.Context, method string, args object) (o } bound[key] = value } - body, err := json.Marshal(object{"using": []any{"urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"}, "methodCalls": []any{[]any{method, bound, "proof"}}}) + body, err := json.Marshal(object{"using": []any{"urn:ietf:params:jmap:core", capability}, "methodCalls": []any{[]any{method, bound, "proof"}}}) if err != nil { return nil, errors.New("mailbox-input") } diff --git a/scripts/verify-email-data-recovery/main.go b/scripts/verify-email-data-recovery/main.go index 0baef80644..7fd77c4e74 100644 --- a/scripts/verify-email-data-recovery/main.go +++ b/scripts/verify-email-data-recovery/main.go @@ -4,6 +4,7 @@ package main import ( "context" + "errors" "fmt" "io" "os" @@ -53,8 +54,29 @@ func runRecovery(ctx context.Context, env func(string) string, k kubernetes, out _, _ = fmt.Fprintln(output, "EMAIL_DATA_RECOVERY=UNVERIFIED stage=cleanup cleanup=RETAINED") return 2 } - if _, err := fmt.Fprintln(output, "EMAIL_DATA_RECOVERY=PASS messages=VERIFIED storage=ENCRYPTED source=RETAINED restore_cleanup=VERIFIED backup=RETAINED_24H"); err != nil { + receipt, err := recoveryReceipt(d.verdicts) + if err != nil { + _, _ = fmt.Fprintln(output, "EMAIL_DATA_RECOVERY=UNVERIFIED stage=receipt cleanup=VERIFIED") + return 2 + } + if _, err := fmt.Fprintln(output, receipt); err != nil { return 2 } return 0 } + +// recoveryReceipt names each census category with a closed verdict only. +func recoveryReceipt(verdicts map[string]string) (string, error) { + receipt := "EMAIL_DATA_RECOVERY=PASS" + for _, category := range []string{"messages", "mailboxes", "calendars", "tasks", "settings"} { + verdict := verdicts[category] + if verdict != "VERIFIED" && (verdict != "EMPTY" || category == "messages" || category == "mailboxes" || category == "settings") { + return "", errors.New("receipt") + } + receipt += " " + category + "=" + verdict + } + if len(verdicts) != 5 { + return "", errors.New("receipt") + } + return receipt + " storage=ENCRYPTED source=RETAINED restore_cleanup=VERIFIED backup=RETAINED_24H", nil +} diff --git a/scripts/verify-email-data-recovery/native_test.go b/scripts/verify-email-data-recovery/native_test.go index af1eef669a..b0490d01fb 100644 --- a/scripts/verify-email-data-recovery/native_test.go +++ b/scripts/verify-email-data-recovery/native_test.go @@ -76,6 +76,19 @@ func TestNativeRecoveryMarkerLifecycle(t *testing.T) { if _, err = client.verifyMessage(ctx, marker.identity); err != nil { t.Fatalf("native marker read: %s", err) } + // The pinned server answers every census method; a repeated census of an + // unchanged store is identical and verifies against itself. + census, err := client.census(ctx) + if err != nil { + t.Fatalf("native store census: %s", err) + } + repeated, err := client.census(ctx) + if err != nil || repeated != census { + t.Fatal("native store census changed without a write") + } + if _, err = censusVerdicts(census, census, repeated); err != nil { + t.Fatalf("native store census verdicts: %s", err) + } reader, err := newRetainedMailboxClientInWindow(client.endpoint, password, window) if err != nil { t.Fatal("native read-only fixture endpoint refused") diff --git a/scripts/verify-email-data-recovery/run.go b/scripts/verify-email-data-recovery/run.go index 0ec95d6cdf..8927771f7b 100644 --- a/scripts/verify-email-data-recovery/run.go +++ b/scripts/verify-email-data-recovery/run.go @@ -131,6 +131,11 @@ func (d *recoveryDriver) execute(ctx context.Context) error { if err != nil { return err } + d.stage = "source-census" + sourceBefore, err := original.census(ctx) + if err != nil { + return err + } d.stage = "backup" backup, err := d.create(ctx, backupManifest(d.i)) if err != nil { @@ -170,6 +175,11 @@ func (d *recoveryDriver) execute(ctx context.Context) error { if err = d.sourceRetained(ctx); err != nil { return err } + d.stage = "source-census" + sourceAfter, err := original.census(ctx) + if err != nil { + return err + } d.stage = "isolated-storage" key, err := randomRecoveryValue() if err != nil { @@ -264,6 +274,14 @@ func (d *recoveryDriver) execute(ctx context.Context) error { if _, err = recovered.verifyMessage(ctx, marker.identity); err != nil { return err } + d.stage = "reader-census" + restored, err := recovered.census(ctx) + if err != nil { + return err + } + if d.verdicts, err = censusVerdicts(sourceBefore, sourceAfter, restored); err != nil { + return err + } d.stage = "source-retention" if err = d.sourceRetained(ctx); err != nil { return err From 153ff90895a1b931b38d5e6ab71479cdbcd3ed01 Mon Sep 17 00:00:00 2001 From: Nikolai Emil Damm Date: Fri, 27 Nov 2026 05:41:29 +0100 Subject: [PATCH 4/6] fix(email): verify recovery on encrypted Longhorn V2 Bind the serving claim, Kopia receipt, and isolated restore to their exact identities. Require three running V2 replicas and the diagnostic encryption key. Refuse regenerated calendar and identity defaults and unverified scan storage registrations. Part of #6256 --- internal/longhorninventory/v2_replicas.go | 38 ++++++++++++ internal/namespaceinventory/coverage.go | 12 +++- internal/namespaceinventory/inventory_test.go | 15 +++-- scripts/verify-email-data-recovery/README.md | 18 +++--- scripts/verify-email-data-recovery/census.go | 56 +++++++++++++---- .../verify-email-data-recovery/census_test.go | 36 +++++++++++ .../cleanup_test.go | 3 +- .../fresh_observation_test.go | 2 +- scripts/verify-email-data-recovery/mailbox.go | 13 ++-- scripts/verify-email-data-recovery/proof.go | 7 ++- .../verify-email-data-recovery/proof_test.go | 8 ++- .../verify-email-data-recovery/resources.go | 2 +- .../resources_test.go | 7 +++ .../retained_protection_test.go | 1 + scripts/verify-email-data-recovery/run.go | 27 ++++++++- scripts/verify-email-data-recovery/source.go | 60 +++++++++++++++---- .../verify-email-data-recovery/source_test.go | 30 +++++++--- .../verify-email-data-recovery/transfer.go | 13 +++- .../transfer_test.go | 22 ++++++- scripts/verify-email-storage-canary/main.go | 4 +- scripts/verify-email-storage-canary/proof.go | 24 -------- .../verify-email-storage-canary/proof_test.go | 6 +- 22 files changed, 315 insertions(+), 89 deletions(-) create mode 100644 internal/longhorninventory/v2_replicas.go diff --git a/internal/longhorninventory/v2_replicas.go b/internal/longhorninventory/v2_replicas.go new file mode 100644 index 0000000000..2faa7e6849 --- /dev/null +++ b/internal/longhorninventory/v2_replicas.go @@ -0,0 +1,38 @@ +package longhorninventory + +import "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + +// V2ReplicaQuorum requires three running replicas of the exact volume on +// distinct nodes and disks. +func V2ReplicaQuorum(volume map[string]any, replicas []map[string]any) bool { + backend := unstructured.Unstructured{Object: volume} + name, uid := backend.GetName(), backend.GetUID() + if name == "" || uid == "" || replicas == nil { + return false + } + nodes, disks, identities := map[string]bool{}, map[string]bool{}, map[string]bool{} + for _, replica := range replicas { + rawSpec, _, _ := unstructured.NestedFieldNoCopy(replica, "spec") + spec, _ := rawSpec.(map[string]any) + if spec["volumeName"] != name { + continue + } + resource := unstructured.Unstructured{Object: replica} + owners := resource.GetOwnerReferences() + node, _ := spec["nodeID"].(string) + disk, _ := spec["diskID"].(string) + id := string(resource.GetUID()) + state, _, _ := unstructured.NestedString(replica, "status", "currentState") + deleted, _, _ := unstructured.NestedFieldNoCopy(replica, "metadata", "deletionTimestamp") + healthyAt, _ := spec["healthyAt"].(string) + failedAt, _ := spec["failedAt"].(string) + if len(owners) != 1 || owners[0].APIVersion != "longhorn.io/v1beta2" || owners[0].Kind != "Volume" || + owners[0].Name != name || owners[0].UID != uid || resource.GetNamespace() != "longhorn-system" || + spec["dataEngine"] != "v2" || healthyAt == "" || failedAt != "" || state != "running" || deleted != nil || + node == "" || disk == "" || id == "" || nodes[node] || disks[disk] || identities[id] { + return false + } + nodes[node], disks[disk], identities[id] = true, true, true + } + return len(nodes) == 3 +} diff --git a/internal/namespaceinventory/coverage.go b/internal/namespaceinventory/coverage.go index d42b84f45e..7e60a613a9 100644 --- a/internal/namespaceinventory/coverage.go +++ b/internal/namespaceinventory/coverage.go @@ -65,6 +65,7 @@ func (r *reader) nativeCoverage(ctx context.Context, resources discovery) ([]ser } result := make([]serviceRegistration, 0, len(items)) seen, seenUID := map[string]bool{}, map[string]bool{} + scanRegistered := false for _, item := range items { group, version := item.Spec.Group, item.Spec.Version if !versionPattern.MatchString(version) || len(version) > 63 || group != "" && (!groupPattern.MatchString(group) || len(group) > 253) || item.Metadata.Name != version+"."+group || item.Metadata.Namespace != "" || item.Metadata.UID == "" || item.Metadata.ResourceVersion == "" || seen[item.Metadata.Name] || seenUID[item.Metadata.UID] { @@ -79,13 +80,18 @@ func (r *reader) nativeCoverage(ctx context.Context, resources discovery) ([]ser if remote && (item.Spec.Service.Name == "" || item.Spec.Service.Namespace == "") { return nil, errors.New("aggregated API service binding is incomplete") } - // An Email recovery namespace is removed by its own invocation, not - // guarded by admission. Kubescape's derived scan records may go with it. - if remote && required[gv] && (!r.scanRecords || !scanStorage(item)) { + scanBackend := r.scanRecords && scanStorage(item) + scanRegistered = scanRegistered || scanBackend + // Only the exact Kubescape backend may supply derived records for a + // recovery namespace this invocation owns. + if remote && required[gv] && !scanBackend { return nil, errors.New("namespace deletion admission is unverified for a remote API backend") } result = append(result, serviceRegistration{item.Metadata.Name, item.Metadata.UID, gv, item.Metadata.ResourceVersion, remote}) } + if r.scanRecords && required[scanGroupVersion] && !scanRegistered { + return nil, errors.New("scan storage registration is unverified") + } sort.Slice(result, func(a, b int) bool { return result[a].Name < result[b].Name }) return result, nil } diff --git a/internal/namespaceinventory/inventory_test.go b/internal/namespaceinventory/inventory_test.go index 83b6ed7f57..3eeba64554 100644 --- a/internal/namespaceinventory/inventory_test.go +++ b/internal/namespaceinventory/inventory_test.go @@ -121,7 +121,7 @@ func TestEmailInventoryAcceptsOnlyKubescapeScanRecords(t *testing.T) { if err != nil || len(result.Bindings()) != 2 || len(result.scanRecords) != 3 { t.Fatalf("Kubescape scan records prevented a complete Email inventory: bindings=%d records=%d error=%v", len(result.Bindings()), len(result.scanRecords), err) } - for _, failure := range []string{"scan records from another service", "scan records under another version", "scan image record", "scan record of a mislabelled kind", "scan continued list", "scan foreign namespace", "scan record without version", "scan duplicate record", "scan view without source"} { + for _, failure := range []string{"scan records from another service", "scan records under another version", "scan missing service", "scan local registration", "scan image record", "scan record of a mislabelled kind", "scan continued list", "scan foreign namespace", "scan record without version", "scan duplicate record", "scan view without source"} { t.Run(failure, func(t *testing.T) { result, err := observeFixtureInNamespace(t, failure, testEmailNamespace) if err == nil || len(result.Bindings()) != 0 || len(result.scanRecords) != 0 { @@ -218,12 +218,15 @@ func observeFixtureInNamespace(t *testing.T, failure, namespace string) (Invento service = `,"service":{"name":"remote","namespace":"system"}` } scan := "" - if scanFixture { - scanService := "storage" - if failure == "scan records from another service" { - scanService = "other" + if scanFixture && failure != "scan missing service" { + scanService := `,"service":{"name":"storage","namespace":"kubescape"}` + switch failure { + case "scan records from another service": + scanService = `,"service":{"name":"other","namespace":"kubescape"}` + case "scan local registration": + scanService = "" } - scan = fmt.Sprintf(`,{"metadata":{"name":"%s.spdx.softwarecomposition.kubescape.io","uid":"scan-service","resourceVersion":"3"},"spec":{"group":"spdx.softwarecomposition.kubescape.io","version":%q,"service":{"name":%q,"namespace":"kubescape"}}}`, scanVersion, scanVersion, scanService) + scan = fmt.Sprintf(`,{"metadata":{"name":"%s.spdx.softwarecomposition.kubescape.io","uid":"scan-service","resourceVersion":"3"},"spec":{"group":"spdx.softwarecomposition.kubescape.io","version":%q%s}}`, scanVersion, scanVersion, scanService) } respond(fmt.Sprintf(`{"apiVersion":"apiregistration.k8s.io/v1","kind":"APIServiceList","metadata":{"resourceVersion":"1","continue":%q},"items":[{"metadata":{"name":"v1.example.io","uid":"api-service","resourceVersion":%q},"spec":{"group":"example.io","version":"v1"%s}}%s]}`, continuation, rv, service, scan)) return diff --git a/scripts/verify-email-data-recovery/README.md b/scripts/verify-email-data-recovery/README.md index d9201d2d2d..316756c6bf 100644 --- a/scripts/verify-email-data-recovery/README.md +++ b/scripts/verify-email-data-recovery/README.md @@ -5,9 +5,9 @@ immutable main revision, on its first attempt, in the protected production environment. It shares the production deployment lock. It does not move the serving claim. -The server serves its store from the encrypted claim `email-data-encrypted` -(storage class `email-encrypted`); the original `private-mail-data` claim stays -mounted read-only as the rollback and is not the store this proof restores. +The server uses the encrypted V2 claim `email-data-encrypted-v2` +(storage class `email-encrypted-v2`). The previous claim is retained separately +from the serving pod. The driver verifies the serving pod, claim and backend identity, then imports one uniquely identified diagnostic message into an unsubscribed test mailbox. JMAP import does not submit an outgoing message. The current account credential stays @@ -19,10 +19,10 @@ their events, tasks, and account settings (sending identities, Sieve filter scripts and the vacation response). It reads identities, counts and object types only, never content, and keeps the counts in memory. An unchanged source requires equal restored counts; a source that changed while the backup ran -bounds each restored count by its two readings. Reading calendars and -identities makes the server create its default calendar and identity if the -account has none; the first census runs before the backup, so the restore must -hold them too. The receipt names each category `VERIFIED`, or `EMPTY` where +bounds each restored count by its two readings. Calendar and identity counts +require the state from a preceding changes query to match the list response. +The census leaves an untouched collection empty and refuses a change during +listing. The receipt names each category `VERIFIED`, or `EMPTY` where the source held none (for example, no tasks), and never a count. A fresh Velero filesystem backup selects the Email pod and includes its related @@ -32,7 +32,9 @@ the backup's overall Completed phase. Velero reads explicitly select its API group so another installed Backup resource cannot shadow the recovery object. The restore uses the completed, source-bound Kopia snapshot as bytes; backed-up pods, hooks, routes and credentials are not replayed. A fixed recovery -server reads a separate, three-replica encrypted volume with a new diagnostic key. +server reads a separate encrypted Longhorn V2 volume with a new diagnostic +key. The proof checks the volume's live key binding and three running replicas +on separate nodes and disks. A single reviewed administration declaration supplies the exact runtime digest for both source validation and the recovery reader. The declared binary base must remain compatible with the native datastore proof; missing or changed facts stop diff --git a/scripts/verify-email-data-recovery/census.go b/scripts/verify-email-data-recovery/census.go index af81d923d4..cd38756473 100644 --- a/scripts/verify-email-data-recovery/census.go +++ b/scripts/verify-email-data-recovery/census.go @@ -3,6 +3,7 @@ package main import ( "context" "errors" + "fmt" ) // storeCensus counts what one account's store holds, without reading any @@ -40,14 +41,43 @@ func (c *mailboxClient) count(ctx context.Context, method string) (int, error) { return queryTotal(result) } -// listAll reads every object of one type by identity only. -func (c *mailboxClient) listAll(ctx context.Context, method string) (int, error) { - result, err := c.call(ctx, method, object{"ids": nil, "properties": []any{"id"}}) +func (c *mailboxClient) collectionState(ctx context.Context, collection string) (string, error) { + changes, err := c.call(ctx, collection+"/changes", object{"sinceState": "n"}) + if err != nil { + return "", err + } + state := text(changes, "newState") + if text(changes, "oldState") != "n" || state == "" || changes["hasMoreChanges"] != false { + return "", fmt.Errorf("census %s: incomplete change state", collection) + } + if state == "n" { + for _, field := range []string{"created", "updated", "destroyed"} { + rows, ok := changes[field].([]any) + if !ok || len(rows) != 0 { + return "", fmt.Errorf("census %s: ambiguous initial state", collection) + } + } + } + return state, nil +} + +// listAll avoids initializing an untouched collection. An initialized +// collection must retain its state while listed, so regenerated entries +// cannot pass as restored data. +func (c *mailboxClient) listAll(ctx context.Context, collection string) (int, error) { + state, err := c.collectionState(ctx, collection) + if err != nil || state == "n" { + return 0, err + } + result, err := c.call(ctx, collection+"/get", object{"ids": nil, "properties": []any{"id"}}) if err != nil { return 0, err } list, ok := result["list"].([]any) - if !ok || len(items(result, "list")) != len(list) || text(result, "state") == "" || !noneMissing(result) { + if text(result, "state") != state { + return 0, fmt.Errorf("census %s: collection changed during listing", collection) + } + if !ok || len(items(result, "list")) != len(list) || !noneMissing(result) { return 0, errors.New("census-list") } return len(list), nil @@ -115,10 +145,8 @@ func (c *mailboxClient) calendarObjects(ctx context.Context) (events, tasks int, return events, tasks, nil } -// census reads the account's complete store census. Reading calendars and -// identities makes the server create its default calendar and identity if -// the account has none; the source census runs before the backup, so those -// defaults are part of what the restore must hold. +// census reads the account's store census, refusing a calendar or identity +// collection that was changed while being counted. func (c *mailboxClient) census(ctx context.Context) (storeCensus, error) { var s storeCensus var err error @@ -128,13 +156,17 @@ func (c *mailboxClient) census(ctx context.Context) (storeCensus, error) { if s.messages, err = c.count(ctx, "Email/query"); err != nil { return s, err } - if s.calendars, err = c.listAll(ctx, "Calendar/get"); err != nil { + if s.calendars, err = c.listAll(ctx, "Calendar"); err != nil { return s, err } - if s.events, s.tasks, err = c.calendarObjects(ctx); err != nil { - return s, err + if s.calendars > 0 { + if s.events, s.tasks, err = c.calendarObjects(ctx); err != nil { + return s, err + } + } else if state, err := c.collectionState(ctx, "CalendarEvent"); err != nil || state != "n" { + return s, errors.New("census-calendar-objects-without-calendar") } - if s.identities, err = c.listAll(ctx, "Identity/get"); err != nil { + if s.identities, err = c.listAll(ctx, "Identity"); err != nil { return s, err } if s.sieveScripts, err = c.count(ctx, "SieveScript/query"); err != nil { diff --git a/scripts/verify-email-data-recovery/census_test.go b/scripts/verify-email-data-recovery/census_test.go index 0fa1e0c15f..71c8be3c69 100644 --- a/scripts/verify-email-data-recovery/census_test.go +++ b/scripts/verify-email-data-recovery/census_test.go @@ -61,6 +61,8 @@ func (s *censusStore) serve(t *testing.T) *mailboxClient { result = query(s.scripts) case "CalendarEvent/query": result = query(len(s.objects)) + case "Calendar/changes", "Identity/changes", "CalendarEvent/changes": + result = object{"oldState": "n", "newState": "s1", "hasMoreChanges": false, "created": []any{}, "updated": []any{}, "destroyed": []any{}} case "Calendar/get": result = listed(s.calendars) case "Identity/get": @@ -97,6 +99,25 @@ func (s *censusStore) serve(t *testing.T) *mailboxClient { return client } +func TestCensusLeavesUninitializedCollectionsUntouched(t *testing.T) { + store := censusFixture() + store.mutate = func(method string, _, result object) { + if strings.HasSuffix(method, "/changes") { + result["newState"] = "n" + } + } + census, err := store.serve(t).census(context.Background()) + if err != nil || census.calendars != 0 || census.events != 0 || census.identities != 0 { + t.Fatalf("an untouched collection did not remain empty: %v", err) + } + for _, method := range store.methods { + switch method { + case "Calendar/get", "CalendarEvent/get", "CalendarEvent/query", "Identity/get": + t.Fatalf("census could initialize an empty collection through %s", method) + } + } +} + func censusFixture() *censusStore { objects := make([]string, 300) for i := range objects { @@ -173,6 +194,21 @@ func TestCensusRefusesIncompleteOrUnknownAnswers(t *testing.T) { result["notFound"] = []any{"id9"} } }, + "calendar-created-during-list": func(method string, _, result object) { + if method == "Calendar/get" { + result["state"] = "s2" + } + }, + "identity-created-during-list": func(method string, _, result object) { + if method == "Identity/get" { + result["state"] = "s2" + } + }, + "incomplete-identity-state": func(method string, _, result object) { + if method == "Identity/changes" { + result["hasMoreChanges"] = true + } + }, "missing-vacation": func(method string, _, result object) { if method == "VacationResponse/get" { result["list"] = []any{} diff --git a/scripts/verify-email-data-recovery/cleanup_test.go b/scripts/verify-email-data-recovery/cleanup_test.go index d70f243e19..5f693f2448 100644 --- a/scripts/verify-email-data-recovery/cleanup_test.go +++ b/scripts/verify-email-data-recovery/cleanup_test.go @@ -122,7 +122,8 @@ func cleanupFixture(t *testing.T, blocked bool) (*recoveryDriver, *cleanupAPI, c child(pvc, "spec")["volumeName"] = d.volumeName pvc["status"] = object{"phase": "Bound"} a.objects[cleanupKey("PersistentVolume", "", d.volumeName)] = object{"metadata": object{"name": d.volumeName, "uid": d.pvUID}, "spec": object{"claimRef": object{"namespace": i.namespace, "name": "data", "uid": claimUID}, "persistentVolumeReclaimPolicy": "Delete", "csi": object{"driver": "driver.longhorn.io", "volumeHandle": d.volumeName}}} - a.objects[cleanupKey("volumes.longhorn.io", "longhorn-system", d.volumeName)] = object{"metadata": object{"name": d.volumeName, "uid": d.volumeUID}, "spec": object{"encrypted": true, "numberOfReplicas": float64(3), "dataEngine": "v1"}} + setScratchKeyRefs(child(child(a.objects[cleanupKey("PersistentVolume", "", d.volumeName)], "spec"), "csi"), i.namespace) + a.objects[cleanupKey("volumes.longhorn.io", "longhorn-system", d.volumeName)] = object{"metadata": object{"name": d.volumeName, "uid": d.volumeUID}, "spec": object{"encrypted": true, "numberOfReplicas": float64(3), "dataEngine": "v2"}} a.objects[cleanupKey("DataDownload", "velero", i.namespace+"-download")]["status"] = object{"phase": "Completed"} a.objects[cleanupKey("Backup", "velero", i.namespace+"-backup")]["status"] = object{"phase": "Completed", "expiration": time.Now().Add(24 * time.Hour).UTC().Format(time.RFC3339)} pod, sourcePVC, pv := servingFixture() diff --git a/scripts/verify-email-data-recovery/fresh_observation_test.go b/scripts/verify-email-data-recovery/fresh_observation_test.go index a4d3cd3d27..c28e491d3e 100644 --- a/scripts/verify-email-data-recovery/fresh_observation_test.go +++ b/scripts/verify-email-data-recovery/fresh_observation_test.go @@ -29,7 +29,7 @@ func freshGraphFixture(w *freshRecoveryWitness) freshGraphAPI { child(backup, "status")["completionTimestamp"] = "2026-11-10T12:45:40Z" owner := items(child(snapshot, "metadata"), "ownerReferences")[0] owner["name"], owner["uid"] = i.namespace+"-backup", w.Backup.UID - child(snapshot, "metadata")["labels"] = object{"velero.io/pvc-uid": source.claimUID} + child(snapshot, "metadata")["labels"] = object{"velero.io/pvc-uid": source.claimUID, "velero.io/backup-uid": w.Backup.UID} child(snapshot, "status")["completionTimestamp"] = "2026-11-10T12:45:30Z" download := downloadManifest(i, text(child(snapshot, "status"), "snapshotID")) child(download, "metadata")["uid"] = w.Download.UID diff --git a/scripts/verify-email-data-recovery/mailbox.go b/scripts/verify-email-data-recovery/mailbox.go index e069924853..896bb3367e 100644 --- a/scripts/verify-email-data-recovery/mailbox.go +++ b/scripts/verify-email-data-recovery/mailbox.go @@ -60,15 +60,18 @@ func (c *mailboxClient) request(ctx context.Context, method, path, contentType s return data, nil } -// mailboxMethods names the JMAP capability of each method this client may -// call. Every method outside the marker lifecycle only reads. +// mailboxMethods names the JMAP capability of each permitted method. Census +// reads that can initialize defaults require an unchanged collection state. var mailboxMethods = map[string]string{ "Email/get": jmapMail, "Email/query": jmapMail, "Email/import": jmapMail, "Email/set": jmapMail, "Mailbox/get": jmapMail, "Mailbox/set": jmapMail, "Mailbox/query": jmapMail, "Calendar/get": "urn:ietf:params:jmap:calendars", "CalendarEvent/query": "urn:ietf:params:jmap:calendars", "CalendarEvent/get": "urn:ietf:params:jmap:calendars", - "Identity/get": "urn:ietf:params:jmap:submission", - "VacationResponse/get": "urn:ietf:params:jmap:vacationresponse", - "SieveScript/query": "urn:ietf:params:jmap:sieve", + "Calendar/changes": "urn:ietf:params:jmap:calendars", + "CalendarEvent/changes": "urn:ietf:params:jmap:calendars", + "Identity/get": "urn:ietf:params:jmap:submission", + "Identity/changes": "urn:ietf:params:jmap:submission", + "VacationResponse/get": "urn:ietf:params:jmap:vacationresponse", + "SieveScript/query": "urn:ietf:params:jmap:sieve", } const jmapMail = "urn:ietf:params:jmap:mail" diff --git a/scripts/verify-email-data-recovery/proof.go b/scripts/verify-email-data-recovery/proof.go index d741056f59..b67eed4e58 100644 --- a/scripts/verify-email-data-recovery/proof.go +++ b/scripts/verify-email-data-recovery/proof.go @@ -73,7 +73,12 @@ func proveBackup(b, p object, s sourceIdentity, i invocation, uid string, after if uid == "" || s.podUID == "" || text(bm, "uid") != uid || text(bm, "name") != i.namespace+"-backup" || text(bm, "namespace") != "velero" || text(child(bm, "labels"), recoveryLabel) != i.run || text(bs, "phase") != "Completed" || (bs["errors"] != nil && bs["errors"] != float64(0)) { return fail() } - owners := items(child(p, "metadata"), "ownerReferences") + meta := child(p, "metadata") + labels := child(meta, "labels") + if s.claimUID == "" || text(labels, "velero.io/pvc-uid") != s.claimUID || text(labels, "velero.io/backup-uid") != uid { + return fail() + } + owners := items(meta, "ownerReferences") if len(owners) != 1 || text(owners[0], "apiVersion") != "velero.io/v1" || text(owners[0], "kind") != "Backup" || text(owners[0], "name") != i.namespace+"-backup" || text(owners[0], "uid") != uid || owners[0]["controller"] != true { return fail() } diff --git a/scripts/verify-email-data-recovery/proof_test.go b/scripts/verify-email-data-recovery/proof_test.go index 310a28cc8c..579ed21775 100644 --- a/scripts/verify-email-data-recovery/proof_test.go +++ b/scripts/verify-email-data-recovery/proof_test.go @@ -12,6 +12,7 @@ func backupProofFixture() (object, object, sourceIdentity, invocation) { source := sourceIdentity{podUID: "source-pod-uid", claimUID: "source-claim-uid", volume: "data", pv: "source-volume", claimSize: "2Gi"} backup := object{"metadata": object{"name": i.namespace + "-backup", "namespace": "velero", "uid": "owned-backup-uid", "labels": object{recoveryLabel: i.run}}, "status": object{"phase": "Completed", "completionTimestamp": "2026-10-29T10:01:00Z", "errors": float64(0)}} pvb := object{"metadata": object{"namespace": "velero", "uid": "volume-backup-uid", "ownerReferences": []any{object{"apiVersion": "velero.io/v1", "kind": "Backup", "name": i.namespace + "-backup", "uid": "owned-backup-uid", "controller": true}}}, "spec": object{"pod": object{"name": "private-mail-0", "namespace": "private-mail", "uid": "source-pod-uid"}, "volume": "data", "backupStorageLocation": "default", "uploaderType": "kopia"}, "status": object{"phase": "Completed", "snapshotID": "0123456789abcdef0123456789abcdef", "completionTimestamp": "2026-10-29T10:00:59Z", "progress": object{"totalBytes": float64(4000), "bytesDone": float64(4000)}}} + child(pvb, "metadata")["labels"] = object{"velero.io/backup-uid": "owned-backup-uid", "velero.io/pvc-uid": source.claimUID} return backup, pvb, source, i } @@ -52,8 +53,11 @@ func TestMailboxSnapshotSelectionIgnoresScratchButRequiresUniqueData(t *testing. // of these foreign, stale, incomplete or empty backups as recovery evidence. func TestUnboundOrIncompleteBackupCannotBecomeRestoreInput(t *testing.T) { mutations := map[string]func(object, object){ - "foreign-backup": func(b, _ object) { child(b, "metadata")["uid"] = "replacement" }, - "wrong-owner": func(_, p object) { items(child(p, "metadata"), "ownerReferences")[0]["uid"] = "another-backup" }, + "foreign-backup": func(b, _ object) { child(b, "metadata")["uid"] = "replacement" }, + "wrong-owner": func(_, p object) { items(child(p, "metadata"), "ownerReferences")[0]["uid"] = "another-backup" }, + "wrong-claim": func(_, p object) { + child(child(p, "metadata"), "labels")["velero.io/pvc-uid"] = "replacement-claim" + }, "wrong-pod": func(_, p object) { child(child(p, "spec"), "pod")["uid"] = "replacement-pod" }, "wrong-namespace": func(_, p object) { child(child(p, "spec"), "pod")["namespace"] = "other" }, "wrong-volume": func(_, p object) { child(p, "spec")["volume"] = "another" }, diff --git a/scripts/verify-email-data-recovery/resources.go b/scripts/verify-email-data-recovery/resources.go index d5a729064f..d26412e263 100644 --- a/scripts/verify-email-data-recovery/resources.go +++ b/scripts/verify-email-data-recovery/resources.go @@ -21,7 +21,7 @@ func recoveryResources(i invocation, key, auth string) []object { sc["provisioner"] = "driver.longhorn.io" sc["reclaimPolicy"] = "Delete" sc["volumeBindingMode"] = "WaitForFirstConsumer" - params := object{"encrypted": "true", "numberOfReplicas": "3", "staleReplicaTimeout": "30", "fromBackup": "", "fsType": "ext4", "dataLocality": "disabled", "unmapMarkSnapChainRemoved": "ignored", "disableRevisionCounter": "true", "dataEngine": "v1", "backupTargetName": "default"} + params := object{"encrypted": "true", "numberOfReplicas": "3", "staleReplicaTimeout": "30", "fsType": "ext4", "dataLocality": "disabled", "unmapMarkSnapChainRemoved": "disabled", "dataEngine": "v2", "backupTargetName": "default"} for _, stage := range []string{"stage", "publish", "expand"} { params["csi.storage.k8s.io/node-"+stage+"-secret-name"] = "storage-key" params["csi.storage.k8s.io/node-"+stage+"-secret-namespace"] = i.namespace diff --git a/scripts/verify-email-data-recovery/resources_test.go b/scripts/verify-email-data-recovery/resources_test.go index 53bcada803..5611a56238 100644 --- a/scripts/verify-email-data-recovery/resources_test.go +++ b/scripts/verify-email-data-recovery/resources_test.go @@ -42,6 +42,13 @@ func TestRecoveryGraphNeverReplaysBackedUpWorkloadOrCredentials(t *testing.T) { } seen[kind+"/"+name] = true switch kind { + case "StorageClass": + params := child(o, "parameters") + if text(params, "dataEngine") != "v2" || text(params, "encrypted") != "true" || + text(params, "numberOfReplicas") != "3" || text(params, "csi.storage.k8s.io/node-stage-secret-namespace") != i.namespace || + text(o, "reclaimPolicy") != "Delete" || text(o, "volumeBindingMode") != "WaitForFirstConsumer" { + t.Fatal("fresh restoration did not request scoped, three-copy encrypted V2 storage") + } case "CiliumNetworkPolicy": spec := child(o, "spec") if len(items(spec, "ingressDeny")) != 1 || len(items(spec, "egressDeny")) != 1 || len(child(spec, "endpointSelector")) != 0 { diff --git a/scripts/verify-email-data-recovery/retained_protection_test.go b/scripts/verify-email-data-recovery/retained_protection_test.go index 74e3ada72a..b4c4621051 100644 --- a/scripts/verify-email-data-recovery/retained_protection_test.go +++ b/scripts/verify-email-data-recovery/retained_protection_test.go @@ -91,6 +91,7 @@ func protectedCleanupFixture(t *testing.T) (*recoveryDriver, *protectedAPI, cont protectedVolumeFixture("protection-uid", "private-mail", "private-mail-0", "serving-pod-uid", d.source.claimUID), protectedVolumeFixture("protection-uid", d.i.namespace, "reader", readerUID, claimUID), }} + child(a.volumes[0].(object), "spec")["volume"] = d.source.volume d.k = a return d, a, ctx } diff --git a/scripts/verify-email-data-recovery/run.go b/scripts/verify-email-data-recovery/run.go index 8927771f7b..63cd0147e0 100644 --- a/scripts/verify-email-data-recovery/run.go +++ b/scripts/verify-email-data-recovery/run.go @@ -9,6 +9,8 @@ import ( "errors" "regexp" "time" + + "github.com/devantler-tech/platform/internal/longhorninventory" ) func randomRecoveryValue() (string, error) { @@ -32,7 +34,7 @@ func (d *recoveryDriver) list(ctx context.Context, kind, ns, selector string) ([ return nil, err } var o object - if json.Unmarshal(data, &o) != nil { + if json.Unmarshal(data, &o) != nil || text(child(o, "metadata"), "continue") != "" || child(o, "metadata")["remainingItemCount"] != nil { return nil, errors.New("list-response") } raw, ok := o["items"].([]any) @@ -282,6 +284,10 @@ func (d *recoveryDriver) execute(ctx context.Context) error { if d.verdicts, err = censusVerdicts(sourceBefore, sourceAfter, restored); err != nil { return err } + d.stage = "restore-replica-proof" + if err = d.verifyRestoredReplicaHealth(ctx); err != nil { + return err + } d.stage = "source-retention" if err = d.sourceRetained(ctx); err != nil { return err @@ -295,6 +301,25 @@ func (d *recoveryDriver) execute(ctx context.Context) error { } return d.sourceRetained(ctx) } + +func (d *recoveryDriver) verifyRestoredReplicaHealth(ctx context.Context) error { + return waitRecovery(ctx, 90*time.Second, func() (bool, error) { + volume, found, err := d.lookup(ctx, "volumes.longhorn.io", d.volumeName, "longhorn-system") + meta := child(volume, "metadata") + if err != nil || !found || text(meta, "uid") != d.volumeUID || text(meta, "name") != d.volumeName || meta["deletionTimestamp"] != nil { + return false, errors.New("restore-volume-identity") + } + status := child(volume, "status") + if text(status, "state") != "attached" || text(status, "robustness") != "healthy" { + return false, nil + } + replicas, err := d.list(ctx, "replicas.longhorn.io", "longhorn-system", "") + if err != nil { + return false, err + } + return longhorninventory.V2ReplicaQuorum(volume, replicas), nil + }) +} func (d *recoveryDriver) observeRestoredStorage(ctx context.Context) error { claim, err := d.ref("PersistentVolumeClaim", "data", d.i.namespace) if err != nil { diff --git a/scripts/verify-email-data-recovery/source.go b/scripts/verify-email-data-recovery/source.go index 4e63bdee24..3821d740ab 100644 --- a/scripts/verify-email-data-recovery/source.go +++ b/scripts/verify-email-data-recovery/source.go @@ -3,18 +3,18 @@ package main import ( "context" "errors" + "path" "regexp" "strings" ) var kubernetesName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) -// The server serves its store from the encrypted claim (#5387). The original -// unencrypted claim stays mounted read-only by the copy step as the rollback; -// it is not the data volume this proof backs up and restores. const ( - servingClaim = "email-data-encrypted" - servingStorageClass = "email-encrypted" + servingClaim = "email-data-encrypted-v2" + servingStorageClass = "email-encrypted-v2" + servingVolume = "v2-data" + servingStorePath = "/var/lib/stalwart-v2" ) // Both serving profiles use the reviewed bundle. Bind runtime identities in a @@ -87,21 +87,61 @@ func proveServingSource(pod, pvc, pv object, expectedImage string) (sourceIdenti } found := false for _, volume := range items(child(pod, "spec"), "volumes") { - if text(volume, "name") == "data" && text(child(volume, "persistentVolumeClaim"), "claimName") == servingClaim && child(volume, "persistentVolumeClaim")["readOnly"] != true { - found = true + if volume["persistentVolumeClaim"] == nil { + continue + } + claim := child(volume, "persistentVolumeClaim") + if found || text(volume, "name") != servingVolume || text(claim, "claimName") != servingClaim || + (claim["readOnly"] != nil && claim["readOnly"] != false) { + return fail() } + found = true } cs, vs := child(pvc, "spec"), child(pv, "spec") name := text(cs, "volumeName") claimRef, csi := child(vs, "claimRef"), child(vs, "csi") - if !found || !kubernetesName.MatchString(name) || text(cs, "storageClassName") != servingStorageClass || text(child(child(cs, "resources"), "requests"), "storage") != "2Gi" || text(child(pvc, "status"), "phase") != "Bound" || text(vm, "name") != name || text(child(pv, "status"), "phase") != "Bound" || text(claimRef, "uid") != text(cm, "uid") || text(claimRef, "namespace") != "private-mail" || text(claimRef, "name") != servingClaim || text(csi, "driver") != "driver.longhorn.io" || text(csi, "volumeHandle") != name { + if !found || !privateMailServingMount(pod) || !kubernetesName.MatchString(name) || text(cs, "storageClassName") != servingStorageClass || + text(vs, "storageClassName") != servingStorageClass || text(child(child(cs, "resources"), "requests"), "storage") != "2Gi" || + text(child(pvc, "status"), "phase") != "Bound" || text(vm, "name") != name || text(child(pv, "status"), "phase") != "Bound" || + text(claimRef, "uid") != text(cm, "uid") || text(claimRef, "namespace") != "private-mail" || text(claimRef, "name") != servingClaim || + text(csi, "driver") != "driver.longhorn.io" || text(csi, "volumeHandle") != name { return fail() } reclaim := text(vs, "persistentVolumeReclaimPolicy") - if reclaim != "Retain" && reclaim != "Delete" { + attributes := child(csi, "volumeAttributes") + if reclaim != "Retain" || text(attributes, "dataEngine") != "v2" || text(attributes, "encrypted") != "true" || + text(attributes, "numberOfReplicas") != "3" { return fail() } - return sourceIdentity{podUID: text(pm, "uid"), claimUID: text(cm, "uid"), volume: "data", pv: name, claimSize: "2Gi", pvUID: text(vm, "uid"), reclaim: reclaim, containers: containers}, nil + return sourceIdentity{podUID: text(pm, "uid"), claimUID: text(cm, "uid"), volume: servingVolume, pv: name, + claimSize: "2Gi", pvUID: text(vm, "uid"), reclaim: reclaim, containers: containers}, nil +} + +func privateMailServingMount(pod object) bool { + for _, server := range items(child(pod, "spec"), "containers") { + if text(server, "name") != "private-mail" { + continue + } + found := false + for _, mount := range items(server, "volumeMounts") { + location := text(mount, "mountPath") + if !strings.HasPrefix(location, "/") || path.Clean(location) != location { + return false + } + if text(mount, "name") == servingVolume { + if found || location != servingStorePath || (mount["readOnly"] != nil && mount["readOnly"] != false) || + mount["subPath"] != nil || mount["subPathExpr"] != nil { + return false + } + found = true + } else if location == "/" || location == servingStorePath || + strings.HasPrefix(location, servingStorePath+"/") || strings.HasPrefix(servingStorePath, location+"/") { + return false + } + } + return found + } + return false } func (d *recoveryDriver) readSource(ctx context.Context) (sourceIdentity, error) { pod, found, err := d.lookup(ctx, "Pod", "private-mail-0", "private-mail") diff --git a/scripts/verify-email-data-recovery/source_test.go b/scripts/verify-email-data-recovery/source_test.go index c3dfb9cecf..6659259197 100644 --- a/scripts/verify-email-data-recovery/source_test.go +++ b/scripts/verify-email-data-recovery/source_test.go @@ -7,14 +7,19 @@ import ( "time" ) -// servingFixture is the production shape since the encrypted-storage cutover: -// the data volume is the encrypted claim and the original claim stays mounted -// read-only as the rollback. +// servingFixture binds the only persistent volume in the V2 serving pod. func servingFixture() (object, object, object) { - pod := object{"metadata": object{"name": "private-mail-0", "namespace": "private-mail", "uid": "serving-pod-uid", "labels": object{"statefulset.kubernetes.io/pod-name": "private-mail-0"}, "ownerReferences": []any{object{"kind": "StatefulSet", "name": "private-mail", "uid": "statefulset-uid", "controller": true}}}, "spec": object{"containers": []any{object{"name": "private-mail", "image": fixtureImage}}, "volumes": []any{object{"name": "data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted"}}, object{"name": "legacy-data", "persistentVolumeClaim": object{"claimName": "private-mail-data", "readOnly": true}}}}, "status": object{"phase": "Running", "conditions": []any{object{"type": "Ready", "status": "True"}}}} + pod := object{"metadata": object{"name": "private-mail-0", "namespace": "private-mail", "uid": "serving-pod-uid", "labels": object{"statefulset.kubernetes.io/pod-name": "private-mail-0"}, "ownerReferences": []any{object{"kind": "StatefulSet", "name": "private-mail", "uid": "statefulset-uid", "controller": true}}}, + "spec": object{ + "containers": []any{object{"name": "private-mail", "image": fixtureImage, "volumeMounts": []any{object{"name": "v2-data", "mountPath": "/var/lib/stalwart-v2"}}}}, + "volumes": []any{ + object{"name": "v2-data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted-v2"}}, + object{"name": "tmp", "emptyDir": object{}}, + }, + }, "status": object{"phase": "Running", "conditions": []any{object{"type": "Ready", "status": "True"}}}} child(pod, "status")["containerStatuses"] = []any{object{"name": "private-mail", "imageID": "runtime-mail", "ready": true, "restartCount": float64(0)}} - pvc := object{"metadata": object{"name": "email-data-encrypted", "namespace": "private-mail", "uid": "serving-claim-uid"}, "spec": object{"volumeName": "serving-volume", "storageClassName": "email-encrypted", "resources": object{"requests": object{"storage": "2Gi"}}}, "status": object{"phase": "Bound"}} - pv := object{"metadata": object{"name": "serving-volume", "uid": "serving-pv-uid"}, "spec": object{"claimRef": object{"namespace": "private-mail", "name": "email-data-encrypted", "uid": "serving-claim-uid"}, "persistentVolumeReclaimPolicy": "Retain", "csi": object{"driver": "driver.longhorn.io", "volumeHandle": "serving-volume"}}, "status": object{"phase": "Bound"}} + pvc := object{"metadata": object{"name": "email-data-encrypted-v2", "namespace": "private-mail", "uid": "serving-claim-uid"}, "spec": object{"volumeName": "serving-volume", "storageClassName": "email-encrypted-v2", "resources": object{"requests": object{"storage": "2Gi"}}}, "status": object{"phase": "Bound"}} + pv := object{"metadata": object{"name": "serving-volume", "uid": "serving-pv-uid"}, "spec": object{"claimRef": object{"namespace": "private-mail", "name": "email-data-encrypted-v2", "uid": "serving-claim-uid"}, "storageClassName": "email-encrypted-v2", "persistentVolumeReclaimPolicy": "Retain", "csi": object{"driver": "driver.longhorn.io", "volumeHandle": "serving-volume", "volumeAttributes": object{"dataEngine": "v2", "encrypted": "true", "numberOfReplicas": "3"}}}, "status": object{"phase": "Bound"}} return pod, pvc, pv } @@ -33,9 +38,18 @@ func TestTheEncryptedClaimIsTheServingSource(t *testing.T) { child(child(v, "spec"), "claimRef")["name"] = "private-mail-data" }, "unencrypted-class": func(_, c, _ object) { child(c, "spec")["storageClassName"] = "longhorn-wffc" }, + "v1-engine": func(_, _, v object) { child(child(child(v, "spec"), "csi"), "volumeAttributes")["dataEngine"] = "v1" }, + "nonretained-pv": func(_, _, v object) { child(v, "spec")["persistentVolumeReclaimPolicy"] = "Delete" }, "rollback-as-data": func(p, _, _ object) { - volumes := child(p, "spec")["volumes"].([]any) - volumes[0], volumes[1] = object{"name": "data", "persistentVolumeClaim": object{"claimName": "private-mail-data", "readOnly": true}}, object{"name": "legacy-data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted"}} + child(p, "spec")["volumes"] = []any{object{"name": "v2-data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted", "readOnly": true}}} + }, + "additional-persistent-store": func(p, _, _ object) { + spec := child(p, "spec") + spec["volumes"] = append(spec["volumes"].([]any), object{"name": "legacy-data", "persistentVolumeClaim": object{"claimName": "email-data-encrypted"}}) + }, + "shadowed-serving-path": func(p, _, _ object) { + server := items(child(p, "spec"), "containers")[0] + server["volumeMounts"] = append(server["volumeMounts"].([]any), object{"name": "config", "mountPath": "/var/lib/stalwart-v2/data"}) }, "read-only-data": func(p, _, _ object) { child(items(child(p, "spec"), "volumes")[0], "persistentVolumeClaim")["readOnly"] = true diff --git a/scripts/verify-email-data-recovery/transfer.go b/scripts/verify-email-data-recovery/transfer.go index 94049af806..649dfee9dc 100644 --- a/scripts/verify-email-data-recovery/transfer.go +++ b/scripts/verify-email-data-recovery/transfer.go @@ -30,7 +30,18 @@ func proveRestoredStorage(pvc, pv, volume object, i invocation, claimUID, source return errors.New("restored-storage-identity") } spec := child(volume, "spec") - if spec["encrypted"] != true || spec["numberOfReplicas"] != float64(3) || text(spec, "dataEngine") != "v1" { + engine := "v2" + if i == retainedRecovery || i == freshRetainedRecovery { + engine = "v1" + } else { + for _, stage := range []string{"nodeStageSecretRef", "nodePublishSecretRef", "nodeExpandSecretRef"} { + key := child(csi, stage) + if text(key, "name") != "storage-key" || text(key, "namespace") != i.namespace { + return errors.New("restored-storage-key") + } + } + } + if spec["encrypted"] != true || spec["numberOfReplicas"] != float64(3) || text(spec, "dataEngine") != engine { return errors.New("restored-storage-encryption") } return nil diff --git a/scripts/verify-email-data-recovery/transfer_test.go b/scripts/verify-email-data-recovery/transfer_test.go index 83b51d3d37..c7916aef91 100644 --- a/scripts/verify-email-data-recovery/transfer_test.go +++ b/scripts/verify-email-data-recovery/transfer_test.go @@ -30,10 +30,22 @@ func TestRestoredStorageMustBeSeparateEncryptedAndBoundToCreatedClaim(t *testing i, _ := authorizeDataRecovery(func(k string) string { return env[k] }) pvc := object{"metadata": object{"uid": "target-claim-uid"}, "spec": object{"storageClassName": i.namespace, "volumeName": "pvc-target-volume"}, "status": object{"phase": "Bound"}} pv := object{"metadata": object{"name": "pvc-target-volume", "uid": "target-volume-uid"}, "spec": object{"claimRef": object{"namespace": i.namespace, "name": "data", "uid": "target-claim-uid"}, "persistentVolumeReclaimPolicy": "Delete", "csi": object{"driver": "driver.longhorn.io", "volumeHandle": "pvc-target-volume"}}} - volume := object{"metadata": object{"name": "pvc-target-volume", "uid": "target-longhorn-uid"}, "spec": object{"encrypted": true, "numberOfReplicas": float64(3), "dataEngine": "v1"}} + csi := child(child(pv, "spec"), "csi") + setScratchKeyRefs(csi, i.namespace) + volume := object{"metadata": object{"name": "pvc-target-volume", "uid": "target-longhorn-uid"}, "spec": object{"encrypted": true, "numberOfReplicas": float64(3), "dataEngine": "v2"}} if err := proveRestoredStorage(pvc, pv, volume, i, "target-claim-uid", "source-volume", false); err != nil { - t.Fatal("isolated encrypted restored volume was refused") + t.Fatal("isolated encrypted V2 restored volume was refused") } + child(volume, "spec")["dataEngine"] = "v1" + if proveRestoredStorage(pvc, pv, volume, i, "target-claim-uid", "source-volume", false) == nil { + t.Fatal("fresh recovery accepted legacy V1 storage") + } + child(volume, "spec")["dataEngine"] = "v2" + csi["nodePublishSecretRef"] = object{"name": "email-storage-key", "namespace": "private-mail"} + if proveRestoredStorage(pvc, pv, volume, i, "target-claim-uid", "source-volume", false) == nil { + t.Fatal("restore accepted a volume bound to the live mailbox key") + } + setScratchKeyRefs(csi, i.namespace) child(volume, "spec")["encrypted"] = false if proveRestoredStorage(pvc, pv, volume, i, "target-claim-uid", "source-volume", false) == nil { t.Fatal("plaintext restored storage was accepted") @@ -44,3 +56,9 @@ func TestRestoredStorageMustBeSeparateEncryptedAndBoundToCreatedClaim(t *testing t.Fatal("serving volume was accepted as isolated storage") } } + +func setScratchKeyRefs(csi object, namespace string) { + for _, stage := range []string{"nodeStageSecretRef", "nodePublishSecretRef", "nodeExpandSecretRef"} { + csi[stage] = object{"name": "storage-key", "namespace": namespace} + } +} diff --git a/scripts/verify-email-storage-canary/main.go b/scripts/verify-email-storage-canary/main.go index 48576c54db..fbea7d759e 100644 --- a/scripts/verify-email-storage-canary/main.go +++ b/scripts/verify-email-storage-canary/main.go @@ -18,6 +18,8 @@ import ( "regexp" "strings" "time" + + "github.com/devantler-tech/platform/internal/longhorninventory" ) type kubernetes interface { @@ -326,7 +328,7 @@ func (r *runner) bindVolume(ctx context.Context, claim reference) error { if err != nil || json.Unmarshal(raw, &replicas) != nil { return false, errors.New("replica-response") } - return v2ReplicaQuorum(volume, items(replicas, "items")), nil + return longhorninventory.V2ReplicaQuorum(volume, items(replicas, "items")), nil }) } func (r *runner) detached(ctx context.Context) error { diff --git a/scripts/verify-email-storage-canary/proof.go b/scripts/verify-email-storage-canary/proof.go index 28b66050b4..3f106af1f6 100644 --- a/scripts/verify-email-storage-canary/proof.go +++ b/scripts/verify-email-storage-canary/proof.go @@ -59,30 +59,6 @@ func checkVolume(o object, name, uid, engine string, detached bool) error { return nil } -func v2ReplicaQuorum(volume object, replicas []object) bool { - name, uid := text(child(volume, "metadata"), "name"), text(child(volume, "metadata"), "uid") - if name == "" || uid == "" || replicas == nil { - return false - } - nodes, disks, identities := map[string]bool{}, map[string]bool{}, map[string]bool{} - for _, replica := range replicas { - spec, meta := child(replica, "spec"), child(replica, "metadata") - if text(spec, "volumeName") != name { - continue - } - owners := items(meta, "ownerReferences") - node, disk, id := text(spec, "nodeID"), text(spec, "diskID"), text(meta, "uid") - if len(owners) != 1 || text(owners[0], "apiVersion") != "longhorn.io/v1beta2" || text(owners[0], "kind") != "Volume" || - text(owners[0], "name") != name || text(owners[0], "uid") != uid || text(meta, "namespace") != "longhorn-system" || - text(spec, "dataEngine") != "v2" || text(spec, "healthyAt") == "" || text(spec, "failedAt") != "" || - text(child(replica, "status"), "currentState") != "running" || meta["deletionTimestamp"] != nil || - node == "" || disk == "" || id == "" || nodes[node] || disks[disk] || identities[id] { - return false - } - nodes[node], disks[disk], identities[id] = true, true, true - } - return len(nodes) == 3 -} func negativeMount(pod object, events []object, uid, volume, mode string) bool { if uid == "" || text(child(pod, "metadata"), "uid") != uid || text(child(pod, "status"), "phase") != "Pending" { return false diff --git a/scripts/verify-email-storage-canary/proof_test.go b/scripts/verify-email-storage-canary/proof_test.go index 34fa5c6254..e1148e609e 100644 --- a/scripts/verify-email-storage-canary/proof_test.go +++ b/scripts/verify-email-storage-canary/proof_test.go @@ -5,6 +5,8 @@ import ( "strconv" "strings" "testing" + + "github.com/devantler-tech/platform/internal/longhorninventory" ) func TestDispatchAuthorization(t *testing.T) { @@ -87,7 +89,7 @@ func TestV2ReplicaQuorumRequiresThreeIndependentNativeCopies(t *testing.T) { } return replicas } - if replicas := newReplicas(); !v2ReplicaQuorum(volume, replicas) || v2ReplicaQuorum(volume, replicas[:2]) { + if replicas := newReplicas(); !longhorninventory.V2ReplicaQuorum(volume, replicas) || longhorninventory.V2ReplicaQuorum(volume, replicas[:2]) { t.Fatal("expected exactly three healthy copies") } for _, test := range []struct { @@ -104,7 +106,7 @@ func TestV2ReplicaQuorumRequiresThreeIndependentNativeCopies(t *testing.T) { t.Run(test.name, func(t *testing.T) { replicas := newReplicas() test.change(replicas[0]) - if v2ReplicaQuorum(volume, replicas) { + if longhorninventory.V2ReplicaQuorum(volume, replicas) { t.Fatal("unproven replica quorum accepted") } }) From ee0c973d06d5ae9c1edb3b9ff737c491444c089c Mon Sep 17 00:00:00 2001 From: Nikolai Emil Damm Date: Fri, 27 Nov 2026 06:10:44 +0100 Subject: [PATCH 5/6] fix(email): verify calendar event state through the final read Compare every event page with the pinned server collection state and recheck an empty result. Refuse a concurrent change even when returned IDs and counts still match. Part of #6256 --- scripts/verify-email-data-recovery/census.go | 14 ++++++++++- .../verify-email-data-recovery/census_test.go | 25 ++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/scripts/verify-email-data-recovery/census.go b/scripts/verify-email-data-recovery/census.go index cd38756473..4ddfbc68f8 100644 --- a/scripts/verify-email-data-recovery/census.go +++ b/scripts/verify-email-data-recovery/census.go @@ -107,6 +107,16 @@ func (c *mailboxClient) calendarObjects(ctx context.Context) (events, tasks int, total, state = pageTotal, text(page, "queryState") ids, _ := page["ids"].([]any) if len(ids) == 0 { + if total != 0 { + return 0, 0, errors.New("census-calendar-total") + } + confirm, err := c.call(ctx, "CalendarEvent/query", object{"calculateTotal": true, "position": 0, "limit": 1}) + if err != nil { + return 0, 0, err + } + if count, err := queryTotal(confirm); err != nil || count != 0 || text(confirm, "queryState") != state || confirm["position"] != float64(0) { + return 0, 0, errors.New("census-calendar-query") + } break } objects, err := c.call(ctx, "CalendarEvent/get", object{"ids": ids, "properties": []any{"id", "@type"}}) @@ -114,7 +124,9 @@ func (c *mailboxClient) calendarObjects(ctx context.Context) (events, tasks int, return 0, 0, err } list := items(objects, "list") - if raw, _ := objects["list"].([]any); len(list) != len(ids) || len(raw) != len(ids) || !noneMissing(objects) { + // The pinned Stalwart release reports the same calendar item change + // state in queryState and get state. + if raw, _ := objects["list"].([]any); text(objects, "state") != state || len(list) != len(ids) || len(raw) != len(ids) || !noneMissing(objects) { return 0, 0, errors.New("census-calendar-objects") } requested := map[any]bool{} diff --git a/scripts/verify-email-data-recovery/census_test.go b/scripts/verify-email-data-recovery/census_test.go index 71c8be3c69..933a98bdca 100644 --- a/scripts/verify-email-data-recovery/census_test.go +++ b/scripts/verify-email-data-recovery/census_test.go @@ -74,7 +74,7 @@ func (s *censusStore) serve(t *testing.T) *mailboxClient { _, _ = fmt.Sscanf(id.(string), "id%d", &index) list = append(list, object{"id": id, "@type": s.objects[index]}) } - result = object{"state": "s1", "list": list, "notFound": []any{}} + result = object{"state": "q1", "list": list, "notFound": []any{}} case "VacationResponse/get": result = object{"state": "s1", "list": []any{}, "notFound": []any{"singleton"}} if s.vacation { @@ -118,6 +118,24 @@ func TestCensusLeavesUninitializedCollectionsUntouched(t *testing.T) { } } +func TestCensusRechecksAnEmptyCalendarEventQuery(t *testing.T) { + store := censusFixture() + store.objects = nil + queries := 0 + store.mutate = func(method string, _, result object) { + if method != "CalendarEvent/query" { + return + } + queries++ + if queries > 1 { + result["queryState"] = "q2" + } + } + if _, err := store.serve(t).census(context.Background()); err == nil || queries != 2 { + t.Fatal("the empty calendar event query was accepted after a state change") + } +} + func censusFixture() *censusStore { objects := make([]string, 300) for i := range objects { @@ -175,6 +193,11 @@ func TestCensusRefusesIncompleteOrUnknownAnswers(t *testing.T) { result["notFound"] = []any{"id0"} } }, + "calendar-last-get-state-changed": func(method string, args, result object) { + if method == "CalendarEvent/get" && args["ids"].([]any)[0] == "id256" { + result["state"] = "q2" + } + }, "query-changed-between-pages": func(method string, args, result object) { if method == "CalendarEvent/query" && args["position"] != float64(0) { result["queryState"] = "q2" From b98dc14782b3e51c3060b3f62f227ab559675f26 Mon Sep 17 00:00:00 2001 From: Nikolai Emil Damm Date: Fri, 27 Nov 2026 06:36:16 +0100 Subject: [PATCH 6/6] fix(storage): allow a deleted calendar in the Mail restore census Use the account owner change feed after a verified empty calendar listing. Reject created and updated objects while accepting tombstones without loading the calendar event cache. --- scripts/verify-email-data-recovery/census.go | 47 ++++++++++++------- .../verify-email-data-recovery/census_test.go | 40 ++++++++++++++++ 2 files changed, 70 insertions(+), 17 deletions(-) diff --git a/scripts/verify-email-data-recovery/census.go b/scripts/verify-email-data-recovery/census.go index 4ddfbc68f8..5ee069fe32 100644 --- a/scripts/verify-email-data-recovery/census.go +++ b/scripts/verify-email-data-recovery/census.go @@ -41,32 +41,38 @@ func (c *mailboxClient) count(ctx context.Context, method string) (int, error) { return queryTotal(result) } -func (c *mailboxClient) collectionState(ctx context.Context, collection string) (string, error) { +type collectionChanges struct { + state string + liveChanges bool +} + +func (c *mailboxClient) collectionChanges(ctx context.Context, collection string) (collectionChanges, error) { changes, err := c.call(ctx, collection+"/changes", object{"sinceState": "n"}) if err != nil { - return "", err + return collectionChanges{}, err } - state := text(changes, "newState") - if text(changes, "oldState") != "n" || state == "" || changes["hasMoreChanges"] != false { - return "", fmt.Errorf("census %s: incomplete change state", collection) + result := collectionChanges{state: text(changes, "newState")} + if text(changes, "oldState") != "n" || result.state == "" || changes["hasMoreChanges"] != false { + return collectionChanges{}, fmt.Errorf("census %s: incomplete change state", collection) } - if state == "n" { - for _, field := range []string{"created", "updated", "destroyed"} { - rows, ok := changes[field].([]any) - if !ok || len(rows) != 0 { - return "", fmt.Errorf("census %s: ambiguous initial state", collection) - } + for _, field := range []string{"created", "updated", "destroyed"} { + rows, ok := changes[field].([]any) + if !ok || (result.state == "n" && len(rows) != 0) { + return collectionChanges{}, fmt.Errorf("census %s: inconsistent changes", collection) + } + if field != "destroyed" && len(rows) != 0 { + result.liveChanges = true } } - return state, nil + return result, nil } // listAll avoids initializing an untouched collection. An initialized // collection must retain its state while listed, so regenerated entries // cannot pass as restored data. func (c *mailboxClient) listAll(ctx context.Context, collection string) (int, error) { - state, err := c.collectionState(ctx, collection) - if err != nil || state == "n" { + changes, err := c.collectionChanges(ctx, collection) + if err != nil || changes.state == "n" { return 0, err } result, err := c.call(ctx, collection+"/get", object{"ids": nil, "properties": []any{"id"}}) @@ -74,7 +80,7 @@ func (c *mailboxClient) listAll(ctx context.Context, collection string) (int, er return 0, err } list, ok := result["list"].([]any) - if text(result, "state") != state { + if text(result, "state") != changes.state { return 0, fmt.Errorf("census %s: collection changed during listing", collection) } if !ok || len(items(result, "list")) != len(list) || !noneMissing(result) { @@ -175,8 +181,15 @@ func (c *mailboxClient) census(ctx context.Context) (storeCensus, error) { if s.events, s.tasks, err = c.calendarObjects(ctx); err != nil { return s, err } - } else if state, err := c.collectionState(ctx, "CalendarEvent"); err != nil || state != "n" { - return s, errors.New("census-calendar-objects-without-calendar") + } else { + // Calendar/get established that no calendar exists. A calendar event + // query can create a default calendar when the server rebuilds its + // cache. Use the owner's change feed here to reject surviving events + // or tasks while allowing a collection whose last objects were deleted. + changes, err := c.collectionChanges(ctx, "CalendarEvent") + if err != nil || changes.liveChanges { + return s, errors.New("census-calendar-objects-without-calendar") + } } if s.identities, err = c.listAll(ctx, "Identity"); err != nil { return s, err diff --git a/scripts/verify-email-data-recovery/census_test.go b/scripts/verify-email-data-recovery/census_test.go index 933a98bdca..a4baa9667c 100644 --- a/scripts/verify-email-data-recovery/census_test.go +++ b/scripts/verify-email-data-recovery/census_test.go @@ -118,6 +118,46 @@ func TestCensusLeavesUninitializedCollectionsUntouched(t *testing.T) { } } +func TestCensusChecksInitializedEventsAfterLastCalendarRemoved(t *testing.T) { + for _, test := range []struct { + name string + liveField string + }{ + {name: "empty after deletion"}, + {name: "created item without calendar", liveField: "created"}, + {name: "updated item without calendar", liveField: "updated"}, + } { + t.Run(test.name, func(t *testing.T) { + store := censusFixture() + store.calendars = 0 + store.objects = nil + store.mutate = func(method string, _, result object) { + if method == "CalendarEvent/changes" { + result["destroyed"] = []any{"deleted-item"} + if test.liveField != "" { + result[test.liveField] = []any{"surviving-item"} + } + } + } + census, err := store.serve(t).census(context.Background()) + for _, method := range store.methods { + if method == "CalendarEvent/query" || method == "CalendarEvent/get" { + t.Fatalf("%s can initialize a default calendar", method) + } + } + if test.liveField == "" { + if err != nil || census.calendars != 0 || census.events != 0 || census.tasks != 0 { + t.Fatalf("census of an initialized empty event collection: %+v, %v", census, err) + } + return + } + if err == nil || !strings.Contains(err.Error(), "census-calendar-objects-without-calendar") { + t.Fatalf("orphaned calendar content did not fail the census: %v", err) + } + }) + } +} + func TestCensusRechecksAnEmptyCalendarEventQuery(t *testing.T) { store := censusFixture() store.objects = nil