Files
tenant-registry/internal/server/admin.go
T
Sharang ParnerkarandClaude Opus 5.5 19c31278e5
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 23m59s
ci / image (pull_request) Skipped
feat(trial): legal trial signup: offer, confirmation, activation (portal#64 A)
The free trial follows the contract states of the epic: the customer's
binding offer (§ 2 Abs. 1 Testbedingungen) → receipt with confirmation link
(§ 312i Abs. 1 Nr. 3 BGB) → Breakpilot accepts by activating once the
address is confirmed: contract concluded, 14 calendar days start.

- Trial terms v1.0 ("Bedingungen für den kostenlosen Breakpilot-Testzugang",
  Stand 1. Oktober 2026) as committed Markdown, HTML and PDF, embedded, with
  pinned SHA-256; public at /v1/legal/trial-terms[/1.0.{pdf,html,md}], the
  same bytes before the offer, in the activation mail and in the tenant's
  Vertragsunterlagen.
- Migration 0011 trial_offers: the offer snapshot (company, address, person,
  e-mail, terms id/version/sha256, 246c notice version, flow version,
  language, offered_at) is immutable (trigger); only the state moves.
  No IP address or browser fingerprint.
- POST /v1/trial-offers: validation, version check against what the portal
  showed (409 version_mismatch), 409 email_taken, 429 within 10 minutes;
  receipt mail with a single-use 72-hour link (only its hash is stored).
- POST /v1/trial-offers/verify: activated / already_activated / 410 expired
  / 404 invalid. Activation creates the tenant (slug from the company name),
  the Keycloak account with the address already verified (only
  UPDATE_PASSWORD), trial_ends_at = contract time + 14 calendar days in
  Berlin time, the audit chain (offer_submitted, email_verified,
  contract_accepted, activated) and the activation mail with the PDF.
- POST /v1/trial-offers/{id}/resend; GET /v1/tenants/{id}/contracts (trial,
  AVV, TOMs, SaaS; trial null for tenants without an offer) and the exact
  accepted PDF; trial.extension_granted event from the admin extension.
- mail: attachments (multipart/mixed); German-only registry mails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-30 17:36:23 +02:00

307 lines
10 KiB
Go

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
}
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:
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).
ext := map[string]interface{}{"new_expiry": end, "granted_by": r.Header.Get("X-Portal-User-Email"), "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: r.Header.Get("X-Portal-User-Email"), 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})
}