feat(services): managed services per tenant for the portal (#77)
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 24m17s
ci / image (pull_request) Skipped

Managed Git (one Gitea instance per customer, INF-GIT-{CLD,OPR}-{STD,BUS,ENT})
is provisioned by hand; the registry now keeps the record so the portal can
show it under "Verwaltete Infrastruktur" and staff can maintain it.

- 0012_managed_services: table with kind/status checks, UNIQUE (tenant_id,
  kind, url), FK cascade on tenant delete (mirrored in the memory store).
- GET /v1/tenants/{id}/managed-services: tenant view without instance_id and
  notes; user tokens need IT_ADMIN, OWNER or CXO (else FORBIDDEN_ROLE).
- GET/POST /v1/admin/tenants/{id}/managed-services and PATCH/DELETE
  .../{sid}: staff view and maintenance, validation codes invalid_kind,
  invalid_name, invalid_url, invalid_sku, invalid_status,
  invalid_instance_id, invalid_notes; 409 duplicate.
- Audit managed_service.created/updated/deleted with the staff actor;
  updated carries the changed fields and old/new status.
- OpenAPI spec and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-04 21:07:59 +02:00
1 parent 6141e45811
commit 3ff7ce2e92
15 files changed
+1124 -3

No files matched your search

+2
View File
@@ -82,6 +82,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
s.listTenantProjects(w, r)
case "contracts":
s.listTenantContracts(w, r)
case "managed-services":
s.listTenantManagedServices(w, r)
default:
writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource")
}
+5
View File
@@ -72,6 +72,11 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
{"POST", "/v1/licences/heartbeat"},
{"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"},
{"GET", "/.well-known/licence-keys.json"},
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/managed-services"},
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services"},
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services"},
{"PATCH", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services/00000000-0000-0000-0000-000000000002"},
{"DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services/00000000-0000-0000-0000-000000000002"},
}
for _, c := range cases {
req := newRequest(t, c.method, c.path)
+6
View File
@@ -175,6 +175,12 @@ func NewRouter(s *Server) http.Handler {
mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument)
mux.HandleFunc("DELETE /v1/admin/documents/{doc}", s.adminDeleteDocument)
mux.HandleFunc("PATCH /v1/admin/documents/{doc}", s.adminUpdateDocument)
// Managed services (0012, portal#77); the tenant's list is a {sub} of
// tenantSubresource.
mux.HandleFunc("GET /v1/admin/tenants/{id}/managed-services", s.adminListManagedServices)
mux.HandleFunc("POST /v1/admin/tenants/{id}/managed-services", s.adminCreateManagedService)
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/managed-services/{sid}", s.adminUpdateManagedService)
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/managed-services/{sid}", s.adminDeleteManagedService)
// Notifications from products (F3; group "notify").
mux.HandleFunc("POST /v1/notifications", s.postNotification)
+300
View File
@@ -0,0 +1,300 @@
package server
import (
"context"
"errors"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// Managed services (0012, portal#77): infrastructure BreakPilot runs for a
// tenant, for now Managed Git (one Gitea instance per customer). Provisioned
// by hand (v0): staff keep the record through the admin routes (group
// "admin"; the portal decides which staff may write), and the portal shows
// the tenant's services under "Verwaltete Infrastruktur" (IT_ADMIN, OWNER
// and CXO; the portal makes CXO read-only).
var (
gitSKURE = regexp.MustCompile(`^INF-GIT-(CLD|OPR)-(STD|BUS|ENT)$`)
instanceIDRE = regexp.MustCompile(`^[a-z0-9-]*$`)
serviceReadRole = map[string]bool{authn.RoleITAdmin: true, authn.RoleOwner: true, "CXO": true}
)
// managedServiceView is the tenant's view of a service: no instance id, no
// staff notes.
type managedServiceView struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
Kind string `json:"kind"`
Name string `json:"name"`
URL string `json:"url"`
SKU string `json:"sku"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func tenantServiceView(ms store.ManagedService) managedServiceView {
return managedServiceView{
ID: ms.ID, TenantID: ms.TenantID, Kind: ms.Kind, Name: ms.Name, URL: ms.URL, SKU: ms.SKU,
Status: ms.Status, CreatedAt: ms.CreatedAt, UpdatedAt: ms.UpdatedAt,
}
}
// listTenantManagedServices is GET /v1/tenants/{id}/managed-services (a {sub}
// of tenantSubresource). Users need IT_ADMIN, OWNER or CXO; service clients
// read with tenants.read.
func (s *Server) listTenantManagedServices(w http.ResponseWriter, r *http.Request) {
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !hasAnyRole(p.OrgRoles, serviceReadRole) {
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "managed services require the IT_ADMIN, OWNER or CXO org role")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
rows, err := s.Store.ListManagedServices(ctx, t.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
items := make([]managedServiceView, len(rows))
for i, ms := range rows {
items[i] = tenantServiceView(ms)
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
type managedServiceReq struct {
Kind *string `json:"kind"`
Name *string `json:"name"`
URL *string `json:"url"`
SKU *string `json:"sku"`
Status *string `json:"status"`
InstanceID *string `json:"instance_id"`
Notes *string `json:"notes"`
}
// apply copies the given fields onto ms; kind only when withKind (it is
// fixed after creation).
func (in managedServiceReq) apply(ms *store.ManagedService, withKind bool) {
set := func(dst *string, v *string) {
if v != nil {
*dst = *v
}
}
if withKind {
set(&ms.Kind, in.Kind)
}
set(&ms.Name, in.Name)
set(&ms.URL, in.URL)
set(&ms.SKU, in.SKU)
set(&ms.Status, in.Status)
set(&ms.InstanceID, in.InstanceID)
set(&ms.Notes, in.Notes)
}
// normalizeManagedService trims the fields and checks them; the message is
// what the admin form shows.
func normalizeManagedService(ms *store.ManagedService) (code, msg string) {
ms.Kind = strings.ToLower(strings.TrimSpace(ms.Kind))
ms.Name = strings.TrimSpace(ms.Name)
ms.URL = strings.TrimSpace(ms.URL)
ms.SKU = strings.ToUpper(strings.TrimSpace(ms.SKU))
ms.Status = strings.ToLower(strings.TrimSpace(ms.Status))
ms.InstanceID = strings.TrimSpace(ms.InstanceID)
ms.Notes = strings.TrimSpace(ms.Notes)
switch {
case !store.ValidManagedServiceKind(ms.Kind):
return "invalid_kind", "kind must be git"
case ms.Name == "" || len([]rune(ms.Name)) > 100:
return "invalid_name", "name must be 1 to 100 characters"
case !validServiceURL(ms.URL):
return "invalid_url", "url must be an absolute https:// URL with a host, at most 300 characters"
case ms.Kind == store.ManagedServiceKindGit && !gitSKURE.MatchString(ms.SKU):
return "invalid_sku", "sku must be INF-GIT-CLD-* or INF-GIT-OPR-* with STD, BUS or ENT"
case !store.ValidManagedServiceStatus(ms.Status):
return "invalid_status", "status must be provisioning, active, restricted or halted"
case len(ms.InstanceID) > 100 || !instanceIDRE.MatchString(ms.InstanceID):
return "invalid_instance_id", "instance_id must be at most 100 characters of a-z, 0-9 and -"
case len([]rune(ms.Notes)) > 2000:
return "invalid_notes", "notes must be at most 2000 characters"
}
return "", ""
}
func validServiceURL(raw string) bool {
if raw == "" || len(raw) > 300 {
return false
}
u, err := url.Parse(raw)
return err == nil && u.Scheme == "https" && u.Hostname() != ""
}
// adminTenantOf loads {id} for the admin routes.
func (s *Server) adminTenantOf(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) {
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return nil, false
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return nil, false
}
return t, true
}
// adminListManagedServices is GET /v1/admin/tenants/{id}/managed-services.
func (s *Server) adminListManagedServices(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.adminTenantOf(ctx, w, r)
if !ok {
return
}
items, err := s.Store.ListManagedServices(ctx, t.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// adminCreateManagedService is POST /v1/admin/tenants/{id}/managed-services.
func (s *Server) adminCreateManagedService(w http.ResponseWriter, r *http.Request) {
var in managedServiceReq
if !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.adminTenantOf(ctx, w, r)
if !ok {
return
}
ms := store.ManagedService{TenantID: t.ID, Status: store.ManagedServiceProvisioning}
in.apply(&ms, true)
if code, msg := normalizeManagedService(&ms); code != "" {
writeError(w, http.StatusBadRequest, code, msg)
return
}
created, err := s.Store.CreateManagedService(ctx, ms)
if err != nil {
writeManagedServiceError(w, err)
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "managed_service.created", TargetID: created.ID, TargetType: "managed_service", TargetName: created.Name,
ActorType: "service", Metadata: map[string]interface{}{"kind": created.Kind, "sku": created.SKU, "url": created.URL, "status": created.Status},
})
writeJSON(w, http.StatusCreated, created)
}
// adminManagedService loads {sid} and checks it belongs to tenant {id}.
func (s *Server) adminManagedService(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, *store.ManagedService, bool) {
t, ok := s.adminTenantOf(ctx, w, r)
if !ok {
return nil, nil, false
}
ms, err := s.Store.GetManagedService(ctx, r.PathValue("sid"))
if err == nil && ms.TenantID != t.ID {
err = store.ErrNotFound
}
if err != nil {
writeManagedServiceError(w, err)
return nil, nil, false
}
return t, ms, true
}
// adminUpdateManagedService is PATCH /v1/admin/tenants/{id}/managed-services/{sid}:
// the fields given are changed (the kind is fixed).
func (s *Server) adminUpdateManagedService(w http.ResponseWriter, r *http.Request) {
var in managedServiceReq
if !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, cur, ok := s.adminManagedService(ctx, w, r)
if !ok {
return
}
next := *cur
in.apply(&next, false)
if code, msg := normalizeManagedService(&next); code != "" {
writeError(w, http.StatusBadRequest, code, msg)
return
}
// What changed, after normalization (a re-sent value is no change).
var changed []string
for _, f := range []struct {
name string
old, new string
}{
{"name", cur.Name, next.Name}, {"url", cur.URL, next.URL}, {"sku", cur.SKU, next.SKU},
{"status", cur.Status, next.Status}, {"instance_id", cur.InstanceID, next.InstanceID}, {"notes", cur.Notes, next.Notes},
} {
if f.old != f.new {
changed = append(changed, f.name)
}
}
if len(changed) == 0 {
writeJSON(w, http.StatusOK, cur)
return
}
updated, err := s.Store.UpdateManagedService(ctx, next)
if err != nil {
writeManagedServiceError(w, err)
return
}
meta := map[string]interface{}{"changed": changed}
if cur.Status != updated.Status {
meta["old_status"], meta["new_status"] = cur.Status, updated.Status
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "managed_service.updated", TargetID: updated.ID, TargetType: "managed_service", TargetName: updated.Name,
ActorType: "service", Metadata: meta,
})
writeJSON(w, http.StatusOK, updated)
}
// adminDeleteManagedService is DELETE /v1/admin/tenants/{id}/managed-services/{sid}.
// Only the record goes; the instance itself is taken down by hand (v0).
func (s *Server) adminDeleteManagedService(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ms, ok := s.adminManagedService(ctx, w, r)
if !ok {
return
}
if err := s.Store.DeleteManagedService(ctx, ms.ID); err != nil {
writeManagedServiceError(w, err)
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "managed_service.deleted", TargetID: ms.ID, TargetType: "managed_service", TargetName: ms.Name,
ActorType: "service", Metadata: map[string]interface{}{"kind": ms.Kind, "sku": ms.SKU, "url": ms.URL, "status": ms.Status},
})
w.WriteHeader(http.StatusNoContent)
}
func writeManagedServiceError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrConflict):
writeError(w, http.StatusConflict, "duplicate", "this tenant already has a service of this kind at this url")
case errors.Is(err, store.ErrInvalidInput):
writeError(w, http.StatusBadRequest, "invalid_input", "invalid managed service")
case mapStoreError(w, err):
default:
writeError(w, http.StatusInternalServerError, "internal", err.Error())
}
}
+161
View File
@@ -0,0 +1,161 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func seedService(t *testing.T, s *Server, tenantID string) *store.ManagedService {
t.Helper()
ms, err := s.Store.CreateManagedService(context.Background(), store.ManagedService{
TenantID: tenantID, Kind: "git", Name: "Git", URL: "https://git.k-00001.example", SKU: "INF-GIT-CLD-STD",
InstanceID: "gitea-k-00001", Notes: "staff only",
})
if err != nil {
t.Fatal(err)
}
return ms
}
func TestManagedServices_tenantRoles(t *testing.T) {
tenantID := "00000000-0000-0000-0000-000000000001"
cases := []struct {
name string
roles []string
want int
}{
{"it admin", []string{"IT_ADMIN"}, http.StatusOK},
{"owner", []string{"OWNER"}, http.StatusOK},
{"cxo", []string{"USER", "CXO"}, http.StatusOK},
{"cxo lower case", []string{"cxo"}, http.StatusOK},
{"plain user", []string{"USER"}, http.StatusForbidden},
{"finance", []string{"FINANCE"}, http.StatusForbidden},
{"legal", []string{"LEGAL"}, http.StatusForbidden},
{"no roles", nil, http.StatusForbidden},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: tenantID, OrgRoles: c.roles}
s, h, tenant := scopedServer(t, p)
seedService(t, s, tenant.ID)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/managed-services", nil))
if rr.Code != c.want {
t.Fatalf("status %d, want %d: %s", rr.Code, c.want, rr.Body.String())
}
body := rr.Body.String()
if c.want == http.StatusForbidden {
if !strings.Contains(body, "FORBIDDEN_ROLE") {
t.Fatalf("error code: %s", body)
}
return
}
if !strings.Contains(body, "https://git.k-00001.example") || strings.Contains(body, "instance_id") || strings.Contains(body, "staff only") {
t.Fatalf("tenant view: %s", body)
}
})
}
// Another tenant's user, even an IT_ADMIN: 404, never a hint it exists.
other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}}
s, h, tenant := scopedServer(t, other)
seedService(t, s, tenant.ID)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/managed-services", nil))
if rr.Code != http.StatusNotFound {
t.Fatalf("cross-tenant: %d %s", rr.Code, rr.Body.String())
}
}
func TestManagedServices_clients(t *testing.T) {
const rules = "portal-svc:tenants,admin;pruefwerk-svc:tenants.read"
// The portal reads the tenant view with its service token.
portal := &authn.Principal{Subject: "svc", ClientID: "portal-svc"}
s, h, tenant := scopedServer(t, portal, rules)
ms := seedService(t, s, tenant.ID)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/managed-services", nil))
if rr.Code != http.StatusOK || strings.Contains(rr.Body.String(), "instance_id") {
t.Fatalf("portal tenant read: %d %s", rr.Code, rr.Body.String())
}
// A client without the admin group may neither read nor write the admin
// routes; staff write access is decided by the portal (SUPPORT_ENGINEER
// reads only), the registry only sees the admin client.
ro := &authn.Principal{Subject: "svc2", ClientID: "pruefwerk-svc"}
_, h2, _ := scopedServer(t, ro, rules)
base := "/v1/admin/tenants/" + tenant.ID + "/managed-services"
for _, c := range []struct{ method, path, body string }{
{http.MethodGet, base, ""},
{http.MethodPost, base, `{"kind":"git","name":"x","url":"https://x.k-00001.example","sku":"INF-GIT-CLD-STD"}`},
{http.MethodPatch, base + "/" + ms.ID, `{"status":"halted"}`},
{http.MethodDelete, base + "/" + ms.ID, ""},
} {
rr := httptest.NewRecorder()
h2.ServeHTTP(rr, httptest.NewRequest(c.method, c.path, strings.NewReader(c.body)))
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "FORBIDDEN_CLIENT") {
t.Fatalf("%s %s by a non-admin client: %d %s", c.method, c.path, rr.Code, rr.Body.String())
}
}
// ...but it may read the tenant view (tenants.read).
rr = httptest.NewRecorder()
h2.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/managed-services", nil))
if rr.Code != http.StatusOK {
t.Fatalf("read client tenant view: %d %s", rr.Code, rr.Body.String())
}
}
func TestManagedServices_staffIsAuditActor(t *testing.T) {
portal := &authn.Principal{Subject: "svc", ClientID: "portal-svc"}
s, h, tenant := scopedServer(t, portal, "portal-svc:tenants,admin")
base := "/v1/admin/tenants/" + tenant.ID + "/managed-services"
send := func(method, path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.Header.Set("X-Staff-Subject", "staff-1")
r.Header.Set("X-Staff-Email", "ops@breakpilot.com")
rr := httptest.NewRecorder()
h.ServeHTTP(rr, r)
return rr
}
rr := send(http.MethodPost, base, `{"kind":"git","name":"Git","url":"https://git.k-00001.example","sku":"INF-GIT-OPR-BUS","instance_id":"gitea-k-00001"}`)
if rr.Code != http.StatusCreated || !strings.Contains(rr.Body.String(), `"instance_id":"gitea-k-00001"`) || !strings.Contains(rr.Body.String(), `"status":"provisioning"`) {
t.Fatalf("create: %d %s", rr.Code, rr.Body.String())
}
items, _ := s.Store.ListManagedServices(context.Background(), tenant.ID)
if len(items) != 1 {
t.Fatalf("stored: %+v", items)
}
id := items[0].ID
if rr := send(http.MethodPatch, base+"/"+id, `{"status":"restricted"}`); rr.Code != http.StatusOK {
t.Fatalf("patch: %d %s", rr.Code, rr.Body.String())
}
if rr := send(http.MethodDelete, base+"/"+id, ""); rr.Code != http.StatusNoContent {
t.Fatalf("delete: %d %s", rr.Code, rr.Body.String())
}
for _, action := range []string{"managed_service.created", "managed_service.updated", "managed_service.deleted"} {
evs, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: action})
if len(evs) != 1 || evs[0].ActorType != "staff" || evs[0].ActorID != "staff-1" || evs[0].ActorName != "ops@breakpilot.com" || evs[0].TargetID != id {
t.Fatalf("%s actor: %+v", action, evs)
}
if action == "managed_service.updated" && (evs[0].Metadata["old_status"] != "provisioning" || evs[0].Metadata["new_status"] != "restricted") {
t.Fatalf("status move: %+v", evs[0].Metadata)
}
}
}
func TestRouteGroup_managedServices(t *testing.T) {
if g := routeGroup(http.MethodGet, "/v1/tenants/x/managed-services"); g != "tenants.read" {
t.Errorf("tenant group %q", g)
}
for _, m := range []string{http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodDelete} {
if g := routeGroup(m, "/v1/admin/tenants/x/managed-services/y"); g != "admin" {
t.Errorf("%s admin group %q", m, g)
}
}
}
+210
View File
@@ -0,0 +1,210 @@
package server_test
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func createService(t *testing.T, h *testHarness, tenantID string, body map[string]any) store.ManagedService {
t.Helper()
resp, raw := h.do("POST", "/v1/admin/tenants/"+tenantID+"/managed-services", body)
if resp.StatusCode != 201 {
t.Fatalf("create managed service: %d %s", resp.StatusCode, raw)
}
var ms store.ManagedService
_ = json.Unmarshal(raw, &ms)
return ms
}
func TestManagedServices_crud(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
admin := "/v1/admin/tenants/" + h.tenant.ID + "/managed-services"
git := createService(t, h, h.tenant.ID, map[string]any{
"kind": "git", "name": " Git K-00001 ", "url": "https://git.k-00001.example", "sku": "INF-GIT-CLD-STD",
"instance_id": "gitea-k-00001", "notes": "provisioned by hand",
})
if git.Name != "Git K-00001" || git.Status != "provisioning" || git.TenantID != h.tenant.ID || git.InstanceID != "gitea-k-00001" || git.Notes != "provisioned by hand" || git.ID == "" {
t.Fatalf("created: %+v", git)
}
onprem := createService(t, h, h.tenant.ID, map[string]any{
"kind": "git", "name": "Git on-prem", "url": "https://git.k-00001.example/onprem", "sku": "INF-GIT-OPR-ENT", "status": "active",
})
// one row per (tenant, kind, url)
if resp, raw := h.do("POST", admin, map[string]any{"kind": "git", "name": "x", "url": "https://git.k-00001.example", "sku": "INF-GIT-CLD-BUS"}); resp.StatusCode != 409 || !strings.Contains(string(raw), `"duplicate"`) {
t.Fatalf("duplicate: %d %s", resp.StatusCode, raw)
}
// validation
valid := func() map[string]any {
return map[string]any{"kind": "git", "name": "n", "url": "https://git2.k-00001.example", "sku": "INF-GIT-CLD-STD"}
}
for _, c := range []struct {
field string
value any
code string
}{
{"kind", "svn", "invalid_kind"},
{"kind", "", "invalid_kind"},
{"name", " ", "invalid_name"},
{"name", strings.Repeat("n", 101), "invalid_name"},
{"url", "http://git2.k-00001.example", "invalid_url"},
{"url", "git2.k-00001.example", "invalid_url"},
{"url", "https://", "invalid_url"},
{"url", "https:///path", "invalid_url"},
{"url", "https://git2.k-00001.example/" + strings.Repeat("p", 300), "invalid_url"},
{"sku", "INF-GIT-CLD-XXL", "invalid_sku"},
{"sku", "PW-STD", "invalid_sku"},
{"sku", "", "invalid_sku"},
{"status", "paused", "invalid_status"},
{"instance_id", "Gitea_01", "invalid_instance_id"},
{"instance_id", strings.Repeat("a", 101), "invalid_instance_id"},
{"notes", strings.Repeat("n", 2001), "invalid_notes"},
} {
body := valid()
body[c.field] = c.value
if resp, raw := h.do("POST", admin, body); resp.StatusCode != 400 || !strings.Contains(string(raw), `"`+c.code+`"`) {
t.Fatalf("%s=%v: %d %s", c.field, c.value, resp.StatusCode, raw)
}
}
if resp, _ := h.doRaw("POST", admin, "{"); resp.StatusCode != 400 {
t.Fatalf("malformed body: %d", resp.StatusCode)
}
if resp, _ := h.do("POST", "/v1/admin/tenants/11111111-1111-1111-1111-111111111111/managed-services", valid()); resp.StatusCode != 404 {
t.Fatalf("unknown tenant: %d", resp.StatusCode)
}
// admin list: oldest first, with instance_id and notes
resp, raw := h.do("GET", admin, nil)
if resp.StatusCode != 200 {
t.Fatalf("admin list: %d %s", resp.StatusCode, raw)
}
list := decode[struct{ Items []map[string]any }](t, raw)
if len(list.Items) != 2 || list.Items[0]["id"] != git.ID || list.Items[1]["id"] != onprem.ID || list.Items[0]["instance_id"] != "gitea-k-00001" || list.Items[1]["notes"] != "" {
t.Fatalf("admin list: %s", raw)
}
// tenant list: same order, never instance_id / notes
resp, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/managed-services", nil)
if resp.StatusCode != 200 {
t.Fatalf("tenant list: %d %s", resp.StatusCode, raw)
}
tl := decode[struct{ Items []map[string]any }](t, raw)
if len(tl.Items) != 2 || tl.Items[0]["id"] != git.ID {
t.Fatalf("tenant list: %s", raw)
}
want := []string{"created_at", "id", "kind", "name", "sku", "status", "tenant_id", "updated_at", "url"}
for _, it := range tl.Items {
if len(it) != len(want) {
t.Fatalf("tenant view fields: %v", it)
}
for _, k := range want {
if _, ok := it[k]; !ok {
t.Fatalf("tenant view misses %s: %v", k, it)
}
}
}
if strings.Contains(string(raw), "instance_id") || strings.Contains(string(raw), "notes") {
t.Fatalf("tenant view leaks staff fields: %s", raw)
}
// patch changes only what is given
one := admin + "/" + git.ID
resp, raw = h.do("PATCH", one, map[string]any{"status": "active", "notes": "live since 10-01"})
if resp.StatusCode != 200 {
t.Fatalf("patch: %d %s", resp.StatusCode, raw)
}
got := decode[store.ManagedService](t, raw)
if got.Status != "active" || got.Notes != "live since 10-01" || got.Name != "Git K-00001" || got.SKU != "INF-GIT-CLD-STD" || got.InstanceID != "gitea-k-00001" {
t.Fatalf("patched: %+v", got)
}
if resp, raw := h.do("PATCH", one, map[string]any{"url": onprem.URL}); resp.StatusCode != 409 || !strings.Contains(string(raw), `"duplicate"`) {
t.Fatalf("patch onto another url: %d %s", resp.StatusCode, raw)
}
for _, bad := range []map[string]any{{"status": "gone"}, {"sku": "INF-GIT-CLD"}, {"url": "ftp://x.example"}, {"name": ""}, {"instance_id": "UPPER"}, {"notes": strings.Repeat("x", 2001)}} {
if resp, raw := h.do("PATCH", one, bad); resp.StatusCode != 400 {
t.Fatalf("patch %v: %d %s", bad, resp.StatusCode, raw)
}
}
// the kind is fixed after creation
resp, raw = h.do("PATCH", one, map[string]any{"kind": "svn", "name": "Git"})
if resp.StatusCode != 200 || decode[store.ManagedService](t, raw).Kind != "git" {
t.Fatalf("patch kind: %d %s", resp.StatusCode, raw)
}
// another tenant's service is not reachable through this tenant
other, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "k-00002", Name: "K-00002"})
foreign := createService(t, h, other.ID, map[string]any{"kind": "git", "name": "Git", "url": "https://git.k-00001.example", "sku": "INF-GIT-CLD-STD"})
if resp, _ := h.do("PATCH", admin+"/"+foreign.ID, map[string]any{"name": "x"}); resp.StatusCode != 404 {
t.Fatalf("cross-tenant patch: %d", resp.StatusCode)
}
if resp, _ := h.do("DELETE", admin+"/"+foreign.ID, nil); resp.StatusCode != 404 {
t.Fatalf("cross-tenant delete: %d", resp.StatusCode)
}
if resp, _ := h.do("PATCH", admin+"/not-a-uuid", map[string]any{"name": "x"}); resp.StatusCode != 404 {
t.Fatalf("bad sid: %d", resp.StatusCode)
}
if resp, _ := h.do("DELETE", one, nil); resp.StatusCode != 204 {
t.Fatalf("delete: %d", resp.StatusCode)
}
if resp, _ := h.do("DELETE", one, nil); resp.StatusCode != 404 {
t.Fatalf("delete again: %d", resp.StatusCode)
}
// audit: created, updated (changed fields, old → new status), deleted
_, raw = h.do("GET", "/v1/audit?tenant_id="+h.tenant.ID+"&action=managed_service.updated&limit=100", nil)
upd := decode[struct{ Items []store.AuditEvent }](t, raw)
var statusMove bool
for _, ev := range upd.Items {
if ev.Metadata["old_status"] == "provisioning" && ev.Metadata["new_status"] == "active" {
statusMove = true
if ch, _ := ev.Metadata["changed"].([]any); len(ch) != 2 {
t.Fatalf("changed fields: %v", ev.Metadata)
}
}
}
if !statusMove {
t.Fatalf("status move not audited: %s", raw)
}
_, raw = h.do("GET", "/v1/audit?tenant_id="+h.tenant.ID+"&limit=100", nil)
for _, a := range []string{"managed_service.created", "managed_service.updated", "managed_service.deleted"} {
if !strings.Contains(string(raw), a) {
t.Fatalf("audit %s missing: %s", a, raw)
}
}
if strings.Contains(string(raw), "live since") {
t.Fatalf("notes copied into the audit trail: %s", raw)
}
})
}
// Deleting a tenant removes its services (FK cascade; mirrored in Memory).
func TestManagedServices_tenantDeleteCascades(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
other, err := h.store.CreateTenant(ctx, store.TenantCreate{Slug: "k-00003", Name: "K-00003"})
if err != nil {
t.Fatal(err)
}
gone := createService(t, h, other.ID, map[string]any{"kind": "git", "name": "Git", "url": "https://git.k-00003.example", "sku": "INF-GIT-CLD-BUS"})
kept := createService(t, h, h.tenant.ID, map[string]any{"kind": "git", "name": "Git", "url": "https://git.k-00003.example", "sku": "INF-GIT-CLD-BUS"})
if err := h.store.DeleteTenant(ctx, other.ID); err != nil {
t.Fatal(err)
}
if _, err := h.store.GetManagedService(ctx, gone.ID); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("service of the deleted tenant: %v", err)
}
if items, _ := h.store.ListManagedServices(ctx, other.ID); len(items) != 0 {
t.Fatalf("list after delete: %+v", items)
}
if _, err := h.store.GetManagedService(ctx, kept.ID); err != nil {
t.Fatalf("other tenant's service: %v", err)
}
})
}