feat(admin): repair a tenant's sign-in, delete an archived tenant (#42)
ci / shared (push) Successful in 15s
ci / test (push) Successful in 23m50s
ci / image (push) Successful in 45s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit was merged in pull request #42.
This commit is contained in:
sharangandClaude Opus 5.5 committed 2026-09-26 11:00:14 +00:00
1 parent 3aa1a8cb8d
commit e8dcd1d259
12 files changed
+610

No files matched your search

+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)