diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index 51bc29c..4287e8a 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -141,6 +141,11 @@ type Adapter interface { // missing. InviteMember(ctx context.Context, in MemberInviteInput) (*MemberInviteResult, error) + // ResendInvite mails the invitation again to a member of the organization + // whose alias is slug (verify email + set password). ErrOrgNotFound when + // the org is missing, ErrUserNotFound when email is not a member of it. + ResendInvite(ctx context.Context, slug, email string) error + // SyncTenantStatus writes the coarse tenant_status attribute on every // member of the organization whose alias is slug (ERP/02: Keycloak // carries only the coarse flag; entitlements stay in the registry). diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index 73df540..d944160 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "net/url" + "strings" "time" ) @@ -216,3 +217,17 @@ func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, a } return nil } + +func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error { + members, err := a.ListOrgMembers(ctx, slug) + if err != nil { + return err + } + for _, m := range members { + if strings.EqualFold(m.Email, email) { + _, err := a.executeActionsEmail(ctx, m.UserID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.cfg.InviteRedirectURI) + return err + } + } + return ErrUserNotFound +} diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index 060798b..585ff06 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -24,6 +24,7 @@ type Mock struct { // seed an empty slice for an org with no members. Members map[string][]OrgMember Invites []MemberInviteInput // every InviteMember call that sent a mail + Resent []string // every ResendInvite call that found the member } func NewMock() *Mock { @@ -84,6 +85,27 @@ func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInv return &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: !created}, nil } +func (m *Mock) ResendInvite(_ context.Context, slug, email string) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.FailNext != nil { + err := m.FailNext + m.FailNext = nil + return err + } + members, ok := m.Members[slug] + if !ok { + return ErrOrgNotFound + } + for _, mem := range members { + if strings.EqualFold(mem.Email, email) { + m.Resent = append(m.Resent, email) + return nil + } + } + return ErrUserNotFound +} + func (m *Mock) SyncTenantStatus(_ context.Context, slug, status string) error { m.mu.Lock() defer m.mu.Unlock() diff --git a/internal/server/admin.go b/internal/server/admin.go new file mode 100644 index 0000000..49ae7c4 --- /dev/null +++ b/internal/server/admin.go @@ -0,0 +1,296 @@ +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, + }) + 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}) +} diff --git a/internal/server/admin_test.go b/internal/server/admin_test.go new file mode 100644 index 0000000..c71049d --- /dev/null +++ b/internal/server/admin_test.go @@ -0,0 +1,177 @@ +package server_test + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +func TestAdminListTenants_searchAndActivity(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + other := newTenant(t, h, "globex-werke") + ev := map[string]any{"idempotency_key": "adm-1", "tenant_id": other.ID, "product": "pruefwerk", "metric": "scan.completed", "quantity": 2, + "occurred_at": time.Now().UTC().Format(time.RFC3339)} + if resp, raw := h.do("POST", "/v1/usage/events", ev); resp.StatusCode != 202 { + t.Fatalf("usage: %d %s", resp.StatusCode, raw) + } + + resp, raw := h.do("GET", "/v1/admin/tenants?q=GLOBEX", nil) + if resp.StatusCode != 200 { + t.Fatalf("list: %d %s", resp.StatusCode, raw) + } + var out struct { + Items []struct { + Slug string `json:"slug"` + Activity struct { + Usage map[string]float64 `json:"usage"` + LastActivityAt *time.Time `json:"last_activity_at"` + } `json:"activity"` + } `json:"items"` + } + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatal(err) + } + if len(out.Items) != 1 || out.Items[0].Slug != "globex-werke" { + t.Fatalf("search: %s", raw) + } + if out.Items[0].Activity.Usage["scan.completed"] != 2 || out.Items[0].Activity.LastActivityAt == nil { + t.Fatalf("activity: %s", raw) + } + + // no filter: both tenants, activity present (possibly empty) for each + _, raw = h.do("GET", "/v1/admin/tenants", nil) + if !strings.Contains(string(raw), `"acme"`) || !strings.Contains(string(raw), `"usage":{}`) { + t.Fatalf("unfiltered: %s", raw) + } + // wildcards in the query are literal + _, raw = h.do("GET", "/v1/admin/tenants?q=%25", nil) + if !strings.Contains(string(raw), `"items":[]`) { + t.Fatalf("wildcard matched: %s", raw) + } + if resp, _ := h.do("GET", "/v1/admin/tenants?limit=0", nil); resp.StatusCode != 400 { + t.Fatalf("limit: %d", resp.StatusCode) + } + if resp, _ := h.do("GET", "/v1/admin/tenants?q="+strings.Repeat("x", 101), nil); resp.StatusCode != 400 { + t.Fatalf("long q: %d", resp.StatusCode) + } + }) +} + +func TestAdminGetTenant_detail(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{{UserID: "u1", Email: "it@acme.test", OrgRoles: []string{"IT_ADMIN"}}} + resp, raw := h.do("GET", "/v1/admin/tenants/"+h.tenant.ID, nil) + if resp.StatusCode != 200 { + t.Fatalf("detail: %d %s", resp.StatusCode, raw) + } + for _, want := range []string{`"tenant":{`, `"entitlements":`, `"subscriptions":`, `"licences":`, `"it@acme.test"`, `"audit":`} { + if !strings.Contains(string(raw), want) { + t.Fatalf("missing %s in %s", want, raw) + } + } + // no organization yet: members empty, reason given + other := newTenant(t, h, "no-org") + _, raw = h.do("GET", "/v1/admin/tenants/"+other.ID, nil) + if !strings.Contains(string(raw), `"members":[]`) || !strings.Contains(string(raw), "no organization yet") { + t.Fatalf("no org: %s", raw) + } + if resp, _ := h.do("GET", "/v1/admin/tenants/00000000-0000-0000-0000-00000000dead", nil); resp.StatusCode != 404 { + t.Fatalf("unknown: %d", resp.StatusCode) + } + }) +} + +func TestAdminExtendTrial(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + ctx := context.Background() + tn := newTenant(t, h, "trial-co") + end := time.Now().UTC().Add(3 * 24 * time.Hour) + if _, err := h.store.UpdateTenant(ctx, tn.ID, store.TenantUpdate{Status: ptr("trial"), TrialEndsAt: &end}); err != nil { + t.Fatal(err) + } + if _, err := h.store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: tn.ID, Product: "pruefwerk", Enabled: true, + Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &end}); err != nil { + t.Fatal(err) + } + + if resp, _ := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 0}); resp.StatusCode != 400 { + t.Fatalf("days 0: %d", resp.StatusCode) + } + resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 7}) + if resp.StatusCode != 200 { + t.Fatalf("extend: %d %s", resp.StatusCode, raw) + } + got, _ := h.store.GetTenant(ctx, tn.ID) + want := end.Add(7 * 24 * time.Hour) + if got.TrialEndsAt == nil || got.TrialEndsAt.Sub(want).Abs() > time.Second { + t.Fatalf("trial end %v, want %v", got.TrialEndsAt, want) + } + tps, _ := h.store.ListTenantProducts(ctx, tn.ID) + if len(tps) != 1 || tps[0].ExpiresAt.Sub(want).Abs() > time.Second { + t.Fatalf("entitlement not moved: %+v", tps) + } + items, _, _ := h.store.ListAudit(ctx, store.AuditFilter{TenantID: tn.ID, Action: "tenant.trial_extended"}) + if len(items) != 1 { + t.Fatalf("audit: %+v", items) + } + + // an expired trial that made the tenant read-only goes back to trial + past := time.Now().UTC().Add(-2 * 24 * time.Hour) + if _, err := h.store.UpdateTenant(ctx, tn.ID, store.TenantUpdate{Status: ptr("restricted"), TrialEndsAt: &past}); err != nil { + t.Fatal(err) + } + if resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 5}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"trial"`) { + t.Fatalf("restricted: %d %s", resp.StatusCode, raw) + } + got, _ = h.store.GetTenant(ctx, tn.ID) + if d := time.Until(*got.TrialEndsAt); d < 4*24*time.Hour || d > 5*24*time.Hour+time.Minute { + t.Fatalf("restart from now: %v", d) + } + + // an active customer is not a trial + if _, err := h.store.UpdateTenant(ctx, tn.ID, store.TenantUpdate{Status: ptr("active")}); err != nil { + t.Fatal(err) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 5}); resp.StatusCode != http.StatusConflict { + t.Fatalf("active: %d", resp.StatusCode) + } + // restricted for non-payment (no trial end) is not a trial either + if _, err := h.store.UpdateTenant(ctx, h.tenant.ID, store.TenantUpdate{Status: ptr("restricted")}); err != nil { + t.Fatal(err) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/trial", map[string]any{"days": 5}); resp.StatusCode != http.StatusConflict { + t.Fatalf("non-trial restricted: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/00000000-0000-0000-0000-00000000dead/trial", map[string]any{"days": 5}); resp.StatusCode != 404 { + t.Fatalf("unknown: %d", resp.StatusCode) + } + }) +} + +func TestAdminResendInvite(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{{UserID: "u1", Email: "it@acme.test"}} + if resp, raw := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/invites/resend", map[string]any{"email": " IT@acme.test "}); resp.StatusCode != 202 { + t.Fatalf("resend: %d %s", resp.StatusCode, raw) + } + if len(h.kcMock.Resent) != 1 || h.kcMock.Resent[0] != "it@acme.test" { + t.Fatalf("mock: %v", h.kcMock.Resent) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/invites/resend", map[string]any{"email": "nobody@acme.test"}); resp.StatusCode != 404 { + t.Fatalf("non-member: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/invites/resend", map[string]any{"email": "not an email"}); resp.StatusCode != 400 { + t.Fatalf("bad email: %d", resp.StatusCode) + } + other := newTenant(t, h, "no-org-2") + if resp, _ := h.do("POST", "/v1/admin/tenants/"+other.ID+"/invites/resend", map[string]any{"email": "a@b.test"}); resp.StatusCode != 409 { + t.Fatalf("no org: %d", resp.StatusCode) + } + }) +} diff --git a/internal/server/authz.go b/internal/server/authz.go index b62e849..67b50c5 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -67,6 +67,8 @@ func (a *Authz) Allowed(azp, group string) bool { // routeGroup classifies a request. Keep in sync with NewRouter. func routeGroup(method, path string) string { switch { + case strings.HasPrefix(path, "/v1/admin/"): + return "admin" case strings.HasPrefix(path, "/v1/internal/entitlements/"): return "entitlements" case strings.HasPrefix(path, "/v1/internal/api-keys/verify"): diff --git a/internal/server/authz_middleware_test.go b/internal/server/authz_middleware_test.go index 5471ffa..8b0e29a 100644 --- a/internal/server/authz_middleware_test.go +++ b/internal/server/authz_middleware_test.go @@ -61,3 +61,40 @@ func TestLogAuthz(t *testing.T) { t.Fatalf("rules must be logged: %s", buf.String()) } } + +func TestStaffActor_onlyFromAdminClients(t *testing.T) { + s := &Server{Authz: ParseAuthzRules("portal-svc:admin,tenants;pruefwerk-svc:tenants.read")} + req := func(client string, user bool) *http.Request { + r := httptest.NewRequest("POST", "/v1/admin/tenants/x/trial", nil) + r.Header.Set("X-Staff-Subject", "staff-1") + r.Header.Set("X-Staff-Email", "ops@breakpilot.com") + p := &authn.Principal{Subject: "svc", ClientID: client} + if user { + p.TenantID = "t1" // a user token carries tenant context + } + return r.WithContext(authn.WithPrincipal(r.Context(), p)) + } + if sub, email, ok := s.staffActor(req("portal-svc", false)); !ok || sub != "staff-1" || email != "ops@breakpilot.com" { + t.Fatalf("admin client: %v %q %q", ok, sub, email) + } + if _, _, ok := s.staffActor(req("portal-svc", true)); ok { + t.Fatal("a user token must not claim a staff actor") + } + if _, _, ok := s.staffActor(req("pruefwerk-svc", false)); ok { + t.Fatal("a non-admin client must not claim a staff actor") + } + if _, _, ok := s.staffActor(httptest.NewRequest("GET", "/", nil)); ok { + t.Fatal("no header, no principal") + } + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("X-Staff-Subject", "staff-1") + if _, _, ok := s.staffActor(r); ok { + t.Fatal("header without a principal") + } + if _, _, ok := s.staffActor(nil); ok { + t.Fatal("nil request") + } + if g := routeGroup("GET", "/v1/admin/tenants"); g != "admin" { + t.Fatalf("route group %q", g) + } +} diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 99d0be8..d293867 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -48,6 +48,11 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/tenants?limit=10"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/invites"}, + {"GET", "/v1/admin/tenants?q=acme"}, + {"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001"}, + {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"}, + {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/invites/resend"}, + {"GET", "/v1/admin/audit?limit=10"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"}, {"POST", "/v1/internal/entitlements/check"}, {"POST", "/v1/internal/erp/webhook"}, diff --git a/internal/server/server.go b/internal/server/server.go index 6ed9f80..9fdf871 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -144,6 +144,13 @@ func NewRouter(s *Server) http.Handler { // JWT subject belong to, with which org_roles and entitlements. mux.HandleFunc("GET /v1/users/{id}/memberships", s.getUserMemberships) + // Staff administration (portal /admin; group "admin"). + mux.HandleFunc("GET /v1/admin/tenants", s.adminListTenants) + mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant) + mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial) + mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite) + mux.HandleFunc("GET /v1/admin/audit", s.listAudit) + root.Handle("/", s.requireAuth(s.requireAuthz(mux))) return logRequest(s.Log)(root) } diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 198fd42..76432e4 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -479,6 +479,10 @@ func (s *Server) emitAudit(ctx context.Context, r *http.Request, ev store.AuditE if r != nil { ev.SourceIP = clientIP(r) ev.UserAgent = r.UserAgent() + // A change made from the staff admin area is attributed to the person. + if sub, email, ok := s.staffActor(r); ok { + ev.ActorID, ev.ActorName, ev.ActorType = sub, email, "staff" + } } else if ev.ActorType == "" { ev.ActorType = "system" } diff --git a/internal/store/memory.go b/internal/store/memory.go index 09ee9d9..9101020 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -3,6 +3,7 @@ package store import ( "context" "sort" + "strings" "sync" "time" @@ -214,6 +215,12 @@ func (m *Memory) ListTenants(_ context.Context, f TenantFilter) ([]Tenant, strin if f.Kind != "" && t.Kind != f.Kind { continue } + if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" && + !strings.Contains(strings.ToLower(t.Slug), q) && + !strings.Contains(strings.ToLower(t.Name), q) && + !strings.Contains(strings.ToLower(t.AdminEmail), q) { + continue + } // keyset: only rows strictly after (cAt, cID) if f.Cursor != "" && t.CreatedAt.Before(cAt) || (f.Cursor != "" && t.CreatedAt.Equal(cAt) && t.ID <= cID) { continue @@ -234,6 +241,43 @@ func (m *Memory) ListTenants(_ context.Context, f TenantFilter) ([]Tenant, strin return all, next, nil } +func (m *Memory) TenantActivity(_ context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) { + m.mu.RLock() + defer m.mu.RUnlock() + want := map[string]bool{} + for _, id := range tenantIDs { + want[id] = true + } + out := map[string]TenantActivity{} + get := func(id string) TenantActivity { + a, ok := out[id] + if !ok { + a = TenantActivity{Usage: map[string]float64{}} + } + return a + } + for _, u := range m.usage { + if !want[u.TenantID] || u.OccurredAt.Before(since) { + continue + } + a := get(u.TenantID) + a.Usage[u.Metric] += u.Quantity + out[u.TenantID] = a + } + for _, ev := range m.audit { + if !want[ev.TenantID] { + continue + } + a := get(ev.TenantID) + if a.LastActivityAt == nil || ev.CreatedAt.After(*a.LastActivityAt) { + at := ev.CreatedAt + a.LastActivityAt = &at + } + out[ev.TenantID] = a + } + return out, nil +} + // ─── products ───────────────────────────────────────────────────────────── func (m *Memory) ListProducts(_ context.Context, includeDisabled bool) ([]Product, error) { diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 7352725..fa34678 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -520,6 +520,11 @@ func (p *Postgres) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, s if f.Kind != "" { add("kind = $%d::tenant_kind", f.Kind) } + if q := strings.TrimSpace(f.Query); q != "" { + args = append(args, "%"+likeEscape(q)+"%") + n := len(args) + where = append(where, fmt.Sprintf("(slug ILIKE $%d OR name ILIKE $%d OR COALESCE(admin_email, '') ILIKE $%d)", n, n, n)) + } if f.Cursor != "" { args = append(args, cAt, cID) where = append(where, fmt.Sprintf("(created_at, id::text) > ($%d, $%d)", len(args)-1, len(args))) @@ -614,3 +619,65 @@ func (p *Postgres) ListProducts(ctx context.Context, includeDisabled bool) ([]Pr func (p *Postgres) GetProduct(ctx context.Context, key string) (*Product, error) { return scanProduct(p.pool.QueryRow(ctx, productSelect+`WHERE key = $1`, key)) } + +// likeEscape escapes the LIKE wildcards in user input (the default escape is \). +func likeEscape(s string) string { + return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s) +} + +func (p *Postgres) TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) { + out := map[string]TenantActivity{} + if len(tenantIDs) == 0 { + return out, nil + } + get := func(id string) TenantActivity { + a, ok := out[id] + if !ok { + a = TenantActivity{Usage: map[string]float64{}} + } + return a + } + rows, err := p.pool.Query(ctx, ` + SELECT tenant_id::text, metric, SUM(quantity) + FROM usage_events + WHERE tenant_id::text = ANY($1) AND occurred_at >= $2 + GROUP BY tenant_id, metric`, tenantIDs, since) + if err != nil { + return nil, err + } + for rows.Next() { + var id, metric string + var total float64 + if err := rows.Scan(&id, &metric, &total); err != nil { + rows.Close() + return nil, err + } + a := get(id) + a.Usage[metric] = total + out[id] = a + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, err + } + rows, err = p.pool.Query(ctx, ` + SELECT tenant_id::text, MAX(created_at) + FROM audit_log + WHERE tenant_id::text = ANY($1) + GROUP BY tenant_id`, tenantIDs) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var id string + var at time.Time + if err := rows.Scan(&id, &at); err != nil { + return nil, err + } + a := get(id) + a.LastActivityAt = &at + out[id] = a + } + return out, rows.Err() +} diff --git a/internal/store/store.go b/internal/store/store.go index f072495..a486b58 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -74,6 +74,9 @@ type Store interface { GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error) UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) // rows + next cursor ("" = none) + // TenantActivity returns usage totals since `since` and the latest audit + // time for each of the given tenants (tenants without either are absent). + TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) // Products (catalog) ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error) diff --git a/internal/store/types.go b/internal/store/types.go index 1e378d6..68c2a57 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -127,10 +127,20 @@ type Product struct { type TenantFilter struct { Status string Kind string + // Query matches slug, name or admin_email case-insensitively (substring). + Query string Limit int Cursor string } +// TenantActivity summarises what a tenant did since a point in time: usage +// totals per metric and the time of its latest audit entry. Staff views use it +// to list tenants without one query per tenant. +type TenantActivity struct { + Usage map[string]float64 `json:"usage"` + LastActivityAt *time.Time `json:"last_activity_at,omitempty"` +} + // Tenant status ladder (migration 0002; ERP/02). 'frozen' is legacy = restricted. const ( StatusDemo = "demo" diff --git a/openapi.yaml b/openapi.yaml index 2d9ed55..4b8e7c1 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -278,6 +278,128 @@ paths: "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } + /v1/admin/tenants: + get: + summary: Staff tenant list with search and 30-day activity. + description: | + Route group `admin` (the portal's service client). `q` matches slug, + name or admin email, case-insensitively. Each item is a Tenant plus + `activity`: usage totals per metric over the last 30 days and the time + of the latest audit entry. Changes made through the admin routes are + audited under the staff member named in `X-Staff-Subject` / + `X-Staff-Email`. + parameters: + - { in: query, name: q, schema: { type: string, maxLength: 100 } } + - { in: query, name: status, schema: { type: string } } + - { in: query, name: kind, schema: { type: string } } + - { in: query, name: cursor, schema: { type: string } } + - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 500 } } + responses: + "200": + description: One page of tenants. + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: + allOf: + - { $ref: "#/components/schemas/Tenant" } + - type: object + properties: + activity: { $ref: "#/components/schemas/TenantActivity" } + next_cursor: { type: string } + "400": { $ref: "#/components/responses/BadRequest" } + + /v1/admin/tenants/{id}: + get: + summary: Everything staff need about one tenant. + description: | + Tenant, 30-day activity, entitlements, subscriptions, licences, the + latest 25 audit entries and the Keycloak organization members (best + effort: on failure `members` is empty and `members_error` says why). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The tenant detail. + content: + application/json: + schema: + type: object + properties: + tenant: { $ref: "#/components/schemas/Tenant" } + activity: { $ref: "#/components/schemas/TenantActivity" } + entitlements: { type: array, items: { type: object } } + subscriptions: { type: array, items: { type: object } } + licences: { type: array, items: { type: object } } + members: { type: array, items: { type: object } } + members_error: { type: string } + audit: { type: array, items: { type: object } } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/admin/tenants/{id}/trial: + post: + summary: Extend a trial. + description: | + Moves the trial end `days` after the later of now and the current end, + moves trial entitlements with it, and returns a tenant that an + expired trial made read-only (and that never had a subscription) to + `trial`. Audited as `tenant.trial_extended`. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [days] + properties: + days: { type: integer, minimum: 1, maximum: 90 } + responses: + "200": + description: The updated tenant. + content: + application/json: { schema: { $ref: "#/components/schemas/Tenant" } } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + + /v1/admin/tenants/{id}/invites/resend: + post: + summary: Send a member's invitation mail again. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [email] + properties: + email: { type: string, format: email } + responses: + "202": { description: Sent. } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + + /v1/admin/audit: + get: + summary: The audit log across all tenants (same filters as /v1/audit). + parameters: + - { in: query, name: tenant_id, schema: { type: string } } + - { in: query, name: action, schema: { type: string } } + - { in: query, name: cursor, schema: { type: integer } } + - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 500 } } + responses: + "200": { description: One page of audit entries. } + "400": { $ref: "#/components/responses/BadRequest" } + /v1/entitlements: get: summary: List product entitlements for a tenant. @@ -983,6 +1105,14 @@ components: error: { type: string, example: invalid_input } message: { type: string } + TenantActivity: + type: object + properties: + usage: + type: object + additionalProperties: { type: number } + description: usage totals per metric over the last 30 days + last_activity_at: { type: string, format: date-time } Tenant: type: object required: [id, slug, name, status, kind, plan, created_at, updated_at]