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
167 lines
5.8 KiB
Go
167 lines
5.8 KiB
Go
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)})
|
|
}
|