feat(admin): repair a tenant's sign-in, delete an archived tenant
ci / shared (pull_request) Successful in 17s
ci / test (pull_request) Failing after 5m34s
ci / image (pull_request) Skipped

Found on staging: a workspace whose Keycloak organization and admin
were deleted by hand stayed in the registry. Its name could not be
used again, and setting it back to trial did not bring the sign-in
back, because nothing re-creates the Keycloak side.

- POST /v1/admin/tenants/{id}/reprovision creates the organization with
  the admin invited when it is missing, invites the admin into an
  existing one, or sends the invitation again; then syncs the status.
- DELETE /v1/admin/tenants/{id}?confirm=<slug> removes an archived
  tenant: document files, then the Keycloak organization and the
  accounts whose tenant_id names this tenant, then the tenant row, whose
  foreign keys take everything attached. The ERP customer and the audit
  trail stay; tenant.purged records the staff member. The name is free.
- Store.DeleteTenant (memory and Postgres), Adapter.PurgeTenant (HTTP
  and mock), OpenAPI, tests against both stores and a stub Keycloak.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-09-26 12:07:49 +02:00
1 parent 3aa1a8cb8d
commit 6f3451272c
12 files changed
+610

No files matched your search

+5
View File
@@ -154,6 +154,11 @@ type Adapter interface {
// email. Signup checks it first: an address can belong to one workspace.
UserExists(ctx context.Context, email string) (bool, error)
// PurgeTenant deletes the organization whose alias is slug and the
// accounts that belong to tenantID (org members and the given e-mails).
// Returns how many accounts were removed; a missing org is not an error.
PurgeTenant(ctx context.Context, slug, tenantID string, emails []string) (int, error)
// SyncTenantStatus writes the coarse tenant_status attribute on every
// member of the organization whose alias is slug (ERP/02: Keycloak
// carries only the coarse flag; entitlements stay in the registry).
+57
View File
@@ -323,3 +323,60 @@ func TestHTTPAdapter_inviteMailRefused(t *testing.T) {
t.Fatalf("result = %+v", res)
}
}
func TestHTTPAdapter_purgeTenant(t *testing.T) {
var deleted []string
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
mux.HandleFunc("/admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{{"id": "org-1", "alias": "acme"}})
})
mux.HandleFunc("/admin/realms/test-realm/organizations/org-1/members", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{{"id": "u-mine"}, {"id": "u-other"}})
})
mux.HandleFunc("/admin/realms/test-realm/organizations/org-1", func(w http.ResponseWriter, r *http.Request) {
deleted = append(deleted, r.Method+" org-1")
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
// The first admin, no longer an org member.
_ = json.NewEncoder(w).Encode([]map[string]any{{"id": "u-admin", "email": "it@acme.test"}})
})
users := map[string]string{"u-mine": "t1", "u-other": "t2", "u-admin": "t1"}
for id, tenant := range users {
mux.HandleFunc("/admin/realms/test-realm/users/"+id, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
deleted = append(deleted, "DELETE "+id)
w.WriteHeader(http.StatusNoContent)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": id, "attributes": map[string][]string{"tenant_id": {tenant}}})
})
}
srv := httptest.NewServer(mux)
defer srv.Close()
n, err := newTestAdapter(srv).PurgeTenant(context.Background(), "acme", "t1", []string{"it@acme.test", ""})
if err != nil || n != 2 {
t.Fatalf("removed %d, err %v", n, err)
}
if strings.Join(deleted, ",") != "DELETE u-mine,DELETE u-admin,DELETE org-1" {
t.Fatalf("deleted: %v", deleted)
}
}
func TestHTTPAdapter_purgeTenantWithoutOrg(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
mux.HandleFunc("/admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{})
})
mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{})
})
srv := httptest.NewServer(mux)
defer srv.Close()
if n, err := newTestAdapter(srv).PurgeTenant(context.Background(), "gone", "t1", []string{"x@y.test"}); err != nil || n != 0 {
t.Fatalf("removed %d, err %v", n, err)
}
}
+30
View File
@@ -26,6 +26,7 @@ type Mock struct {
Members map[string][]OrgMember
Invites []MemberInviteInput // every InviteMember call that sent a mail
Resent []string // every ResendInvite call that found the member
Purged []string // every PurgeTenant call, by slug
}
func NewMock() *Mock {
@@ -190,3 +191,32 @@ func (m *Mock) SyncClaims(_ context.Context, userID string, c Claims) error {
m.Claims[userID] = c
return nil
}
// PurgeTenant implements Adapter: drops the org and the users recorded for
// its members and the given e-mails.
func (m *Mock) PurgeTenant(_ context.Context, slug, tenantID string, emails []string) (int, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.FailNext != nil {
err := m.FailNext
m.FailNext = nil
return 0, err
}
removed := 0
for _, mem := range m.Members[slug] {
if _, ok := m.Users[mem.Email]; ok {
delete(m.Users, mem.Email)
removed++
}
}
for _, e := range emails {
if _, ok := m.Users[e]; ok {
delete(m.Users, e)
removed++
}
}
delete(m.Members, slug)
delete(m.Orgs, tenantID)
m.Purged = append(m.Purged, slug)
return removed, nil
}
+95
View File
@@ -0,0 +1,95 @@
package keycloak
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"slices"
)
// PurgeTenant implements Adapter: it removes the organization whose alias is
// slug and the accounts that belong to this tenant, found among the org's
// members and by the extra e-mails (the tenant's first admin, whose org
// membership may already be gone). An account is only deleted when its
// tenant_id attribute names this tenant, so a person who also belongs to
// another workspace is never removed. A missing org or user is not an error.
func (a *HTTPAdapter) PurgeTenant(ctx context.Context, slug, tenantID string, emails []string) (int, error) {
var userIDs []string
orgID, err := a.findOrgByAlias(ctx, slug)
switch {
case err == nil:
var members []memberRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/organizations/%s/members?max=500", orgID), nil, &members)
if err != nil {
return 0, err
}
if resp.StatusCode/100 != 2 {
_ = resp.Body.Close()
return 0, fmt.Errorf("list members: %d", resp.StatusCode)
}
for _, m := range members {
userIDs = append(userIDs, m.ID)
}
case errors.Is(err, ErrOrgNotFound):
orgID = ""
default:
return 0, err
}
for _, e := range emails {
if e == "" {
continue
}
id, err := a.findUserByEmail(ctx, e)
if err == nil && !slices.Contains(userIDs, id) {
userIDs = append(userIDs, id)
} else if err != nil && !errors.Is(err, errUserLookupMiss) {
return 0, err
}
}
removed := 0
for _, id := range userIDs {
var u memberRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+id, nil, &u)
if err != nil {
return removed, err
}
if resp.StatusCode == http.StatusNotFound {
_ = resp.Body.Close()
continue
}
if resp.StatusCode/100 != 2 {
_ = resp.Body.Close()
return removed, fmt.Errorf("get user: %d", resp.StatusCode)
}
if !slices.Contains(u.Attributes["tenant_id"], tenantID) {
continue
}
if err := a.deleteResource(ctx, "/users/"+id); err != nil {
return removed, fmt.Errorf("delete user: %w", err)
}
removed++
}
if orgID != "" {
if err := a.deleteResource(ctx, "/organizations/"+orgID); err != nil {
return removed, fmt.Errorf("delete org: %w", err)
}
}
return removed, nil
}
// deleteResource DELETEs an admin resource; 404 counts as already gone.
func (a *HTTPAdapter) deleteResource(ctx context.Context, path string) error {
resp, err := a.adminCall(ctx, http.MethodDelete, path, nil, nil)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode/100 == 2 || resp.StatusCode == http.StatusNotFound {
return nil
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
return fmt.Errorf("%d %s", resp.StatusCode, body)
}
+166
View File
@@ -0,0 +1,166 @@
package server
import (
"context"
"errors"
"net/http"
"net/mail"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
type reprovisionReq struct {
// Email of the admin to (re-)invite; defaults to the tenant's first admin.
Email string `json:"email"`
}
// adminReprovision is POST /v1/admin/tenants/{id}/reprovision: repairs a
// tenant whose sign-in no longer works because its Keycloak organization or
// its admin account is missing (the registry is the record; Keycloak is
// brought back in line). A missing organization is created with the admin
// invited; an existing one gets the admin invited, or the invitation sent
// again if the admin is already a member.
func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) {
var in reprovisionReq
if r.ContentLength != 0 && !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if t.Status == store.StatusArchived {
writeError(w, http.StatusConflict, "tenant_archived", "an archived tenant has no sign-in; change its status first")
return
}
email := strings.ToLower(strings.TrimSpace(in.Email))
if email == "" {
email = t.AdminEmail
}
if addr, err := mail.ParseAddress(email); email == "" || err != nil || addr.Address != email {
writeError(w, http.StatusBadRequest, "invalid_email", "no admin e-mail on record; pass one")
return
}
outcome := "invited"
_, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug)
switch {
case errors.Is(lerr, keycloak.ErrOrgNotFound):
res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email})
if err != nil {
if errors.Is(err, keycloak.ErrUserConflict) {
writeError(w, http.StatusConflict, "email_taken", "an account with this e-mail exists outside this tenant")
return
}
s.writeKeycloakError(w, t.ID, "reprovision", err)
return
}
if res.MailError != nil {
outcome = "created_mail_failed"
}
case lerr != nil:
s.writeKeycloakError(w, t.ID, "reprovision", lerr)
return
default:
res, err := s.Keycloak.InviteMember(ctx, keycloak.MemberInviteInput{TenantID: t.ID, Slug: t.Slug, TenantStatus: t.Status, Email: email, Role: "IT_ADMIN"})
if err != nil {
s.writeKeycloakError(w, t.ID, "reprovision", err)
return
}
if res.Status == keycloak.InviteStatusMember {
if err := s.Keycloak.ResendInvite(ctx, t.Slug, email); err != nil {
s.writeKeycloakError(w, t.ID, "reprovision", err)
return
}
outcome = "resent"
}
}
if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil {
s.Log.Warn("keycloak status sync after reprovision failed", "tenant_id", t.ID, "err", err)
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "tenant.signin_reprovisioned", TargetID: email, TargetType: "user", TargetName: email,
ActorType: "service", Metadata: map[string]interface{}{"outcome": outcome},
})
writeJSON(w, http.StatusOK, map[string]string{"status": outcome, "email": email})
}
// 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.
func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if r.URL.Query().Get("confirm") != t.Slug {
writeError(w, http.StatusBadRequest, "confirm_mismatch", "pass ?confirm=<slug> of the tenant")
return
}
if t.Status != store.StatusArchived {
writeError(w, http.StatusConflict, "not_archived", "only an archived tenant can be deleted")
return
}
docs, err := s.Store.ListDocuments(ctx, t.ID, false)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if len(docs) > 0 && s.Objects == nil {
writeError(w, http.StatusServiceUnavailable, "storage_unavailable", "document storage is not configured")
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)
writeError(w, http.StatusBadGateway, "storage_error", "a document file could not be deleted; nothing else was removed")
return
}
}
var emails []string
if t.AdminEmail != "" {
emails = append(emails, t.AdminEmail)
}
accounts, err := s.Keycloak.PurgeTenant(ctx, t.Slug, t.ID, emails)
if err != nil {
s.writeKeycloakError(w, t.ID, "purge", err)
return
}
if err := s.Store.DeleteTenant(ctx, t.ID); err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
meta := map[string]interface{}{"slug": t.Slug, "name": t.Name, "accounts_removed": accounts, "documents_removed": len(docs)}
if t.ErpCustomerID != "" {
meta["erp_customer_id_kept"] = t.ErpCustomerID
}
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)})
}
+134
View File
@@ -0,0 +1,134 @@
package server_test
import (
"net/http"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func createWithAdmin(t *testing.T, h *testHarness, slug, email string) *store.Tenant {
t.Helper()
resp, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": slug, "name": slug + " GmbH", "admin_email": email})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create %s: %d %s", slug, resp.StatusCode, raw)
}
return decode[struct {
Tenant *store.Tenant `json:"tenant"`
}](t, raw).Tenant
}
func auditCount(t *testing.T, h *testHarness, q string) int {
t.Helper()
_, raw := h.do("GET", "/v1/audit?"+q, nil)
return len(decode[struct {
Items []store.AuditEvent `json:"items"`
}](t, raw).Items)
}
func TestAdminReprovision(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := createWithAdmin(t, h, "repro-co", "it@repro.test")
// Someone removed the org and the account in Keycloak by hand.
delete(h.kcMock.Orgs, tn.ID)
delete(h.kcMock.Users, "it@repro.test")
resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/reprovision", nil)
if resp.StatusCode != http.StatusOK || !strings.Contains(string(raw), `"status":"invited"`) || !strings.Contains(string(raw), "it@repro.test") {
t.Fatalf("reprovision: %d %s", resp.StatusCode, raw)
}
if _, ok := h.kcMock.Orgs[tn.ID]; !ok {
t.Fatal("org not recreated")
}
if n := auditCount(t, h, "action=tenant.signin_reprovisioned&tenant_id="+tn.ID); n != 1 {
t.Fatalf("audit events: %d", n)
}
// With the org present and the admin a member, the invitation goes out again.
h.kcMock.Members["repro-co"] = []keycloak.OrgMember{{UserID: "u1", Email: "it@repro.test"}}
if resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/reprovision", map[string]any{"email": "IT@repro.test"}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"resent"`) {
t.Fatalf("resend: %d %s", resp.StatusCode, raw)
}
// An existing org and a new address: the person is invited into it.
if resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/reprovision", map[string]any{"email": "second@repro.test"}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"invited"`) {
t.Fatalf("invite into org: %d %s", resp.StatusCode, raw)
}
})
}
func TestAdminReprovisionRejects(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
noAdmin := newTenant(t, h, "no-admin-co")
if resp, _ := h.do("POST", "/v1/admin/tenants/"+noAdmin.ID+"/reprovision", nil); resp.StatusCode != 400 {
t.Fatalf("no admin on record: %d", resp.StatusCode)
}
if resp, _ := h.do("POST", "/v1/admin/tenants/"+noAdmin.ID+"/reprovision", map[string]any{"email": "not an email"}); resp.StatusCode != 400 {
t.Fatalf("bad email: %d", resp.StatusCode)
}
// The address already belongs to another workspace's account.
h.kcMock.Users["taken@x.test"] = "u-other"
if resp, _ := h.do("POST", "/v1/admin/tenants/"+noAdmin.ID+"/reprovision", map[string]any{"email": "taken@x.test"}); resp.StatusCode != 409 {
t.Fatalf("taken: %d", resp.StatusCode)
}
if resp, _ := h.do("POST", "/v1/tenants/"+noAdmin.ID+"/status", map[string]any{"status": "archived", "source": "test"}); resp.StatusCode != 200 {
t.Fatalf("archive: %d", resp.StatusCode)
}
if resp, _ := h.do("POST", "/v1/admin/tenants/"+noAdmin.ID+"/reprovision", map[string]any{"email": "a@b.test"}); resp.StatusCode != 409 {
t.Fatalf("archived: %d", resp.StatusCode)
}
if resp, _ := h.do("POST", "/v1/admin/tenants/00000000-0000-0000-0000-00000000dead/reprovision", nil); resp.StatusCode != 404 {
t.Fatalf("unknown: %d", resp.StatusCode)
}
h.kcMock.FailNext = keycloak.ErrUnavailable
other := createWithAdmin(t, h, "kc-down-co", "it@down.test")
h.kcMock.FailNext = keycloak.ErrUnavailable
if resp, _ := h.do("POST", "/v1/admin/tenants/"+other.ID+"/reprovision", nil); resp.StatusCode != 503 {
t.Fatalf("keycloak down: %d", resp.StatusCode)
}
})
}
func TestAdminPurgeTenant(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := createWithAdmin(t, h, "purge-co", "it@purge.test")
base := "/v1/admin/tenants/" + tn.ID
if resp, _ := h.do("DELETE", base+"?confirm=purge-co", nil); resp.StatusCode != 409 {
t.Fatalf("not archived: %d", resp.StatusCode)
}
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)
}
if resp, _ := h.do("DELETE", base+"?confirm=wrong", nil); resp.StatusCode != 400 {
t.Fatalf("confirm mismatch: %d", resp.StatusCode)
}
h.kcMock.FailNext = keycloak.ErrUnavailable
if resp, _ := h.do("DELETE", base+"?confirm=purge-co", nil); resp.StatusCode != 503 {
t.Fatalf("keycloak down keeps the tenant: %d", resp.StatusCode)
}
if resp, _ := h.do("GET", "/v1/tenants/"+tn.ID, nil); resp.StatusCode != 200 {
t.Fatalf("tenant gone after failed purge: %d", resp.StatusCode)
}
resp, raw := h.do("DELETE", base+"?confirm=purge-co", nil)
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"purged"`) || !strings.Contains(string(raw), `"accounts_removed":1`) {
t.Fatalf("purge: %d %s", resp.StatusCode, raw)
}
if resp, _ := h.do("GET", "/v1/tenants/"+tn.ID, nil); resp.StatusCode != 404 {
t.Fatalf("tenant still there: %d", resp.StatusCode)
}
if len(h.kcMock.Purged) != 1 || h.kcMock.Purged[0] != "purge-co" {
t.Fatalf("keycloak purge: %v", h.kcMock.Purged)
}
if n := auditCount(t, h, "action=tenant.purged"); n != 1 {
t.Fatalf("purge audit: %d", n)
}
// The name and the address are free again.
createWithAdmin(t, h, "purge-co", "it@purge.test")
if resp, _ := h.do("DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-00000000dead?confirm=x", nil); resp.StatusCode != 404 {
t.Fatalf("unknown: %d", resp.StatusCode)
}
})
}
+2
View File
@@ -52,6 +52,8 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001"},
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"},
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/invites/resend"},
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/reprovision"},
{"DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001"},
{"GET", "/v1/admin/audit?limit=10"},
{"POST", "/v1/notifications"},
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/documents"},
+2
View File
@@ -153,6 +153,8 @@ func NewRouter(s *Server) http.Handler {
mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant)
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial)
mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite)
mux.HandleFunc("POST /v1/admin/tenants/{id}/reprovision", s.adminReprovision)
mux.HandleFunc("DELETE /v1/admin/tenants/{id}", s.adminPurgeTenant)
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments)
mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument)
+63
View File
@@ -501,3 +501,66 @@ func firstNonEmpty(values ...string) string {
}
return ""
}
// DeleteTenant implements Store.
func (m *Memory) DeleteTenant(_ context.Context, id string) error {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tenants[id]
if !ok {
return ErrNotFound
}
delete(m.tenants, id)
delete(m.bySlug, t.Slug)
delete(m.products, id)
for kid, k := range m.apiKeys {
if k.TenantID == id {
delete(m.byPrefix, k.Prefix)
delete(m.apiKeys, kid)
}
}
for sid, sub := range m.subs {
if sub.TenantID == id {
delete(m.subs, sid)
}
}
for lid, l := range m.licences {
if l.TenantID == id {
delete(m.licences, lid)
}
}
for did, d := range m.documents {
if d.TenantID == id {
delete(m.documents, did)
}
}
usage := m.usage[:0]
for _, u := range m.usage {
if u.TenantID != id {
usage = append(usage, u)
} else {
delete(m.usageKey, u.IdempotencyKey)
}
}
m.usage = usage
outbox := m.outbox[:0]
for _, o := range m.outbox {
if o.TenantID != id {
outbox = append(outbox, o)
}
}
m.outbox = outbox
mail := m.mail[:0]
for _, mi := range m.mail {
if mi.TenantID != id {
mail = append(mail, mi)
}
}
m.mail = mail
for _, a := range m.audit {
if a.TenantID == id {
a.TenantID = ""
}
}
return nil
}
+13
View File
@@ -681,3 +681,16 @@ func (p *Postgres) TenantActivity(ctx context.Context, tenantIDs []string, since
}
return out, rows.Err()
}
// DeleteTenant implements Store. The foreign keys do the rest: every table
// that belongs to a tenant cascades, audit_log keeps its rows (SET NULL).
func (p *Postgres) DeleteTenant(ctx context.Context, id string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM tenants WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
+6
View File
@@ -132,6 +132,12 @@ type Store interface {
CreateDocument(ctx context.Context, d Document) (*Document, error)
GetDocument(ctx context.Context, id string) (*Document, error)
ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error)
// DeleteTenant removes the tenant and everything that belongs to it
// (entitlements, keys, subscriptions, usage, licences, outbox, documents,
// mail). Audit events stay, with the tenant reference cleared.
// ErrNotFound when there is no such tenant.
DeleteTenant(ctx context.Context, id string) error
PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error)
DeleteDocument(ctx context.Context, id string) error
+37
View File
@@ -354,6 +354,20 @@ paths:
audit: { type: array, items: { type: object } }
"404": { $ref: "#/components/responses/NotFound" }
delete:
summary: Delete an archived tenant for good.
description: |
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.
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. }
responses:
"200": { description: Deleted. }
"400": { $ref: "#/components/responses/BadRequest" }
"404": { $ref: "#/components/responses/NotFound" }
"409": { $ref: "#/components/responses/Conflict" }
/v1/admin/tenants/{id}/trial:
post:
summary: Extend a trial.
@@ -402,6 +416,29 @@ paths:
"404": { $ref: "#/components/responses/NotFound" }
"409": { $ref: "#/components/responses/Conflict" }
/v1/admin/tenants/{id}/reprovision:
post:
summary: Repair a tenant's sign-in when its Keycloak organization or admin account is missing.
description: |
Creates the organization with the admin invited when it is missing, invites the admin into an
existing one, or sends the invitation again when the admin is already a member. The admin is
the one given, else the tenant's first admin on record.
parameters:
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
email: { type: string, format: email }
responses:
"200": { description: "Done: status is invited, resent or created_mail_failed." }
"400": { $ref: "#/components/responses/BadRequest" }
"404": { $ref: "#/components/responses/NotFound" }
"409": { $ref: "#/components/responses/Conflict" }
/v1/admin/audit:
get:
summary: The audit log across all tenants (same filters as /v1/audit).