package server import ( "context" "errors" "net/http" "net/mail" "strconv" "strings" "time" "git.breakpilot.com/platform/tenant-registry/internal/authn" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // Staff administration (route group "admin", granted to the portal's service // client only). The portal checks the staff member's realm role and passes // who they are in X-Staff-Subject / X-Staff-Email, so every change lands in // the audit log under the person, not under the portal. const ( headerStaffSubject = "X-Staff-Subject" headerStaffEmail = "X-Staff-Email" activityWindow = 30 * 24 * time.Hour ) // staffActor is the staff member a request acts for: only honoured from a // client that holds the admin group, so a product client cannot claim to be // staff by setting a header. func (s *Server) staffActor(r *http.Request) (subject, email string, ok bool) { if r == nil { return "", "", false } subject = strings.TrimSpace(r.Header.Get(headerStaffSubject)) if subject == "" { return "", "", false } p, has := authn.PrincipalFrom(r.Context()) if !has || p.IsUser() || !s.Authz.Allowed(p.ClientID, "admin") { return "", "", false } return subject, strings.TrimSpace(r.Header.Get(headerStaffEmail)), true } // portalUser is the person the portal names in X-Portal-User-Subject and // X-Portal-User-Email when it calls with its service token. Like staffActor, // it is only honoured from a client that holds the users group (the portal's // service client), so another product client cannot act, or be logged, in a // user's name by setting a header. A user token speaks for itself: the // headers are ignored. Without a principal (AUTH_ENABLED=false, dev) they // are taken as given. func (s *Server) portalUser(r *http.Request) (subject, email string, ok bool) { subject = strings.TrimSpace(r.Header.Get(headerPortalUserSubject)) email = strings.TrimSpace(r.Header.Get(headerPortalUserEmail)) if subject == "" && email == "" { return "", "", false } if p, has := authn.PrincipalFrom(r.Context()); has && (p.IsUser() || !s.Authz.Allowed(p.ClientID, "users.act")) { return "", "", false } return subject, email, true } type adminTenant struct { store.Tenant Activity store.TenantActivity `json:"activity"` } // adminListTenants is GET /v1/admin/tenants?q=&status=&kind=&cursor=&limit=. func (s *Server) adminListTenants(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() f := store.TenantFilter{Status: q.Get("status"), Kind: q.Get("kind"), Query: q.Get("q"), Cursor: q.Get("cursor")} if v := q.Get("limit"); v != "" { n, err := strconv.Atoi(v) if err != nil || n < 1 || n > 500 { writeError(w, http.StatusBadRequest, "invalid_limit", "limit must be 1..500") return } f.Limit = n } if len(f.Query) > 100 { writeError(w, http.StatusBadRequest, "invalid_query", "q must be at most 100 chars") return } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() tenants, next, err := s.Store.ListTenants(ctx, f) if err != nil { if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } ids := make([]string, len(tenants)) for i, t := range tenants { ids[i] = t.ID } act, err := s.Store.TenantActivity(ctx, ids, time.Now().UTC().Add(-activityWindow)) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } items := make([]adminTenant, len(tenants)) for i, t := range tenants { a, ok := act[t.ID] if !ok { a = store.TenantActivity{Usage: map[string]float64{}} } items[i] = adminTenant{Tenant: t, Activity: a} } writeJSON(w, http.StatusOK, map[string]any{"items": items, "next_cursor": next}) } type adminTenantDetail struct { Tenant store.Tenant `json:"tenant"` Activity store.TenantActivity `json:"activity"` Entitlements []store.TenantProduct `json:"entitlements"` Subscriptions []store.Subscription `json:"subscriptions"` Licences []store.Licence `json:"licences"` Members []keycloak.OrgMember `json:"members"` MembersError string `json:"members_error,omitempty"` Audit []store.AuditEvent `json:"audit"` } // adminGetTenant is GET /v1/admin/tenants/{id}: everything staff need on one // page. Keycloak is best effort; its failure is reported, not fatal. func (s *Server) adminGetTenant(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 15*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 } out := adminTenantDetail{Tenant: *t, Members: []keycloak.OrgMember{}} act, err := s.Store.TenantActivity(ctx, []string{t.ID}, time.Now().UTC().Add(-activityWindow)) if err == nil { out.Activity = act[t.ID] } if out.Activity.Usage == nil { out.Activity.Usage = map[string]float64{} } if out.Entitlements, err = s.Store.ListTenantProducts(ctx, t.ID); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if out.Subscriptions, err = s.Store.ListSubscriptions(ctx, t.ID); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if out.Licences, err = s.Store.ListLicences(ctx, t.ID); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if out.Audit, _, err = s.Store.ListAudit(ctx, store.AuditFilter{TenantID: t.ID, Limit: 25}); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if s.Keycloak != nil { members, merr := s.Keycloak.ListOrgMembers(ctx, t.Slug) switch { case merr == nil: decorateMembers(members, t.ID) out.Members = members case errors.Is(merr, keycloak.ErrOrgNotFound): out.MembersError = "no organization yet" default: out.MembersError = merr.Error() } } writeJSON(w, http.StatusOK, out) } type extendTrialReq struct { Days int `json:"days"` } // adminExtendTrial is POST /v1/admin/tenants/{id}/trial {"days": n}. The new // end is n days after the later of now and the current end; trial // entitlements move with it, and a tenant that the expired trial had made // read-only goes back to trial. func (s *Server) adminExtendTrial(w http.ResponseWriter, r *http.Request) { var in extendTrialReq if !decodeJSON(w, r, &in) { return } if in.Days < 1 || in.Days > 90 { writeError(w, http.StatusBadRequest, "invalid_days", "days must be 1..90") return } ctx, cancel := context.WithTimeout(r.Context(), 10*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 } now := time.Now().UTC() switch t.Status { case store.StatusTrial: case store.StatusRestricted, store.StatusFrozen, store.StatusHalted: // Only when the expired trial is the reason: the trial end has passed // and the tenant never had a subscription (a customer who stopped // paying is not extended from here). if t.TrialEndsAt == nil || t.TrialEndsAt.After(now) || s.hasSubscriptions(ctx, t.ID) { writeError(w, http.StatusConflict, "not_a_trial", "tenant is "+t.Status+" for a reason other than an expired trial") return } default: writeError(w, http.StatusConflict, "not_a_trial", "only a trial (or a tenant stopped by an expired trial) can be extended") return } base := now if t.TrialEndsAt != nil && t.TrialEndsAt.After(now) { base = *t.TrialEndsAt } end := base.Add(time.Duration(in.Days) * 24 * time.Hour) previous := t.TrialEndsAt t, err = s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{TrialEndsAt: &end}) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } tps, err := s.Store.ListTenantProducts(ctx, t.ID) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } for _, tp := range tps { if tp.ExpiresAt == nil || tp.Config["source"] != "trial" { continue } tp.ExpiresAt, tp.Enabled = &end, true if _, err := s.Store.UpsertTenantProduct(ctx, tp); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } } if t.Status != store.StatusTrial { if t, err = s.transition(ctx, r, t, store.StatusTrial, "staff:trial_extended"); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } } meta := map[string]interface{}{"days": in.Days, "trial_ends_at": end} if previous != nil { meta["previous_trial_ends_at"] = *previous } s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "tenant.trial_extended", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug, ActorType: "service", Metadata: meta, }) // portal#64 §10: the extension of the trial contract as its own event, // without a new contract (§ 3 Abs. 3 Testbedingungen). _, grantedBy, _ := s.portalUser(r) ext := map[string]interface{}{"new_expiry": end, "granted_by": grantedBy, "granted_at": now} if previous != nil { ext["old_expiry"] = *previous } s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "trial.extension_granted", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug, ActorType: "staff", ActorName: grantedBy, Metadata: ext, }) writeJSON(w, http.StatusOK, t) } // hasSubscriptions reports whether the tenant ever had a subscription. An // error counts as yes, so a failed lookup never unlocks a paying customer. func (s *Server) hasSubscriptions(ctx context.Context, tenantID string) bool { subs, err := s.Store.ListSubscriptions(ctx, tenantID) return err != nil || len(subs) > 0 } type resendInviteReq struct { Email string `json:"email"` } // adminResendInvite is POST /v1/admin/tenants/{id}/invites/resend {"email"}. func (s *Server) adminResendInvite(w http.ResponseWriter, r *http.Request) { var in resendInviteReq if !decodeJSON(w, r, &in) { return } in.Email = strings.ToLower(strings.TrimSpace(in.Email)) if addr, err := mail.ParseAddress(in.Email); err != nil || addr.Address != in.Email { writeError(w, http.StatusBadRequest, "invalid_email", "email must be a bare, valid address") return } ctx, cancel := context.WithTimeout(r.Context(), 15*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 s.Keycloak == nil { writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", "no identity provider configured") return } if err := s.Keycloak.ResendInvite(ctx, t.Slug, in.Email); err != nil { switch { case errors.Is(err, keycloak.ErrOrgNotFound): writeError(w, http.StatusConflict, "org_not_provisioned", "tenant has no Keycloak organization yet") case errors.Is(err, keycloak.ErrUserNotFound): writeError(w, http.StatusNotFound, "not_a_member", "no member with that email in this tenant") default: s.writeKeycloakError(w, t.ID, "resend invite", err) } return } s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "user.invite_resent", TargetID: in.Email, TargetType: "user", TargetName: in.Email, ActorType: "service", }) writeJSON(w, http.StatusAccepted, map[string]string{"status": "sent", "email": in.Email}) }