hub v0.61.0 + felhom-tenantsync v1.1.0: Customer RESET (middle lifecycle tier)

One operator action returns a customer to pre-first-install: all operational
state dies (offsite repo, PBS namespace+backups, DR recipe, one-time secret,
claim state, retained escrow custody); identity + basic config + provenance +
events survive. Sits between host delete and customer Delete.

- store/customer_reset.go: customer_resets journal, live inventory, ack-gated
  purge (never touches identity/provenance/events), DeleteClaim.
- claim.ResetToUnclaimed: delete claim row -> fresh code next onboarding.
- offsite.Deprovision (idempotent) + OffsiteIdentifier + ClearProvisionedDescriptor.
- tenantsync.Deprovision + felhom-tenantsync.sh deprovision op (destroys ns +
  backup groups + token; shared user untouched; idempotent).
- web/customer_reset.go: GET reset -> inventory JSON; POST -> orchestration
  (external teardown FIRST, DB purge LAST; refuse-while-hosts; typed-id +
  separate escrow ack). Amber RESET card distinct from red Danger-zone Delete.
- Red-proofs: ack-gate + partial-failure resumability (both proven red);
  store ack-gating + journal round-trip; offsite idempotency + descriptor clear;
  RESET-card render. Green: build + vet + test.
This commit is contained in:
2026-07-17 13:09:04 +02:00
parent 6b1fbca51d
commit 4009401f46
17 changed files with 1193 additions and 13 deletions
+228
View File
@@ -0,0 +1,228 @@
package web
import (
"context"
"encoding/json"
"net/http"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/offsite"
)
// Customer RESET (v0.61.0) — the middle lifecycle tier (host delete < RESET < customer DELETE). One
// operator action returns a customer to pre-first-install: every OPERATIONAL trace dies (offsite repo
// + PBS namespace + credentials + DR recipe + claim state + retained escrow custody), while IDENTITY
// and the BASIC CONFIG survive (customer_configs row, provenance rows, the audit event stream).
//
// Orchestration discipline (spec §3): external teardown runs FIRST, the DB purge runs LAST
// (publish-last). Every leg is idempotent, so a partial run is simply re-run from the top — a failed
// external leg is a clean journal entry, and the DB purge (which erases the descriptors that say what
// still needs tearing down) is withheld until every external leg is ok. Provenance/events are NEVER
// wiped — the audit trail outlives every lifecycle tier.
// offsiteChoice reads the customer's offsite tier selection out of config_json (the same shape the
// re-issue/freeze handlers read). enabled=false means no offsite leg to run.
func offsiteChoice(configJSON string) (enabled bool, typ string) {
var o struct {
Offsite struct {
Enabled bool `json:"enabled"`
Type string `json:"type"`
} `json:"offsite"`
}
_ = json.Unmarshal([]byte(configJSON), &o)
return o.Offsite.Enabled, o.Offsite.Type
}
// handleCustomerResetPreview — GET /configs/{id}/reset. Returns the live inventory the confirm surface
// renders (ruling 4): what a RESET would destroy right now. Read-only — no writes, no external calls
// beyond the label lookups needed to name the offsite resource. `refused` is true when a host row still
// exists (ruling 3: RESET refuses until the operator deletes the hosts first).
func (s *Server) handleCustomerResetPreview(w http.ResponseWriter, r *http.Request, customerID string) {
cfg, err := s.store.GetCustomerConfig(customerID)
if err != nil {
s.logger.Printf("[ERROR] reset preview %s: %v", customerID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if cfg == nil {
http.NotFound(w, r)
return
}
inv, err := s.store.CustomerResetInventory(customerID)
if err != nil {
s.logger.Printf("[ERROR] reset preview %s: inventory: %v", customerID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
offsiteEnabled, offsiteType := offsiteChoice(cfg.ConfigJSON)
offsiteName := ""
if offsiteEnabled && s.offsite != nil {
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if n, oerr := s.offsite.OffsiteIdentifier(ctx, customerID, offsiteType); oerr != nil {
s.logger.Printf("[WARN] reset preview %s: offsite identifier lookup: %v", customerID, oerr)
} else {
offsiteName = n
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"customer_id": customerID,
"host_count": inv.HostCount,
"refused": inv.HostCount > 0, // ruling 3
"superseded_blobs": inv.SupersededBlobs,
"escrow_ack_required": inv.SupersededBlobs > 0, // ruling 1: separate custody-destruction ack
"dr_recipe_present": inv.DRRecipePresent,
"one_time_secret": inv.OneTimeSecretPresent,
"claim_present": inv.ClaimPresent,
"offsite_enabled": offsiteEnabled,
"offsite_type": offsiteType,
"offsite_identifier": offsiteName,
"pbs_tenancy_configured": s.tenantsync != nil,
})
}
// handleCustomerReset — POST /configs/{id}/reset. Executes the reset. Preconditions (Scenario A + the
// confirm gates) are checked BEFORE any write or external call: a refused reset leaves zero side effects.
func (s *Server) handleCustomerReset(w http.ResponseWriter, r *http.Request, customerID string) {
cfg, err := s.store.GetCustomerConfig(customerID)
if err != nil {
s.logger.Printf("[ERROR] reset %s: %v", customerID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if cfg == nil {
http.NotFound(w, r)
return
}
inv, err := s.store.CustomerResetInventory(customerID)
if err != nil {
s.logger.Printf("[ERROR] reset %s: inventory: %v", customerID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Ruling 3 (Scenario A): RESET REFUSES while any host row exists. RESET never deletes hosts — the
// operator deletes them first. 409 with ZERO writes and ZERO external calls.
if inv.HostCount > 0 {
s.logger.Printf("[WARN] reset %s REFUSED: %d host row(s) still present — delete the hosts first", customerID, inv.HostCount)
http.Error(w, "Reset refused: this customer still has host(s). Delete every host first — reset never deletes hosts.", http.StatusConflict)
return
}
// Typed-confirmation gate: the operator must type the exact customer-id.
if r.FormValue("confirm_id") != customerID {
http.Error(w, "Reset refused: the typed customer-id does not match.", http.StatusBadRequest)
return
}
// Ruling 1: destroying retained escrow custody (M>0) needs its OWN separate acknowledgment.
escrowAck := r.FormValue("escrow_ack") == "1"
if inv.SupersededBlobs > 0 && !escrowAck {
http.Error(w, "Reset refused: destroying the retained recovery-key custody requires the separate acknowledgment.", http.StatusBadRequest)
return
}
// From here the reset is committed. Detached ctx (spec: once teardown starts it must run to a clean
// journal state regardless of the operator's browser). External legs FIRST.
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Minute)
defer cancel()
resetID, err := s.store.StartCustomerReset(customerID, escrowAck)
if err != nil {
s.logger.Printf("[ERROR] reset %s: open journal: %v", customerID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
s.logger.Printf("[INFO] customer RESET started for %s (journal #%d, escrow_ack=%t)", customerID, resetID, escrowAck)
// Leg: Hetzner offsite (repo DATA destroyed). Only when the customer chose an offsite tier.
offsiteEnabled, offsiteType := offsiteChoice(cfg.ConfigJSON)
if offsiteEnabled && s.offsite != nil {
if derr := s.offsite.Deprovision(ctx, customerID, offsiteType); derr != nil {
_ = s.store.UpdateResetLeg(resetID, "hetzner", "failed")
s.logger.Printf("[ERROR] reset %s: hetzner deprovision FAILED (journal #%d retained; re-run to resume): %v", customerID, resetID, derr)
http.Error(w, "Reset incomplete: the offsite (Hetzner) teardown failed — nothing was purged; re-run to resume. ("+derr.Error()+")", http.StatusBadGateway)
return
}
_ = s.store.UpdateResetLeg(resetID, "hetzner", "ok")
s.logger.Printf("[INFO] reset %s: offsite deprovisioned (repo data destroyed)", customerID)
} else {
_ = s.store.UpdateResetLeg(resetID, "hetzner", "skipped")
}
// Leg: PBS DR tenancy (namespace + backups + token destroyed). The namespace is customer-id-keyed
// and survives host deletion, so it is torn down here by id; idempotent when absent.
if s.tenantsync != nil {
if _, derr := s.tenantsync.Deprovision(ctx, customerID); derr != nil {
_ = s.store.UpdateResetLeg(resetID, "pbs", "failed")
s.logger.Printf("[ERROR] reset %s: PBS deprovision FAILED (journal #%d retained; re-run to resume): %v", customerID, resetID, derr)
http.Error(w, "Reset incomplete: the PBS namespace teardown failed — nothing was purged; re-run to resume. ("+derr.Error()+")", http.StatusBadGateway)
return
}
_ = s.store.UpdateResetLeg(resetID, "pbs", "ok")
s.logger.Printf("[INFO] reset %s: PBS tenancy deprovisioned", customerID)
} else {
_ = s.store.UpdateResetLeg(resetID, "pbs", "skipped")
}
// All external legs are ok — now the DB side (publish-last, one leg at a time so the journal
// records where a mid-purge crash stopped). Claim → unclaimed (fresh code next onboarding).
if s.claimEngine != nil {
if cerr := s.claimEngine.ResetToUnclaimed(cfg); cerr != nil {
_ = s.store.UpdateResetLeg(resetID, "claim", "failed")
s.logger.Printf("[ERROR] reset %s: claim reset failed: %v", customerID, cerr)
http.Error(w, "Reset incomplete: the claim reset failed — re-run to resume. ("+cerr.Error()+")", http.StatusInternalServerError)
return
}
} else if derr := s.store.DeleteClaim(customerID); derr != nil { // no engine wired: use the store primitive directly
_ = s.store.UpdateResetLeg(resetID, "claim", "failed")
s.logger.Printf("[ERROR] reset %s: claim delete failed: %v", customerID, derr)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
_ = s.store.UpdateResetLeg(resetID, "claim", "ok")
// Clear the provisioned offsite descriptor (keep the tier CHOICE, drop provisioned host/user/repo/
// fingerprint) and re-save → ConfigVersion bump. Identity + basic config survive intact.
newConfigJSON, cerr := offsite.ClearProvisionedDescriptor(cfg.ConfigJSON)
if cerr != nil {
_ = s.store.UpdateResetLeg(resetID, "descriptor", "failed")
s.logger.Printf("[ERROR] reset %s: clear offsite descriptor: %v", customerID, cerr)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
cfg.ConfigJSON = newConfigJSON
if serr := s.store.SaveCustomerConfig(cfg); serr != nil {
_ = s.store.UpdateResetLeg(resetID, "descriptor", "failed")
s.logger.Printf("[ERROR] reset %s: save cleared config: %v", customerID, serr)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
_ = s.store.UpdateResetLeg(resetID, "descriptor", "ok")
// DB purge LAST: retained escrow (ack-gated), one-time secret, DR recipe, log bundles.
if perr := s.store.PurgeCustomerResetDBState(customerID, escrowAck); perr != nil {
_ = s.store.UpdateResetLeg(resetID, "db_purge", "failed")
s.logger.Printf("[ERROR] reset %s: DB purge failed: %v", customerID, perr)
http.Error(w, "Reset incomplete: the DB purge failed — re-run to resume. ("+perr.Error()+")", http.StatusInternalServerError)
return
}
_ = s.store.UpdateResetLeg(resetID, "db_purge", "ok")
if ferr := s.store.FinishCustomerReset(resetID); ferr != nil {
s.logger.Printf("[WARN] reset %s: journal finish stamp failed (state is complete): %v", customerID, ferr)
}
// Audit event (SURVIVES — the reset is part of the customer's permanent history).
msg := "Ügyfél-visszaállítás (RESET): minden működési állapot törölve (offsite tároló, PBS névtér, DR-recept, azonosítási állapot). Az azonosság és az alapkonfiguráció megmaradt."
if escrowAck {
msg += " A megőrzött helyreállítási-kulcs letét is megsemmisült (megerősítve)."
}
if _, eerr := s.store.SaveEvent(customerID, "customer_reset", "warning", msg, "", "hub"); eerr != nil {
s.logger.Printf("[WARN] reset %s: save audit event: %v", customerID, eerr)
}
s.logger.Printf("[INFO] customer RESET complete for %s (journal #%d) — identity + basic config retained", customerID, resetID)
s.bumpIntent(customerID) // wake any holding wait so a lingering box sees the cleared state promptly
http.Redirect(w, r, "/customers/"+customerID+"?flash=reset_done", http.StatusSeeOther)
}
@@ -0,0 +1,46 @@
package web
import (
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// The RESET control renders on the customer page as its OWN amber card, visually distinct from the
// red Danger-zone Delete, with the typed-id confirm + the separate escrow-custody ack row (ruling 1).
func TestTemplates_CustomerResetCard(t *testing.T) {
s, st := newTestServer(t)
if err := st.SaveCustomerConfig(&store.CustomerConfig{
CustomerID: "acme", CustomerName: "Acme", Domain: "acme.hu",
RetrievalPassword: "pw", APIKey: "k", Status: "active",
}); err != nil {
t.Fatal(err)
}
html := renderCustomerPage(t, s, "acme")
// The RESET form posts to the reset endpoint, and the preview endpoint is fetched by its JS.
if !strings.Contains(html, `action="/configs/acme/reset"`) {
t.Error("reset form action missing")
}
for _, fn := range []string{"customerResetConfirm", "customerResetSubmit", "/configs/' + encodeURIComponent(cid) + '/reset"} {
if !strings.Contains(html, fn) {
t.Errorf("reset JS missing %q", fn)
}
}
// Distinct visual: the reset card is amber (--warn); the delete form (red --crit) still exists
// separately — the two controls are not merged.
if !strings.Contains(html, "border-color: var(--warn);") {
t.Error("reset card is not amber-toned (must be distinct from the red Delete)")
}
if !strings.Contains(html, `action="/configs/acme/delete"`) {
t.Error("the Danger-zone Delete must remain a separate control")
}
// The separate escrow-custody ack (ruling 1) + typed-id confirm.
if !strings.Contains(html, `id="cust-reset-escrow-acme"`) {
t.Error("escrow-custody ack checkbox missing")
}
if !strings.Contains(html, `name="confirm_id"`) || !strings.Contains(html, `name="escrow_ack"`) {
t.Error("reset confirm inputs (confirm_id / escrow_ack) missing")
}
}
+222
View File
@@ -0,0 +1,222 @@
package web
// Customer RESET (v0.61.0) orchestration red-proofs. The load-bearing contracts:
// - Scenario A: RESET refuses while ANY host row exists — 409, ZERO side effects (no journal row).
// - Ruling 1: destroying retained escrow custody (M>0) requires the SEPARATE ack — missing → 400,
// nothing purged.
// - Typed-id gate: a wrong confirm_id → 400, nothing purged.
// - Happy path: external legs FIRST, DB purge LAST; identity + basic config SURVIVE; provenance +
// events SURVIVE; journal completes.
// - Partial failure (external FIRST): a failing external leg leaves the DB UNPURGED and the journal
// retained (resumable) — a re-run converges.
import (
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// seedResettable seeds a customer with a full operational footprint but NO host (the reset
// precondition). Returns the store. offsiteJSON is the config_json (with an offsite descriptor).
func seedResettable(t *testing.T, st *store.Store, customerID string) {
t.Helper()
cfgJSON := `{"offsite":{"enabled":true,"type":"shared","host":"u1-sub3.your-storagebox.de","user":"u1-sub3","port":23,"repo_path":"/home/felhom","quota_gb":100,"host_fingerprint":"SHA256:abc"}}`
if err := st.SaveCustomerConfig(&store.CustomerConfig{
CustomerID: customerID, CustomerName: "Teszt", Domain: customerID + ".example",
Email: "t@example.com", RetrievalPassword: "pw", APIKey: "capi", ConfigJSON: cfgJSON,
}); err != nil {
t.Fatalf("seed config: %v", err)
}
// A superseded escrow blob retained via F-14 provenance (host deleted, blob kept).
hostID := customerID + "-01"
if err := st.UpsertHost(&store.Host{HostID: hostID, CustomerID: customerID, APIKey: "hapi"}); err != nil {
t.Fatalf("seed host: %v", err)
}
if _, err := st.SaveHostEscrow(hostID, []byte("blobA"), "fpA", "posture", "2026-01-01T00:00:00Z", "shaA"); err != nil {
t.Fatalf("seed escrow A: %v", err)
}
if _, err := st.SaveHostEscrow(hostID, []byte("blobB"), "fpB", "posture", "2026-01-02T00:00:00Z", "shaB"); err != nil {
t.Fatalf("seed escrow B: %v", err)
}
if err := st.DeleteHost(hostID, true); err != nil { // demotes current → retained; records host_deletions
t.Fatalf("delete host (demote): %v", err)
}
if err := st.SaveOneTimeSecret(customerID, "one-time-pw"); err != nil {
t.Fatalf("seed one-time secret: %v", err)
}
if err := st.SaveDRRecipeHostHalf(customerID, hostID, 1, []byte("half")); err != nil {
t.Fatalf("seed dr recipe: %v", err)
}
if _, err := st.RotateClaimCode(customerID, "$2a$10$hashhashhashhashhashha"); err != nil {
t.Fatalf("seed claim: %v", err)
}
}
func postReset(t *testing.T, s *Server, customerID string, form url.Values) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest("POST", "/configs/"+customerID+"/reset", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
s.handleCustomerReset(rr, req, customerID)
return rr
}
func superseded(t *testing.T, st *store.Store, customerID string) int {
t.Helper()
inv, err := st.CustomerResetInventory(customerID)
if err != nil {
t.Fatalf("inventory: %v", err)
}
return inv.SupersededBlobs
}
func TestCustomerReset_RefusesWhileHostsExist(t *testing.T) {
s, st := newTestServer(t)
s.SetTenantSync(&fakeTenancy{})
seedResettable(t, st, "acme")
// Re-add a live host: RESET must refuse (ruling 3).
if err := st.UpsertHost(&store.Host{HostID: "acme-live", CustomerID: "acme", APIKey: "h"}); err != nil {
t.Fatalf("re-add host: %v", err)
}
rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}, "escrow_ack": {"1"}})
if rr.Code != http.StatusConflict {
t.Fatalf("reset-with-host = %d, want 409", rr.Code)
}
// ZERO side effects: no journal row, secret intact, blobs intact, claim intact.
if cr, _ := st.LatestCustomerReset("acme"); cr != nil {
t.Errorf("a journal row was opened despite the refusal: %+v", cr)
}
if inv, _ := st.CustomerResetInventory("acme"); !inv.OneTimeSecretPresent || !inv.ClaimPresent || inv.SupersededBlobs == 0 {
t.Errorf("refused reset still mutated state: %+v", inv)
}
}
// Red-proof (a): the escrow-custody ack gate. M>0 and no ack → 400, nothing purged. Dropping the
// `!escrowAck` guard would let the reset proceed and destroy the retained blobs → this FAILS.
func TestCustomerReset_EscrowAckRequired(t *testing.T) {
s, st := newTestServer(t)
s.SetTenantSync(&fakeTenancy{})
seedResettable(t, st, "acme")
if superseded(t, st, "acme") == 0 {
t.Fatal("precondition: expected retained blobs to gate on")
}
rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}}) // no escrow_ack
if rr.Code != http.StatusBadRequest {
t.Fatalf("reset without escrow ack = %d, want 400", rr.Code)
}
if cr, _ := st.LatestCustomerReset("acme"); cr != nil {
t.Errorf("journal opened despite the ack refusal: %+v", cr)
}
if superseded(t, st, "acme") == 0 {
t.Error("retained blobs were destroyed despite the missing ack")
}
}
func TestCustomerReset_TypedIDMustMatch(t *testing.T) {
s, st := newTestServer(t)
s.SetTenantSync(&fakeTenancy{})
seedResettable(t, st, "acme")
rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acmee"}, "escrow_ack": {"1"}})
if rr.Code != http.StatusBadRequest {
t.Fatalf("reset with wrong confirm_id = %d, want 400", rr.Code)
}
if inv, _ := st.CustomerResetInventory("acme"); !inv.OneTimeSecretPresent {
t.Error("mismatched-id reset still purged state")
}
}
func TestCustomerReset_HappyPath(t *testing.T) {
s, st := newTestServer(t)
fake := &fakeTenancy{deprovisionExisted: true}
s.SetTenantSync(fake)
seedResettable(t, st, "acme")
rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}, "escrow_ack": {"1"}})
if rr.Code != http.StatusSeeOther {
t.Fatalf("happy reset = %d (%s), want 303", rr.Code, rr.Body.String())
}
// External leg ran.
if fake.deprovisionCalls != 1 {
t.Errorf("pbs deprovision calls = %d, want 1", fake.deprovisionCalls)
}
// Operational state DIED.
inv, _ := st.CustomerResetInventory("acme")
if inv.OneTimeSecretPresent || inv.DRRecipePresent || inv.ClaimPresent || inv.SupersededBlobs != 0 {
t.Errorf("operational state survived the reset: %+v", inv)
}
// Identity + basic config SURVIVE; the offsite tier CHOICE is kept, provisioned fields cleared.
cfg, _ := st.GetCustomerConfig("acme")
if cfg == nil {
t.Fatal("customer_config was destroyed — identity must survive a RESET")
}
if cfg.CustomerName != "Teszt" || cfg.Email != "t@example.com" {
t.Errorf("identity mutated: %+v", cfg)
}
if !strings.Contains(cfg.ConfigJSON, `"enabled":true`) || !strings.Contains(cfg.ConfigJSON, `"type":"shared"`) {
t.Errorf("offsite tier choice was lost: %s", cfg.ConfigJSON)
}
if strings.Contains(cfg.ConfigJSON, "your-storagebox.de") || strings.Contains(cfg.ConfigJSON, "u1-sub3") ||
strings.Contains(cfg.ConfigJSON, "repo_path") || strings.Contains(cfg.ConfigJSON, "host_fingerprint") {
t.Errorf("provisioned offsite fields survived the reset: %s", cfg.ConfigJSON)
}
// Journal completed with every leg recorded ok; provenance + audit event SURVIVE.
cr, _ := st.LatestCustomerReset("acme")
if cr == nil || cr.CompletedAt == nil {
t.Fatalf("journal not finished: %+v", cr)
}
for _, leg := range []string{"pbs", "claim", "descriptor", "db_purge"} {
if cr.Legs[leg] != "ok" {
t.Errorf("leg %q = %q, want ok (legs=%v)", leg, cr.Legs[leg], cr.Legs)
}
}
if ev, _ := st.GetLatestEventByType("acme", "customer_reset"); ev == nil {
t.Error("no customer_reset audit event was recorded")
}
}
// Red-proof (b): partial failure. A failing external leg (PBS) must leave the DB UNPURGED and the
// journal retained — the reset is resumable. Purging before the external legs succeed would erase the
// descriptors that tell a re-run what still needs tearing down → this FAILS.
func TestCustomerReset_PartialFailureIsResumable(t *testing.T) {
s, st := newTestServer(t)
fake := &fakeTenancy{err: errors.New("pbs boom")}
s.SetTenantSync(fake)
seedResettable(t, st, "acme")
rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}, "escrow_ack": {"1"}})
if rr.Code != http.StatusBadGateway {
t.Fatalf("partial reset = %d, want 502", rr.Code)
}
// Nothing purged — the external leg failed FIRST, before any DB mutation.
inv, _ := st.CustomerResetInventory("acme")
if !inv.OneTimeSecretPresent || !inv.DRRecipePresent || !inv.ClaimPresent || inv.SupersededBlobs == 0 {
t.Errorf("DB was purged despite the external leg failing: %+v", inv)
}
cfg, _ := st.GetCustomerConfig("acme")
if !strings.Contains(cfg.ConfigJSON, "your-storagebox.de") {
t.Errorf("descriptor was cleared despite the failure: %s", cfg.ConfigJSON)
}
cr, _ := st.LatestCustomerReset("acme")
if cr == nil || cr.CompletedAt != nil || cr.Legs["pbs"] != "failed" {
t.Fatalf("journal should be open with pbs=failed: %+v", cr)
}
// Resume: the external leg now succeeds; a re-run converges (idempotent from the top).
fake.err = nil
rr2 := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}, "escrow_ack": {"1"}})
if rr2.Code != http.StatusSeeOther {
t.Fatalf("resumed reset = %d (%s), want 303", rr2.Code, rr2.Body.String())
}
inv2, _ := st.CustomerResetInventory("acme")
if inv2.OneTimeSecretPresent || inv2.DRRecipePresent || inv2.ClaimPresent || inv2.SupersededBlobs != 0 {
t.Errorf("resume did not converge: %+v", inv2)
}
}
+3
View File
@@ -34,6 +34,9 @@ import (
type tenancyProvisioner interface {
Provision(ctx context.Context, customerID string) (*tenantsync.Result, error)
Reissue(ctx context.Context, customerID string) (*tenantsync.Result, error)
// Deprovision DESTROYS the customer's PBS namespace + backups + token (customer-RESET teardown,
// v0.61.0). Idempotent — existed=false when nothing was there. The shared user is never touched.
Deprovision(ctx context.Context, customerID string) (existed bool, err error)
}
// SetTenantSync enables PBS DR tier provisioning (optional). Without it, saving a config with the
+19 -5
View File
@@ -24,11 +24,14 @@ import (
)
type fakeTenancy struct {
provisionCalls int
reissueCalls int
err error // both ops fail with this
provisionErr error // Provision-only failure (the F-14 token_exists shape: reissue still works)
secret string
provisionCalls int
reissueCalls int
deprovisionCalls int
err error // both ops fail with this
provisionErr error // Provision-only failure (the F-14 token_exists shape: reissue still works)
deprovisionErr error // Deprovision-only failure (RESET partial-failure red-proof)
deprovisionExisted bool // what Deprovision reports (namespace existed / was destroyed)
secret string
}
func (f *fakeTenancy) result(customerID string) *tenantsync.Result {
@@ -60,6 +63,17 @@ func (f *fakeTenancy) Reissue(ctx context.Context, customerID string) (*tenantsy
return f.result(customerID), nil
}
func (f *fakeTenancy) Deprovision(ctx context.Context, customerID string) (bool, error) {
f.deprovisionCalls++
if f.deprovisionErr != nil {
return false, f.deprovisionErr
}
if f.err != nil {
return false, f.err
}
return f.deprovisionExisted, nil
}
// newPBSDRServer builds a server + store with the full provisioning preconditions satisfied:
// customer config, enrolled host, WG endpoint record, bound WG peer. The logger is captured so
// tests can grep-assert the secret never reaches it.
+9
View File
@@ -508,6 +508,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/reset"):
// Customer RESET (v0.61.0): GET renders the confirm surface (live inventory), POST executes.
customerID := strings.TrimPrefix(path, "/configs/")
customerID = strings.TrimSuffix(customerID, "/reset")
if r.Method == http.MethodPost {
s.handleCustomerReset(w, r, customerID)
} else {
s.handleCustomerResetPreview(w, r, customerID)
}
case strings.HasPrefix(path, "/configs/"):
// Redirect old config detail URL to unified customer page
customerID := strings.TrimPrefix(path, "/configs/")
@@ -55,6 +55,7 @@
{{else if eq .Flash "log_tail_requested"}}Log tail requested — the controller delivers it on its next report cycle (a few minutes). A customer-visible event line was recorded.
{{else if eq .Flash "claim-resent"}}Code re-sent to the registered address. A kód a doboz következő jelentésekor (~15 percen belül) aktiválódik.
{{else if eq .Flash "claim-resend-failed"}}Claim code resend FAILED — check the hub log (email delivery / send error).
{{else if eq .Flash "reset_done"}}Customer RESET complete — every operational trace was destroyed (offsite repo, PBS namespace, DR recipe, claim state, retained escrow custody). Identity and basic config survive; the audit event stream records it.
{{end}}
</div>
{{end}}
@@ -702,6 +703,84 @@
{{end}}
{{if .HasConfig}}
<!-- Reset customer (v0.61.0): the MIDDLE lifecycle tier — host delete < RESET < customer Delete.
One action returns the customer to pre-first-install: every OPERATIONAL trace dies (offsite
repo, PBS namespace, DR recipe, one-time secret, claim state, retained escrow custody), while
IDENTITY and the basic config SURVIVE. Amber (--warn), deliberately distinct from the red
Danger-zone Delete below it. Refuses while any host row exists (delete hosts first). -->
<section class="card" style="border-color: var(--warn);">
<h2>Ügyfél-visszaállítás <span class="text-muted" style="font-size: 0.8em; font-weight: normal;">(RESET — pre-első-telepítés)</span></h2>
<p class="text-muted">Egyetlen művelettel visszaállítja az ügyfelet az első telepítés előtti állapotba: <strong>minden működési állapot törlődik</strong> (offsite tároló, PBS névtér, DR-recept, egyszeri jelszó, azonosítási állapot). Az <strong>azonosság és az alapkonfiguráció megmarad</strong> (ügyfélrekord, előzmények, események). Ez NEM törli a hostokat — ha még van host, előbb azt kell törölni. Kevesebb, mint a Danger zone Delete: az ügyfél megmarad, csak a működési nyomok tűnnek el.</p>
<button type="button" class="btn btn-sm" style="border-color: var(--warn); color: var(--warn);" onclick="customerResetConfirm('{{.CustomerID}}')">Ügyfél visszaállítása&hellip;</button>
<div id="cust-reset-confirm-{{.CustomerID}}" style="display: none; margin-top: 0.75rem; padding: 0.75rem; border: 1px solid var(--warn); background: var(--warn-dim); border-radius: var(--radius); max-width: 46em;">
<p id="cust-reset-inv-{{.CustomerID}}" style="margin: 0 0 0.5rem; font-size: 0.9em;">&hellip;</p>
<label id="cust-reset-escrow-row-{{.CustomerID}}" style="display: none; margin: 0 0 0.6rem; font-size: 0.85em; color: var(--crit);">
<input type="checkbox" id="cust-reset-escrow-{{.CustomerID}}">
<strong>Megőrzött helyreállítási-kulcs letét megsemmisítése</strong> — külön megerősítés (ez visszafordíthatatlanul törli a megőrzött escrow blobokat).
</label>
<p style="margin: 0 0 0.4rem; font-size: 0.85em; color: var(--text-2);">Írd be az ügyfél azonosítóját a megerősítéshez:</p>
<form method="POST" action="/configs/{{.CustomerID}}/reset" id="cust-reset-form-{{.CustomerID}}" style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
{{.CSRFField}}
<input type="hidden" name="confirm_id" id="cust-reset-confirm-hidden-{{.CustomerID}}" value="">
<input type="hidden" name="escrow_ack" id="cust-reset-escrow-hidden-{{.CustomerID}}" value="">
<input type="text" id="cust-reset-input-{{.CustomerID}}" placeholder="ügyfél-azonosító&hellip;" style="padding: 0.3em 0.5em; width: 16em;">
<button type="button" class="btn btn-sm" id="cust-reset-go-{{.CustomerID}}" style="border-color: var(--warn); color: var(--warn);" onclick="customerResetSubmit('{{.CustomerID}}')">Megerősítés &amp; visszaállítás</button>
<button type="button" class="btn btn-sm btn-outline" onclick="document.getElementById('cust-reset-confirm-{{.CustomerID}}').style.display='none';">Mégse</button>
</form>
<p id="cust-reset-err-{{.CustomerID}}" style="margin: 0.4em 0 0; font-size: 0.8em; color: var(--crit);"></p>
</div>
</section>
<script>
function customerResetConfirm(cid) {
var box = document.getElementById('cust-reset-confirm-' + cid);
var inv = document.getElementById('cust-reset-inv-' + cid);
var go = document.getElementById('cust-reset-go-' + cid);
document.getElementById('cust-reset-input-' + cid).value = '';
document.getElementById('cust-reset-err-' + cid).textContent = '';
box.style.display = 'block';
inv.textContent = 'Leltár lekérése…';
go.disabled = false;
fetch('/configs/' + encodeURIComponent(cid) + '/reset')
.then(function(r){ return r.json(); })
.then(function(d){
if (d.refused) {
inv.innerHTML = '<strong style="color: var(--crit)">Elutasítva:</strong> ehhez az ügyfélhez még ' + d.host_count +
' host tartozik. A RESET soha nem töröl hostot — előbb töröld a host(oka)t.';
go.disabled = true;
document.getElementById('cust-reset-escrow-row-' + cid).style.display = 'none';
return;
}
var dies = [];
if (d.offsite_enabled) dies.push('offsite tároló' + (d.offsite_identifier ? ' (' + d.offsite_identifier + ')' : ''));
if (d.pbs_tenancy_configured) dies.push('PBS névtér + mentések');
if (d.dr_recipe_present) dies.push('DR-recept');
if (d.one_time_secret) dies.push('egyszeri jelszó');
if (d.claim_present) dies.push('azonosítási állapot (friss kód a következő onboardingnál)');
if (d.superseded_blobs > 0) dies.push(d.superseded_blobs + ' megőrzött escrow blob');
inv.innerHTML = '<strong>Törlődik:</strong> ' + (dies.length ? dies.join(', ') : 'nincs működési állapot') +
'. <strong>Megmarad:</strong> ügyfélrekord, alapkonfiguráció, előzmények, események.';
var escrowRow = document.getElementById('cust-reset-escrow-row-' + cid);
escrowRow.style.display = d.escrow_ack_required ? 'block' : 'none';
document.getElementById('cust-reset-escrow-' + cid).checked = false;
})
.catch(function(){ inv.textContent = 'A leltár nem kérhető le — a szerver minden feltételt így is kikényszerít.'; });
}
function customerResetSubmit(cid) {
var typed = document.getElementById('cust-reset-input-' + cid).value.trim();
var err = document.getElementById('cust-reset-err-' + cid);
if (typed !== cid) { err.textContent = 'A beírt azonosító nem egyezik.'; return; }
var escrowRow = document.getElementById('cust-reset-escrow-row-' + cid);
var escrowCb = document.getElementById('cust-reset-escrow-' + cid);
if (escrowRow.style.display !== 'none' && !escrowCb.checked) {
err.textContent = 'A megőrzött kulcs-letét megsemmisítéséhez pipáld be a külön megerősítést.';
return;
}
document.getElementById('cust-reset-confirm-hidden-' + cid).value = typed;
document.getElementById('cust-reset-escrow-hidden-' + cid).value = escrowCb.checked ? '1' : '';
document.getElementById('cust-reset-form-' + cid).submit();
}
</script>
<!-- Danger zone (v0.48.0 edit-a): the Block/Delete forms relocated verbatim from the
Customer Info header — endpoints and confirm() handlers unchanged. -->
<section class="card">