feat(purge): erase the tenant's Prüfwerk data before deleting it #154
No files matched your search
@@ -1,11 +1,15 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -107,10 +111,10 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// adminPurgeTenant is DELETE /v1/admin/tenants/{id}?confirm=<slug>: removes an
|
||||
// archived tenant for good, frees its name, and takes its sign-in with it.
|
||||
// Order matters: document files, then Keycloak, then the database, so a
|
||||
// failure never leaves files or accounts behind a deleted record. The ERP
|
||||
// customer stays (bookkeeping), and so does the audit trail, plus one
|
||||
// tenant.purged event that names the staff member.
|
||||
// Order matters: Prüfwerk's data, document files, then Keycloak, then the
|
||||
// database, so a failure never leaves data or accounts behind a deleted
|
||||
// record. The ERP customer stays (bookkeeping), and so does the audit trail,
|
||||
// plus one tenant.purged event that names the staff member.
|
||||
func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
@@ -154,6 +158,15 @@ func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusServiceUnavailable, "storage_unavailable", "document storage is not configured")
|
||||
return
|
||||
}
|
||||
// Prüfwerk keeps the tenant's targets, findings and code in its own
|
||||
// database and on disk. They go first: if Prüfwerk cannot erase them,
|
||||
// nothing else is removed and staff can try again.
|
||||
pwErase, err := s.erasePruefwerkData(ctx, t.ID)
|
||||
if err != nil {
|
||||
s.Log.Error("purge: pruefwerk erasure failed", "tenant_id", t.ID, "err", err)
|
||||
writeError(w, http.StatusBadGateway, "pruefwerk_error", "Prüfwerk could not delete the workspace's data; nothing was removed")
|
||||
return
|
||||
}
|
||||
for _, d := range docs {
|
||||
if err := s.Objects.Delete(ctx, d.ObjectKey); err != nil {
|
||||
s.Log.Error("purge: delete document object failed", "tenant_id", t.ID, "document", d.ID, "err", err)
|
||||
@@ -193,9 +206,64 @@ func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) {
|
||||
if t.ErpCustomerID != "" {
|
||||
meta["erp_customer_id_kept"] = t.ErpCustomerID
|
||||
}
|
||||
meta["pruefwerk_data"] = pwErase.Status
|
||||
if pwErase.FilesNotRemoved > 0 {
|
||||
meta["pruefwerk_files_not_removed"] = pwErase.FilesNotRemoved
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
Action: "tenant.purged", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug,
|
||||
ActorType: "service", Metadata: meta,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{"status": "purged", "accounts_removed": accounts, "documents_removed": len(docs)})
|
||||
}
|
||||
|
||||
// pruefwerkErasure is what the purge records about Prüfwerk: "deleted", or
|
||||
// "not_configured" when this environment has no Prüfwerk.
|
||||
type pruefwerkErasure struct {
|
||||
Status string
|
||||
FilesNotRemoved int
|
||||
}
|
||||
|
||||
// erasePruefwerkData asks Prüfwerk to drop the tenant's database and files
|
||||
// (DELETE …/platform/tenants/{id}/data, the registry's service token). Any
|
||||
// answer but 200 is an error.
|
||||
func (s *Server) erasePruefwerkData(ctx context.Context, tenantID string) (pruefwerkErasure, error) {
|
||||
base, _, err := s.pruefwerkBase(ctx)
|
||||
if errors.Is(err, errPruefwerkAbsent) {
|
||||
return pruefwerkErasure{Status: "not_configured"}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return pruefwerkErasure{}, err
|
||||
}
|
||||
body, _ := json.Marshal(map[string]string{"confirm": tenantID})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, base+"/tenants/"+url.PathEscape(tenantID)+"/data", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return pruefwerkErasure{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
tok, err := s.Keycloak.ServiceToken(ctx)
|
||||
if err != nil {
|
||||
return pruefwerkErasure{}, err
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
|
||||
if err != nil {
|
||||
return pruefwerkErasure{}, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return pruefwerkErasure{}, fmt.Errorf("pruefwerk: %s: %s", resp.Status, strings.TrimSpace(string(raw)))
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
FilesNotRemoved int `json:"files_not_removed"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil || out.Status != "deleted" {
|
||||
return pruefwerkErasure{}, fmt.Errorf("pruefwerk: unexpected answer: %.200s", raw)
|
||||
}
|
||||
return pruefwerkErasure{Status: "deleted", FilesNotRemoved: out.FilesNotRemoved}, nil
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -169,3 +171,74 @@ func TestPurgeKeepsIntakeReports(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The purge erases the tenant's Prüfwerk data first (DELETE
|
||||
// …/platform/tenants/{id}/data with the service token). If Prüfwerk fails,
|
||||
// nothing else is removed; without Prüfwerk in the catalog it is skipped.
|
||||
func TestPurgeErasesPruefwerkData(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
var calls []string
|
||||
var gotAuth, gotBody string
|
||||
fail := true
|
||||
pw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls = append(calls, r.Method+" "+r.URL.Path)
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(b)
|
||||
if fail {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"status":"deleted","tenant_id":"x","files_removed":3,"files_not_removed":1}`)
|
||||
}))
|
||||
defer pw.Close()
|
||||
h.app.Cfg.PruefwerkPlatformURL = pw.URL + "/api/v1/platform/"
|
||||
|
||||
tn := createWithAdmin(t, h, "pw-purge-co", "it@pw-purge.test")
|
||||
if resp, _ := h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": "archived", "source": "test"}); resp.StatusCode != 200 {
|
||||
t.Fatalf("archive: %d", resp.StatusCode)
|
||||
}
|
||||
base := "/v1/admin/tenants/" + tn.ID + "?confirm=pw-purge-co"
|
||||
|
||||
resp, raw := h.do("DELETE", base, nil)
|
||||
if resp.StatusCode != http.StatusBadGateway || !strings.Contains(string(raw), "pruefwerk_error") {
|
||||
t.Fatalf("pruefwerk down: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
if len(h.kcMock.Purged) != 0 {
|
||||
t.Fatalf("sign-in removed although Prüfwerk failed: %v", h.kcMock.Purged)
|
||||
}
|
||||
if resp, _ := h.do("GET", "/v1/tenants/"+tn.ID, nil); resp.StatusCode != 200 {
|
||||
t.Fatalf("tenant gone after failed erasure: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
fail = false
|
||||
if resp, raw := h.do("DELETE", base, nil); resp.StatusCode != 200 {
|
||||
t.Fatalf("purge: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
want := "DELETE /api/v1/platform/tenants/" + tn.ID + "/data"
|
||||
if len(calls) != 2 || calls[1] != want {
|
||||
t.Fatalf("calls: %v, want %s", calls, want)
|
||||
}
|
||||
if gotAuth != "Bearer mock-service-token" || gotBody != `{"confirm":"`+tn.ID+`"}` {
|
||||
t.Fatalf("request: %q %q", gotAuth, gotBody)
|
||||
}
|
||||
_, raw = h.do("GET", "/v1/audit?action=tenant.purged", nil)
|
||||
if !strings.Contains(string(raw), `"pruefwerk_data":"deleted"`) || !strings.Contains(string(raw), `"pruefwerk_files_not_removed":1`) {
|
||||
t.Fatalf("audit: %s", raw)
|
||||
}
|
||||
|
||||
h.app.Cfg.PruefwerkPlatformURL = ""
|
||||
other := createWithAdmin(t, h, "no-pw-co", "it@no-pw.test")
|
||||
if resp, _ := h.do("POST", "/v1/tenants/"+other.ID+"/status", map[string]any{"status": "archived", "source": "test"}); resp.StatusCode != 200 {
|
||||
t.Fatalf("archive: %d", resp.StatusCode)
|
||||
}
|
||||
// No Prüfwerk in this environment's catalog: the purge goes ahead.
|
||||
if resp, raw := h.do("DELETE", "/v1/admin/tenants/"+other.ID+"?confirm=no-pw-co", nil); resp.StatusCode != 200 {
|
||||
t.Fatalf("purge without prüfwerk: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
_, raw = h.do("GET", "/v1/audit?action=tenant.purged", nil)
|
||||
if !strings.Contains(string(raw), `"pruefwerk_data":"not_configured"`) {
|
||||
t.Fatalf("audit without prüfwerk: %s", raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -376,6 +376,10 @@ func (s *Server) listProjectTargets(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items, "available": true})
|
||||
}
|
||||
|
||||
// errPruefwerkAbsent: this environment's catalog has no Prüfwerk (on-prem
|
||||
// without it, or a test setup), as opposed to Prüfwerk not answering.
|
||||
var errPruefwerkAbsent = errors.New("pruefwerk: not in this environment's catalog")
|
||||
|
||||
// pruefwerkBase is Prüfwerk's platform API root and dashboard URL for this
|
||||
// environment, derived from the catalog (provision URL …/tenants/{id}/provision,
|
||||
// launch URL).
|
||||
@@ -384,13 +388,16 @@ func (s *Server) pruefwerkBase(ctx context.Context) (platform, launch string, er
|
||||
return strings.TrimRight(s.Cfg.PruefwerkPlatformURL, "/"), strings.TrimRight(s.Cfg.PruefwerkURL, "/"), nil
|
||||
}
|
||||
p, err := s.Store.GetProduct(ctx, "pruefwerk")
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return "", "", errPruefwerkAbsent
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
prov := p.ProvisionURLs[s.env()]
|
||||
const suffix = "/tenants/{id}/provision"
|
||||
if !strings.HasSuffix(prov, suffix) {
|
||||
return "", "", fmt.Errorf("pruefwerk: no provision URL for %q", s.env())
|
||||
return "", "", fmt.Errorf("%w: no provision URL for %q", errPruefwerkAbsent, s.env())
|
||||
}
|
||||
return strings.TrimSuffix(prov, suffix), strings.TrimRight(p.LaunchURLs[s.env()], "/"), nil
|
||||
}
|
||||
|
||||
+8
-2
@@ -1397,9 +1397,13 @@ paths:
|
||||
delete:
|
||||
summary: Delete an archived tenant for good.
|
||||
description: |
|
||||
Removes the document files, the Keycloak organization and the accounts that belong to the tenant,
|
||||
First asks Prüfwerk to erase the tenant's data (its database and files, through Prüfwerk's
|
||||
platform API with the registry's service token); if that fails, nothing is removed (502
|
||||
pruefwerk_error). Without Prüfwerk in this environment's catalog the step is skipped. Then
|
||||
removes the document files, the Keycloak organization and the accounts that belong to the tenant,
|
||||
then the tenant with everything attached. The ERP customer and the audit trail stay; a
|
||||
tenant.purged event records who did it. Frees the tenant's name.
|
||||
tenant.purged event records who did it and whether Prüfwerk's data was deleted. Frees the
|
||||
tenant's name.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: query, name: confirm, required: true, schema: { type: string }, description: The tenant's slug. }
|
||||
@@ -1408,6 +1412,8 @@ paths:
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
"502": { description: "pruefwerk_error (nothing removed) or storage_error." }
|
||||
"503": { description: Keycloak or document storage unavailable. }
|
||||
/v1/admin/tenants/{id}/trial:
|
||||
post:
|
||||
summary: Extend a trial.
|
||||
|
||||
Reference in new issue
Block a user