ci / shared (pull_request) Skipped
On-prem every account comes from the customer's AD through Keycloak's federation, so an AD admin answered email_taken and invitations asked for a new password. The Keycloak adapter gets a directory mode (DirectoryUsers, on with APP_ENV=onprem): - The first admin and invited members are existing directory users, attached to the organization with their role. No local user is created, no execute-actions mail is sent (invite status "added", audit user.added / keycloak.admin_added). - An unknown address (or one outside the admitted AD groups) answers 404 not_in_directory. For the workspace's admin it is checked before the workspace is created, and the adapter looks the user up before creating the organization, so nothing is left behind. - Resend answers 409 no_invite_mail; directory members are never pending. - Member lists read the roles from the user when Keycloak lists a federated member with its LDAP attributes only (seen with Keycloak 26.8). - The admin address is normalized once for lookup, store and Keycloak. Checked against Keycloak 26.8.1 with a Samba AD (the test install in platform/onprem, realm with UNSYNCED federation and realm-policy.sh). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
200 lines
7.2 KiB
Go
200 lines
7.2 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, TenantStatus: t.Status})
|
|
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=<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
|
|
}
|
|
|
|
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)})
|
|
}
|