package server import ( "context" "errors" "fmt" "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, TenantStatus: s.onPremStatus(t)}) 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" } else if s.onPrem() { outcome = "added" } 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 } switch { case res.Status == keycloak.InviteStatusAdded: outcome = "added" case res.Status == keycloak.InviteStatusMember: err := s.Keycloak.ResendInvite(ctx, t.Slug, email) switch { case errors.Is(err, keycloak.ErrNoInviteMail): outcome = "member" // a directory user: nothing to resend case err != nil: s.writeKeycloakError(w, t.ID, "reprovision", err) return default: 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=: 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= of the tenant") return } if t.Status != store.StatusArchived { writeError(w, http.StatusConflict, "not_archived", "only an archived tenant can be deleted") return } // Security reports outlive their workspace (docgen#6 decision Nr. 17, // V-g): checked before anything is removed. if n, err := s.Store.CountIntakeReports(ctx, t.ID); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } else if n > 0 { writeError(w, http.StatusConflict, "intake_retained", fmt.Sprintf("the workspace has %d security report(s); they are kept, so the workspace cannot be deleted", n)) return } docs, err := s.Store.ListDocuments(ctx, t.ID, false) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } contractDocs, err := s.Store.ListContractDocuments(ctx, t.ID) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if len(docs)+len(contractDocs) > 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 } } // The tenant's filled contract documents (0027) go with it. for _, d := range contractDocs { if err := s.Objects.Delete(ctx, d.ObjectKey); err != nil { s.Log.Error("purge: delete contract document object failed", "tenant_id", t.ID, "contract_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), "contract_documents_removed": len(contractDocs)} 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)}) }