hub (unreleased): the record of an off-site account outlives an untick; RESET and delete take the account down (R-1375, D71); runbook: a household or a tester leaves (D74)
gates / gates (push) Successful in 2m0s

An untick alone takes nothing down (pinned first). Tests run the real save and RESET over the repository's fake
provider. Not deployed.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
admin committed 2026-11-14 17:56:29 +01:00
1 parent 186f3fca58
commit e5c643d73d
11 files changed
+563 -2

No files matched your search

@@ -0,0 +1,51 @@
package offsite
import (
"strings"
"testing"
"time"
)
// D71 (R-1375): the four cases of KeepAccountRecord, as a table. The web tests (TestD71_*) prove the consequence
// through the real save and the real RESET; this pins the rule itself.
func TestKeepAccountRecord_FourCases(t *testing.T) {
now := time.Date(2026, 11, 14, 20, 0, 0, 0, time.UTC)
const (
provisioned = `{"git":{"username":"x"},"offsite":{"enabled":true,"type":"shared","host":"u1-sub3.example","user":"u1-sub3","port":23}}`
choiceOnly = `{"offsite":{"enabled":true,"type":"shared","quota_gb":100}}` // ticked, never provisioned (or after a RESET)
withRecord = `{"offsite_account":{"type":"shared","user":"u1-sub3","host":"u1-sub3.example","unticked_at":"2026-11-01T00:00:00Z"}}`
unticked = `{"git":{"username":"x"}}`
)
for _, c := range []struct {
name, prev, next string
wantUser, wantAt string // "" = no record
keepsOther string
}{
{"ticked and provisioned, then unticked: a record from the old descriptor", provisioned, unticked, "u1-sub3", "2026-11-14T20:00:00Z", `"git"`},
{"a record, still unticked: carried unchanged (the form does not know it)", withRecord, unticked, "u1-sub3", "2026-11-01T00:00:00Z", `"git"`},
{"ticked again: no record", withRecord, provisioned, "", "", `"offsite"`},
{"a config that carries BOTH a ticked tier and a record: the record goes (the descriptor is the record)", withRecord,
`{"offsite":{"enabled":true,"type":"shared","user":"u1-sub3"},"offsite_account":{"type":"shared","user":"u1-sub3"}}`, "", "", `"offsite"`},
{"ticked, never provisioned, then unticked: no account was made, no record", choiceOnly, unticked, "", "", `"git"`},
{"never ticked: nothing", `{}`, unticked, "", "", `"git"`},
{"an empty previous config", ``, `{}`, "", "", ``},
} {
out, err := KeepAccountRecord(c.prev, c.next, now)
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
rec := ReadAccountRecord(out)
switch {
case c.wantUser == "" && rec != nil:
t.Errorf("%s: a record %+v, want none (%s)", c.name, rec, out)
case c.wantUser != "" && (rec == nil || rec.User != c.wantUser || rec.UntickedAt != c.wantAt || rec.Type != "shared"):
t.Errorf("%s: record %+v, want user %s unticked_at %s (%s)", c.name, rec, c.wantUser, c.wantAt, out)
}
if c.keepsOther != "" && !strings.Contains(out, c.keepsOther) {
t.Errorf("%s: the other keys were lost: %s", c.name, out)
}
}
if _, err := KeepAccountRecord(provisioned, `{not json`, now); err == nil {
t.Error("a config that cannot be read must be an error (the save is then refused), not a silent loss of the record")
}
}
+93
View File
@@ -514,6 +514,8 @@ func ClearProvisionedDescriptor(configJSON string) (string, error) {
if err != nil {
return "", err
}
// D71: the record of an unticked tier's account dies with the account too (RESET took it down before this leg).
configJSON = dropAccountRecord(configJSON)
if cur == nil {
return configJSON, nil // no offsite block — nothing to clear
}
@@ -521,6 +523,97 @@ func ClearProvisionedDescriptor(configJSON string) (string, error) {
return MergeDescriptor(configJSON, cleared)
}
func dropAccountRecord(configJSON string) string {
obj := map[string]json.RawMessage{}
if json.Unmarshal([]byte(configJSON), &obj) != nil {
return configJSON
}
if _, ok := obj[AccountRecordKey]; !ok {
return configJSON
}
delete(obj, AccountRecordKey)
out, err := json.Marshal(obj)
if err != nil {
return configJSON
}
return string(out)
}
// AccountRecordKey is the ConfigJSON key that holds the record of an off-site account whose tier was UNTICKED
// (D71, `09` §3 decision 291, R-1375; `06-offsite-connectivity.md`). The box does not read it.
const AccountRecordKey = "offsite_account"
// AccountRecord says: an off-site account for this household still exists at the provider although the tier is
// switched off. Before it, unticking the tier dropped the whole `offsite` block (the form rebuilds ConfigJSON), so
// the hub forgot the account: a later RESET or delete skipped it and the account stayed, paid for, with the
// household's copies in it and no record anywhere (endings EH06-4, EH01-4). Non-secret.
type AccountRecord struct {
Type string `json:"type,omitempty"` // shared | dedicated — what Deprovision needs
User string `json:"user,omitempty"`
Host string `json:"host,omitempty"`
UntickedAt string `json:"unticked_at,omitempty"` // RFC3339 UTC
}
// ReadAccountRecord returns the record, or nil when there is none (or it cannot be read).
func ReadAccountRecord(configJSON string) *AccountRecord {
obj := map[string]json.RawMessage{}
if json.Unmarshal([]byte(configJSON), &obj) != nil {
return nil
}
raw, ok := obj[AccountRecordKey]
if !ok {
return nil
}
var r AccountRecord
if json.Unmarshal(raw, &r) != nil {
return nil
}
return &r
}
// KeepAccountRecord is called on every save of a household's config, with the config as it WAS and as the form
// built it. It returns the new config with the account record carried:
// - the tier is ticked in the new config: no record (the descriptor itself is the record);
// - the tier was ticked AND PROVISIONED before and is unticked now: a record is written from the old descriptor;
// - a record was there before and the tier is still unticked: the record is carried (the form does not know it);
// - else: nothing — a tier that was ticked and never provisioned made no account.
//
// It calls no provider and removes nothing: AN UNTICK ALONE NEVER TAKES AN ACCOUNT OR ITS DATA DOWN. Only RESET and
// delete do (web.commitCustomerReset), and they read this record. Pinned by TestKeepAccountRecord_* and
// web TestD71_*.
func KeepAccountRecord(prevJSON, newJSON string, now time.Time) (string, error) {
obj := map[string]json.RawMessage{}
if strings.TrimSpace(newJSON) != "" {
if err := json.Unmarshal([]byte(newJSON), &obj); err != nil {
return "", fmt.Errorf("offsite: parse config_json: %w", err)
}
}
newD, err := ReadDescriptor(newJSON)
if err != nil {
return "", err
}
if newD != nil && newD.Enabled {
delete(obj, AccountRecordKey)
} else {
var rec *AccountRecord
if prevD, _ := ReadDescriptor(prevJSON); prevD != nil && prevD.Enabled && (prevD.User != "" || prevD.Host != "") {
rec = &AccountRecord{Type: prevD.Type, User: prevD.User, Host: prevD.Host, UntickedAt: now.UTC().Format(time.RFC3339)}
} else if prevRec := ReadAccountRecord(prevJSON); prevRec != nil {
rec = prevRec
}
if rec == nil {
return newJSON, nil
}
rb, _ := json.Marshal(rec)
obj[AccountRecordKey] = rb
}
out, err := json.Marshal(obj)
if err != nil {
return "", err
}
return string(out), nil
}
// ReadDescriptor extracts the non-secret offsite Descriptor from a customer's ConfigJSON, or (nil, nil)
// when there is no offsite block (never provisioned). This is the AUTHORITATIVE tier/quota source — the
// pool-box Σ(quota) aggregate (v0.64.0, R-5) and the RESET clear both read through it, NEVER the report
+13
View File
@@ -916,6 +916,7 @@ func (s *Server) handleConfigUpdate(w http.ResponseWriter, r *http.Request, cust
}
}
prevConfigJSON := cfg.ConfigJSON // D71: the form rebuilds ConfigJSON; the account's record must outlive an untick
cfg.ConfigJSON = buildConfigJSON(r)
if err := s.applyOffsite(r.Context(), r, cfg); errors.Is(err, offsite.ErrProvisionInProgress) {
@@ -928,6 +929,18 @@ func (s *Server) handleConfigUpdate(w http.ResponseWriter, r *http.Request, cust
http.Error(w, "Offsite provisioning failed: "+err.Error(), http.StatusBadGateway)
return
}
// D71 (R-1375): unticking the off-site tier takes NOTHING down — and the hub now keeps the record of the account,
// so a later RESET or delete finds it. Fail-closed: a config we cannot carry the record into is not saved.
if kept, kerr := offsite.KeepAccountRecord(prevConfigJSON, cfg.ConfigJSON, time.Now()); kerr != nil {
s.logger.Printf("[ERROR] offsite account record for %s: %v", customerID, kerr)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
} else {
if rec := offsite.ReadAccountRecord(kept); rec != nil && offsite.ReadAccountRecord(prevConfigJSON) == nil {
s.logger.Printf("[WARN] offsite tier UNTICKED for %s: nothing was removed at the provider; the account (%s, %s) stays and its record is kept — RESET or delete takes it down", customerID, rec.Type, rec.User)
}
cfg.ConfigJSON = kept
}
// PBS DR tier (fail-closed; idempotent on an already-provisioned descriptor — no re-key,
// no second secret, no spurious generation bump).
+10
View File
@@ -23,6 +23,9 @@ import (
// 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.
// offsiteChoice answers „is there an off-site account of this household to take down, and of which type?” — the tier
// is ticked, OR it was unticked and the account's record was kept (offsite.KeepAccountRecord). Read by the RESET
// commit and by both previews. Pinned by TestD71_*.
func offsiteChoice(configJSON string) (enabled bool, typ string) {
var o struct {
Offsite struct {
@@ -31,6 +34,13 @@ func offsiteChoice(configJSON string) (enabled bool, typ string) {
} `json:"offsite"`
}
_ = json.Unmarshal([]byte(configJSON), &o)
if !o.Offsite.Enabled {
// D71 (`09` §3 decision 291, R-1375): the tier is unticked, but the hub kept the record of the account it
// made — RESET and delete take that account down too, and their previews name it. An untick alone never does.
if rec := offsite.ReadAccountRecord(configJSON); rec != nil {
return true, rec.Type
}
}
return o.Offsite.Enabled, o.Offsite.Type
}
@@ -0,0 +1,174 @@
package web
import (
"context"
"encoding/json"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-hub/internal/hetznerapi"
"gitea.dooplex.hu/admin/felhom-hub/internal/offsite"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// d71Server: the hub's web server over the repo's FAKE provider (hetznerapi.Fake — no provider is called). purges
// counts the calls to the shared folder's purge, the step that destroys a household's off-site copies.
func d71Server(t *testing.T) (*Server, *store.Store, *hetznerapi.Fake, *int) {
t.Helper()
s, st := newTestServer(t)
api := hetznerapi.NewFake()
purges := 0
s.SetOffsiteProvisioner(&offsite.Provisioner{
API: api, Store: st, Scanner: webTestScanner{}, PoolBoxID: 611714, Location: "fsn1",
Logger: log.New(io.Discard, "", 0),
PurgeShared: func(context.Context, string) error { purges++; return nil },
})
s.SetTenantSync(&fakeTenancy{})
if err := st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "acme", CustomerName: "Acme", Domain: "acme.hu",
Email: "a@example.com", RetrievalPassword: "pw", APIKey: "k", ConfigJSON: "{}"}); err != nil {
t.Fatal(err)
}
return s, st, api, &purges
}
func d71Save(t *testing.T, s *Server, form string) {
t.Helper()
w := httptest.NewRecorder()
s.handleConfigUpdate(w, postForm("/configs/acme/edit", "customer_name=Acme&domain=acme.hu&dr_tier=on"+form), "acme")
if w.Code != http.StatusSeeOther {
t.Fatalf("save (%s): %d %s", form, w.Code, w.Body.String())
}
}
func d71Accounts(t *testing.T, api *hetznerapi.Fake) int {
t.Helper()
subs, err := api.ListSubaccounts(context.Background(), 611714, "")
if err != nil {
t.Fatal(err)
}
return len(subs)
}
const d71Tick = "&offsite_enabled=on&offsite_type=shared&offsite_quota_gb=50"
// D71 (`09` §3 decision 291, R-1375). THE WRONG CASE, pinned first: an untick alone must NEVER take an account or
// its data down. Then the fix: the hub keeps the account's record through the untick (and through later saves — the
// form rebuilds the whole config), so a later RESET finds the account and takes it down; before, RESET skipped it and
// the account stayed at the provider, paid for, with no record in the hub.
// COMPANION RED-PROOFS (observed, audits/night-build-2026-11-14/B/redproof-hub-offsite-record.txt).
func TestD71_UntickKeepsTheAccountAndItsRecord_ResetTakesItDown(t *testing.T) {
s, st, api, purges := d71Server(t)
d71Save(t, s, d71Tick)
if n := d71Accounts(t, api); n != 1 {
t.Fatalf("setup: %d account(s) at the fake provider after the tick, want 1", n)
}
cfg, _ := st.GetCustomerConfig("acme")
d, _ := offsite.ReadDescriptor(cfg.ConfigJSON)
if d == nil || d.User == "" {
t.Fatalf("setup: no provisioned descriptor: %s", cfg.ConfigJSON)
}
// UNTICK — and two more saves after it
d71Save(t, s, "")
d71Save(t, s, "")
d71Save(t, s, "&debug_mode=on")
if n := d71Accounts(t, api); n != 1 || *purges != 0 {
t.Fatalf("AN UNTICK TOOK SOMETHING DOWN: %d account(s) left (want 1), %d purge call(s) (want 0)", n, *purges)
}
cfg, _ = st.GetCustomerConfig("acme")
if nd, _ := offsite.ReadDescriptor(cfg.ConfigJSON); nd != nil && nd.Enabled {
t.Fatalf("the tier is still enabled after the untick: %s", cfg.ConfigJSON)
}
rec := offsite.ReadAccountRecord(cfg.ConfigJSON)
if rec == nil || rec.User != d.User || rec.Type != "shared" || rec.UntickedAt == "" {
t.Fatalf("the account's record did not survive the untick and two saves: %+v in %s", rec, cfg.ConfigJSON)
}
// the box is handed the tier as OFF: the record is not an `offsite` block
var box map[string]json.RawMessage
_ = json.Unmarshal([]byte(cfg.ConfigJSON), &box)
if _, has := box["offsite"]; has {
t.Errorf("an unticked tier still carries an `offsite` block the box would read: %s", cfg.ConfigJSON)
}
// both previews name the account
for _, path := range []string{"reset", "delete"} {
rr := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/configs/acme/"+path, nil)
if path == "reset" {
s.handleCustomerResetPreview(rr, req, "acme")
} else {
s.handleCustomerDeletePreview(rr, req, "acme")
}
if !strings.Contains(rr.Body.String(), `"offsite_enabled":true`) || !strings.Contains(rr.Body.String(), d.User) {
t.Errorf("the %s preview does not name the kept account %s: %s", path, d.User, rr.Body.String())
}
}
// the form says it
page := httptest.NewRecorder()
s.renderConfigForm(page, httptest.NewRequest("GET", "/configs/acme/edit", nil), false, cfg, nil, "")
if !strings.Contains(page.Body.String(), "data-offsite-account-kept") || !strings.Contains(page.Body.String(), d.User) {
t.Errorf("the config form does not say that the account still exists")
}
// RESET: the account goes, its folder is purged first, and the record goes with it
rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}})
if rr.Code != http.StatusSeeOther {
t.Fatalf("reset: %d %s", rr.Code, rr.Body.String())
}
if n := d71Accounts(t, api); n != 0 || *purges != 1 {
t.Fatalf("after the RESET: %d account(s) left (want 0), %d purge(s) (want 1) — the unticked account was skipped", n, *purges)
}
cr, _ := st.LatestCustomerReset("acme")
if cr == nil || cr.Legs["hetzner"] != "ok" {
t.Fatalf("journal: %+v, want the hetzner leg ok (not skipped)", cr)
}
cfg, _ = st.GetCustomerConfig("acme")
if offsite.ReadAccountRecord(cfg.ConfigJSON) != nil {
t.Errorf("the record outlived the account: %s", cfg.ConfigJSON)
}
}
// Ticking again takes the same account back into use (the provider is asked by the household's label, so no second
// account is made) and the record is gone: the descriptor is the record again.
func TestD71_TickAgainUsesTheSameAccount(t *testing.T) {
s, st, api, purges := d71Server(t)
d71Save(t, s, d71Tick)
cfg, _ := st.GetCustomerConfig("acme")
first, _ := offsite.ReadDescriptor(cfg.ConfigJSON)
d71Save(t, s, "")
d71Save(t, s, d71Tick)
cfg, _ = st.GetCustomerConfig("acme")
again, _ := offsite.ReadDescriptor(cfg.ConfigJSON)
if again == nil || !again.Enabled || again.User != first.User {
t.Fatalf("after ticking again: %+v, want the first account %s", again, first.User)
}
if offsite.ReadAccountRecord(cfg.ConfigJSON) != nil {
t.Errorf("a ticked tier still carries the untick record: %s", cfg.ConfigJSON)
}
if n := d71Accounts(t, api); n != 1 || *purges != 0 {
t.Fatalf("accounts=%d purges=%d, want 1 and 0", n, *purges)
}
}
// A household that never had the tier gets no record, and a RESET then calls no provider (as before).
func TestD71_NeverTickedMakesNoRecord(t *testing.T) {
s, st, api, purges := d71Server(t)
d71Save(t, s, "")
d71Save(t, s, "")
cfg, _ := st.GetCustomerConfig("acme")
if offsite.ReadAccountRecord(cfg.ConfigJSON) != nil {
t.Fatalf("a record for an account that never existed: %s", cfg.ConfigJSON)
}
if rr := postReset(t, s, "acme", url.Values{"confirm_id": {"acme"}}); rr.Code != http.StatusSeeOther {
t.Fatalf("reset: %d", rr.Code)
}
cr, _ := st.LatestCustomerReset("acme")
if cr == nil || cr.Legs["hetzner"] != "skipped" || d71Accounts(t, api) != 0 || *purges != 0 {
t.Fatalf("journal %+v, purges %d — want the hetzner leg skipped and nothing called", cr, *purges)
}
_ = http.StatusOK
}
@@ -97,13 +97,14 @@
</div>
</details>
<details class="card" {{if index .Overrides "offsite"}}open{{end}}>
<details class="card" {{if or (index .Overrides "offsite") (index .Overrides "offsite_account")}}open{{end}}>
<summary><h2 style="display:inline">Offsite backup</h2></summary>
<div class="form-grid" style="margin-top: 1rem;">
<div class="form-group">
<label><input type="checkbox" name="offsite_enabled"
{{with .Overrides}}{{with index . "offsite"}}{{if index . "enabled"}}checked{{end}}{{end}}{{end}}>
Enable offsite (provisions a Hetzner Storage Box on save)</label>
{{with index .Overrides "offsite_account"}}<p class="form-hint" data-offsite-account-kept>The off-site tier is OFF, and this household's account still exists at the provider: <strong>{{index . "user"}}</strong> ({{index . "type"}}), unticked {{index . "unticked_at"}}. Unticking removed nothing. A RESET or „Delete customer…” takes the account and its copies down. Tick again to use it.</p>{{end}}
</div>
<div class="form-group">
<label for="offsite_type">Type</label>