Files
tenant-registry/internal/server/admin_lifecycle.go
T
Sharang ParnerkarandClaude Opus 5.5 400d1b1678
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 6m36s
ci / image (pull_request) Skipped
feat(connections): connect two workspaces by code (#138)
A workspace administrator creates a code (160 random bits, 14 days,
single use, stored as SHA-256 only); another workspace's administrator
enters it and the two are connected at once. Each side sees only the
other's display name. Every code that does not work gets the same 404,
and entering codes is limited to 20 per hour per workspace and person.
Either side can end a connection; archiving a workspace ends all of its
connections, and a purged side leaves the other an ended connection
with the name it knew. Both audit logs record each step; the other
side's entry names neither the person nor the address.

Products read the active connections and check one before each
delivery under the new route group connections.read
(GET /v1/internal/tenants/{id}/connections, GET
/v1/internal/connections/{connection}).

The Postgres GetTenant now answers a non-UUID id as not found (404),
as the memory store does, instead of a 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-20 09:39:56 +01:00

192 lines
7.1 KiB
Go

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})
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
}
// 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
}
// Archiving ended its connections; this only catches a failure then.
s.endTenantConnections(ctx, t, "tenant_purged")
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)})
}