From b02bf254bc56e48ffa03fe0983e17c09a11c3468 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:55:28 +0100 Subject: [PATCH 1/3] feat(erpsetup): registry user may read dunning, read only The late-payment ladder (#134) reads Dunnings, which ERPNext lets only the Accounts roles read. The registry's API user holds Sales User only. erpsetup now adds a level-0 read rule for Sales User on Dunning through Frappe's permission manager (which first copies the standard rules, as the Role Permissions Manager UI does) and cuts a broader rule back to read only. The spec.go comment no longer claims Accounts User. Live ERP: the same rule was added by hand on 17.11.; the next run reports it as existing. Co-Authored-By: Claude Opus 5.5 --- internal/erpsetup/erpsetup.go | 6 +++ internal/erpsetup/erpsetup_test.go | 67 +++++++++++++++++++++++++ internal/erpsetup/permissions.go | 79 ++++++++++++++++++++++++++++++ internal/erpsetup/spec.go | 5 +- 4 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 internal/erpsetup/permissions.go diff --git a/internal/erpsetup/erpsetup.go b/internal/erpsetup/erpsetup.go index a46f12a..796a398 100644 --- a/internal/erpsetup/erpsetup.go +++ b/internal/erpsetup/erpsetup.go @@ -205,6 +205,12 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) { if err := r.reisekosten(ctx); err != nil { return r.steps, err } + // What the registry's API user must read beyond its role (permissions.go). + for _, dt := range registryReads() { + if err := r.ensureReadPerm(ctx, dt, registryRole); err != nil { + return r.steps, err + } + } for _, w := range webhooks(cfg.WebhookURL, cfg.WebhookSecret) { if err := r.ensureWebhook(ctx, w); err != nil { return r.steps, err diff --git a/internal/erpsetup/erpsetup_test.go b/internal/erpsetup/erpsetup_test.go index ab49204..23f9365 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -67,6 +67,20 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) return } + if r.URL.Path == "/api/method/frappe.core.page.permission_manager.permission_manager.add" && r.Method == http.MethodPost { + // Frappe copies the standard rules first, then adds the role with read only. + var in map[string]any + _ = json.NewDecoder(r.Body).Decode(&in) + if f.docs["Custom DocPerm"] == nil { + f.docs["Custom DocPerm"] = map[string]map[string]any{} + } + name := fmt.Sprintf("perm-%d", len(f.docs["Custom DocPerm"])+1) + f.docs["Custom DocPerm"][name] = map[string]any{"name": name, "parent": in["parent"], "role": in["role"], "permlevel": in["permlevel"], + "read": 1, "write": 0, "create": 0, "submit": 0, "cancel": 0, "delete": 0, "amend": 0} + f.posts++ + _, _ = io.WriteString(w, `{"message":"`+name+`"}`) + return + } rest := strings.TrimPrefix(r.URL.Path, "/api/resource/") parts := strings.SplitN(rest, "/", 2) doctype, _ := url.PathUnescape(parts[0]) @@ -809,3 +823,56 @@ func TestCustomerTextSpellsBreakpilot(t *testing.T) { } } } + +// The registry's API user may read Dunning (Mahnungen) and nothing more: a +// missing rule is created through the permission manager, a broader one is +// cut back to read only, a correct one is left alone. +func TestRegistryReadPermission(t *testing.T) { + f := newFake() + srv := httptest.NewServer(f) + defer srv.Close() + find := func() map[string]any { + for _, d := range f.docs["Custom DocPerm"] { + if d["parent"] == "Dunning" && d["role"] == registryRole { + return d + } + } + return nil + } + result := func(steps []Step) string { + for _, s := range steps { + if strings.HasPrefix(s.What, "permission Dunning") { + return s.Result + } + } + return "(no step)" + } + + dry := cfg(srv.URL) + dry.DryRun = true + steps, err := Run(t.Context(), dry) + if err != nil || result(steps) != "would create" || find() != nil { + t.Fatalf("dry run: %v %q", err, result(steps)) + } + steps, err = Run(t.Context(), cfg(srv.URL)) + if err != nil || result(steps) != "created" { + t.Fatalf("first run: %v %q", err, result(steps)) + } + if d := find(); d == nil || fmt.Sprint(d["read"]) != "1" || fmt.Sprint(d["write"]) != "0" { + t.Fatalf("rule: %v", d) + } + steps, _ = Run(t.Context(), cfg(srv.URL)) + if !strings.HasPrefix(result(steps), "exists") { + t.Fatalf("second run: %q", result(steps)) + } + // someone ticked more in the UI: the next run cuts it back to read only + d := find() + d["write"], d["create"] = 1, 1 + steps, _ = Run(t.Context(), cfg(srv.URL)) + if r := result(steps); !strings.HasPrefix(r, "updated") || !strings.Contains(r, "write 1 โ†’ 0") || !strings.Contains(r, "create 1 โ†’ 0") { + t.Fatalf("broader rule: %q", r) + } + if fmt.Sprint(find()["write"]) != "0" || fmt.Sprint(find()["read"]) != "1" { + t.Fatalf("after cut back: %v", find()) + } +} diff --git a/internal/erpsetup/permissions.go b/internal/erpsetup/permissions.go new file mode 100644 index 0000000..bfdc09d --- /dev/null +++ b/internal/erpsetup/permissions.go @@ -0,0 +1,79 @@ +package erpsetup + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" +) + +// registryRole is the role of the registry's API user (platform-registry@): +// it appends usage records and reads invoices. It is not Accounts User, which +// could also create and submit bookings and payments. +const registryRole = "Sales User" + +// registryReads are the doctypes the registry must read beyond what its role +// gets by default. Dunning: the late-payment ladder counts from the Mahnung +// (AGB ยง 10, tenant-registry #134); ERPNext gives read only to the Accounts +// roles. The child table (Overdue Payment) follows its parent. +func registryReads() []string { return []string{"Dunning"} } + +// grantFlags are the rights a read-only rule must not carry. +var grantFlags = []string{"write", "create", "submit", "cancel", "delete", "amend"} + +// ensureReadPerm makes sure `role` may read `doctype` and nothing more, at +// permission level 0. A missing rule is added through Frappe's permission +// manager, which first copies the doctype's standard rules into Custom DocPerm +// (as the Role Permissions Manager UI does), so the other roles keep theirs. +// An existing rule is corrected to read-only. +func (r *runner) ensureReadPerm(ctx context.Context, doctype, role string) error { + what := fmt.Sprintf("permission %s: %s may read (level 0, read only)", doctype, role) + filters, _ := json.Marshal([][]any{{"parent", "=", doctype}, {"role", "=", role}, {"permlevel", "=", 0}}) + fields, _ := json.Marshal(append([]string{"name", "read"}, grantFlags...)) + q := url.Values{"filters": {string(filters)}, "fields": {string(fields)}, "limit_page_length": {"1"}} + status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape("Custom DocPerm")+"?"+q.Encode(), nil) + if err != nil { + return err + } + if status != http.StatusOK { + return fmt.Errorf("erpsetup: list Custom DocPerm: HTTP %d %s", status, truncate(body)) + } + var list struct { + Data []map[string]any `json:"data"` + } + if err := json.Unmarshal(body, &list); err != nil { + return fmt.Errorf("erpsetup: decode Custom DocPerm list: %w", err) + } + if len(list.Data) == 0 { + if r.cfg.DryRun { + r.record(what, "would create") + return nil + } + status, body, err = r.call(ctx, http.MethodPost, "/api/method/frappe.core.page.permission_manager.permission_manager.add", + map[string]any{"parent": doctype, "role": role, "permlevel": 0}) + if err != nil { + return err + } + if status/100 != 2 { + return fmt.Errorf("erpsetup: create %s: HTTP %d %s", what, status, truncate(body)) + } + r.record(what, "created") + return nil + } + row := list.Data[0] + name := fmt.Sprint(row["name"]) + patch := map[string]any{} + var changes []string + if fmt.Sprint(row["read"]) != "1" { + patch["read"] = 1 + changes = append(changes, change("read", row["read"], 1)) + } + for _, f := range grantFlags { + if v := fmt.Sprint(row[f]); v != "0" && v != "" { + patch[f] = 0 + changes = append(changes, change(f, row[f], 0)) + } + } + return r.applyPatch(ctx, "/api/resource/"+url.PathEscape("Custom DocPerm")+"/"+url.PathEscape(name), what, " ("+name+")", patch, changes) +} diff --git a/internal/erpsetup/spec.go b/internal/erpsetup/spec.go index 287c89d..62b06db 100644 --- a/internal/erpsetup/spec.go +++ b/internal/erpsetup/spec.go @@ -60,8 +60,9 @@ func usageRecordDoctype() map[string]any { {"role": "System Manager", "read": 1, "write": 1, "create": 1, "delete": 1, "report": 1, "export": 1}, {"role": "Accounts Manager", "read": 1, "report": 1, "export": 1}, {"role": "Sales Manager", "read": 1, "report": 1, "export": 1}, - // The registry's API user (platform-registry) holds Sales User and - // Accounts User, not System Manager: it only appends usage. + // The registry's API user (platform-registry) holds Sales User + // only, not System Manager: it appends usage. Its extra reads are + // in permissions.go. {"role": "Sales User", "read": 1, "create": 1}, }, } -- 2.54.1 From 524f5009d3fc5b2407479a40df4484c0fbec52a1 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:55:28 +0100 Subject: [PATCH 2/3] test(migrations): intake reports keep their workspace (0030) TestSeed_canInsertAndQuery deleted a tenant that had intake reports, which 0030 forbids on purpose (reports outlive their workspace). The intake rows now sit on a workspace of their own; the test checks that its delete is refused and the rows stay, and the cascade check keeps the other tenant. Co-Authored-By: Claude Opus 5.5 --- migrations/migrations_test.go | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index fc71a7d..3f4a956 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -340,17 +340,22 @@ func TestSeed_canInsertAndQuery(t *testing.T) { } // 0028: the R1 intake, insert-only, one capture per report, one - // settling receipt per entry. + // settling receipt per entry. On a workspace of its own: since 0030 a + // workspace with intake reports cannot be deleted (checked below). + var itid string + if err := db.QueryRowContext(ctx, `INSERT INTO tenants (slug, name, plan, status, kind) VALUES ('intake-co', 'Intake Co', 'professional', 'active', 'customer') RETURNING id`).Scan(&itid); err != nil { + t.Fatalf("insert intake tenant: %v", err) + } if _, err := db.ExecContext(ctx, `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) - VALUES ($1, 'SH-2026-00001', 1, now(), 'portal', 'u-1', 'product', 'no')`, tid); err != nil { + VALUES ($1, 'SH-2026-00001', 1, now(), 'portal', 'u-1', 'product', 'no')`, itid); err != nil { t.Fatalf("insert intake report: %v", err) } insEntry := `INSERT INTO intake_entries (tenant_id, reference, kind, content, by_sub, at) VALUES ($1, 'SH-2026-00001', $2, '{"what":"x"}', 'u-1', now()) RETURNING id` var entryID int64 - if err := db.QueryRowContext(ctx, insEntry, tid, "capture").Scan(&entryID); err != nil { + if err := db.QueryRowContext(ctx, insEntry, itid, "capture").Scan(&entryID); err != nil { t.Fatalf("insert intake capture: %v", err) } - if _, err := db.ExecContext(ctx, insEntry, tid, "capture"); err == nil { + if _, err := db.ExecContext(ctx, insEntry, itid, "capture"); err == nil { t.Error("a second capture of the same report was stored") } insReceipt := `INSERT INTO intake_receipts (entry_id, status, by_client, at) VALUES ($1, $2, 'werkmeister-svc', now())` @@ -359,7 +364,7 @@ func TestSeed_canInsertAndQuery(t *testing.T) { } for name, stmt := range map[string]string{ "second settling receipt": `INSERT INTO intake_receipts (entry_id, status, by_client, at) VALUES (` + strconv.FormatInt(entryID, 10) + `, 'refused', 'w', now())`, - "bad reference": `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) VALUES ('` + tid + `', 'X-1', 2, now(), 'portal', 'u', 'product', 'no')`, + "bad reference": `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) VALUES ('` + itid + `', 'X-1', 2, now(), 'portal', 'u', 'product', 'no')`, "changed report": `UPDATE intake_reports SET danger = 'yes'`, "changed entry": `UPDATE intake_entries SET content = '{}'`, "changed receipt": `UPDATE intake_receipts SET status = 'refused'`, @@ -369,15 +374,23 @@ func TestSeed_canInsertAndQuery(t *testing.T) { } } + // 0030: security reports outlive their workspace, so the database + // refuses to delete a workspace that has intake reports. + if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, itid); err == nil { + t.Error("a workspace with intake reports was deleted") + } + var nReports, nEntries int + _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_reports WHERE tenant_id = $1`, itid).Scan(&nReports) + _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_entries WHERE tenant_id = $1`, itid).Scan(&nEntries) + if nReports != 1 || nEntries != 1 { + t.Errorf("intake after a refused delete: reports=%d entries=%d, want 1/1", nReports, nEntries) + } + // FK cascade โ€” delete tenant, projects/products/keys/audit_log handling. if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil { t.Fatalf("delete tenant: %v", err) } - var nServices, nSettings, nContractDocs, nIntake int - _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_entries WHERE tenant_id = $1`, tid).Scan(&nIntake) - if nIntake != 0 { - t.Errorf("FK cascade incomplete: intake_entries=%d", nIntake) - } + var nServices, nSettings, nContractDocs int _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices) _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_product_settings WHERE tenant_id = $1`, tid).Scan(&nSettings) _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_contract_documents WHERE tenant_id = $1`, tid).Scan(&nContractDocs) -- 2.54.1 From 37032e649ed9b00d59a2401bcdf471a8654c24e6 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:55:28 +0100 Subject: [PATCH 3/3] fix(usage): malformed tenant id lists no events on postgres pgx reports an invalid UUID from rows.Err, not from Query, so GET /v1/usage/events?tenant_id=not-a-uuid answered 500 on Postgres and 200 on the memory store. It now returns an empty list on both. Co-Authored-By: Claude Opus 5.5 --- internal/server/usage_summary_test.go | 13 +++++++++++++ internal/store/postgres_erp.go | 10 +++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/internal/server/usage_summary_test.go b/internal/server/usage_summary_test.go index b42ff08..c9f64a3 100644 --- a/internal/server/usage_summary_test.go +++ b/internal/server/usage_summary_test.go @@ -154,3 +154,16 @@ func TestUsageSummary_emptyAndBadInput(t *testing.T) { } }) } + +// The event list answers a malformed tenant id like an unknown one: an empty +// list. Postgres reports the bad UUID only once the rows are read. +func TestUsageEvents_malformedTenantIsEmpty(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + for _, id := range []string{"not-a-uuid", "00000000-0000-0000-0000-0000000000ff"} { + resp, raw := h.do("GET", "/v1/usage/events?tenant_id="+id, nil) + if resp.StatusCode != 200 || !bytes.Contains(raw, []byte(`[]`)) { + t.Fatalf("events %s: %d %s", id, resp.StatusCode, raw) + } + } + }) +} diff --git a/internal/store/postgres_erp.go b/internal/store/postgres_erp.go index 8337c42..a655ca2 100644 --- a/internal/store/postgres_erp.go +++ b/internal/store/postgres_erp.go @@ -173,7 +173,15 @@ func (p *Postgres) ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageE } out = append(out, *u) } - return out, rows.Err() + // pgx reports a malformed tenant id only once the rows are read, not + // from Query: a tenant id that is not a UUID matches no events. + if err := rows.Err(); err != nil { + if isInvalidUUID(err) { + return []UsageEvent{}, nil + } + return nil, err + } + return out, nil } func (p *Postgres) MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error { -- 2.54.1