feat(services): managed services per tenant for the portal (#77) #61
No files matched your search
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -37,6 +37,7 @@ type Memory struct {
|
||||
documents map[string]*Document
|
||||
projects map[string]*Project
|
||||
offers map[string]*TrialOffer
|
||||
services map[string]*ManagedService
|
||||
mail []*MailItem
|
||||
mailID int64
|
||||
}
|
||||
@@ -61,6 +62,7 @@ func NewMemory() *Memory {
|
||||
licences: make(map[string]*Licence),
|
||||
projects: make(map[string]*Project),
|
||||
offers: make(map[string]*TrialOffer),
|
||||
services: make(map[string]*ManagedService),
|
||||
|
||||
documents: make(map[string]*Document),
|
||||
}
|
||||
@@ -543,6 +545,11 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error {
|
||||
delete(m.projects, pid)
|
||||
}
|
||||
}
|
||||
for sid, ms := range m.services {
|
||||
if ms.TenantID == id {
|
||||
delete(m.services, sid)
|
||||
}
|
||||
}
|
||||
usage := m.usage[:0]
|
||||
for _, u := range m.usage {
|
||||
if u.TenantID != id {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// serviceTaken reports whether another service of the tenant has the same
|
||||
// kind and url (UNIQUE (tenant_id, kind, url) in 0012). Caller holds the lock.
|
||||
func (m *Memory) serviceTaken(ms ManagedService) bool {
|
||||
for _, x := range m.services {
|
||||
if x.TenantID == ms.TenantID && x.ID != ms.ID && x.Kind == ms.Kind && x.URL == ms.URL {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *Memory) ListManagedServices(_ context.Context, tenantID string) ([]ManagedService, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := []ManagedService{}
|
||||
for _, ms := range m.services {
|
||||
if ms.TenantID == tenantID {
|
||||
out = append(out, *ms)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].CreatedAt.Equal(out[j].CreatedAt) {
|
||||
return out[i].ID < out[j].ID
|
||||
}
|
||||
return out[i].CreatedAt.Before(out[j].CreatedAt)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) GetManagedService(_ context.Context, id string) (*ManagedService, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
ms, ok := m.services[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
out := *ms
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CreateManagedService(_ context.Context, ms ManagedService) (*ManagedService, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.tenants[ms.TenantID]; !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if ms.Status == "" {
|
||||
ms.Status = ManagedServiceProvisioning
|
||||
}
|
||||
if !ValidManagedServiceKind(ms.Kind) || !ValidManagedServiceStatus(ms.Status) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
ms.ID = uuid.NewString()
|
||||
if m.serviceTaken(ms) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
ms.CreatedAt, ms.UpdatedAt = now, now
|
||||
row := ms
|
||||
m.services[ms.ID] = &row
|
||||
out := row
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) UpdateManagedService(_ context.Context, ms ManagedService) (*ManagedService, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cur, ok := m.services[ms.ID]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
ms.TenantID, ms.Kind = cur.TenantID, cur.Kind
|
||||
if !ValidManagedServiceStatus(ms.Status) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if m.serviceTaken(ms) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
cur.Name, cur.URL, cur.SKU, cur.Status = ms.Name, ms.URL, ms.SKU, ms.Status
|
||||
cur.InstanceID, cur.Notes, cur.UpdatedAt = ms.InstanceID, ms.Notes, time.Now().UTC()
|
||||
out := *cur
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) DeleteManagedService(_ context.Context, id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.services[id]; !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
delete(m.services, id)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const serviceSelect = `
|
||||
SELECT id::text, tenant_id::text, kind, name, url, sku, status, instance_id, notes, created_at, updated_at
|
||||
FROM managed_services `
|
||||
|
||||
func scanManagedService(row pgx.Row) (*ManagedService, error) {
|
||||
var ms ManagedService
|
||||
if err := row.Scan(&ms.ID, &ms.TenantID, &ms.Kind, &ms.Name, &ms.URL, &ms.SKU, &ms.Status,
|
||||
&ms.InstanceID, &ms.Notes, &ms.CreatedAt, &ms.UpdatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &ms, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error) {
|
||||
rows, err := p.pool.Query(ctx, serviceSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID)
|
||||
if isInvalidUUID(err) {
|
||||
return []ManagedService{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []ManagedService{}
|
||||
for rows.Next() {
|
||||
ms, err := scanManagedService(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *ms)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (p *Postgres) GetManagedService(ctx context.Context, id string) (*ManagedService, error) {
|
||||
ms, err := scanManagedService(p.pool.QueryRow(ctx, serviceSelect+`WHERE id = $1::uuid`, id))
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return ms, err
|
||||
}
|
||||
|
||||
func (p *Postgres) CreateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error) {
|
||||
if ms.Status == "" {
|
||||
ms.Status = ManagedServiceProvisioning
|
||||
}
|
||||
var id string
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
INSERT INTO managed_services (tenant_id, kind, name, url, sku, status, instance_id, notes)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8) RETURNING id::text`,
|
||||
ms.TenantID, ms.Kind, ms.Name, ms.URL, ms.SKU, ms.Status, ms.InstanceID, ms.Notes).Scan(&id)
|
||||
switch {
|
||||
case err == nil:
|
||||
return p.GetManagedService(ctx, id)
|
||||
case isFKViolation(err), isInvalidUUID(err):
|
||||
return nil, ErrNotFound
|
||||
case isUniqueViolation(err):
|
||||
return nil, ErrConflict
|
||||
case isCheckViolation(err):
|
||||
return nil, ErrInvalidInput
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Postgres) UpdateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error) {
|
||||
tag, err := p.pool.Exec(ctx, `
|
||||
UPDATE managed_services
|
||||
SET name = $2, url = $3, sku = $4, status = $5, instance_id = $6, notes = $7, updated_at = now()
|
||||
WHERE id = $1::uuid`, ms.ID, ms.Name, ms.URL, ms.SKU, ms.Status, ms.InstanceID, ms.Notes)
|
||||
switch {
|
||||
case isInvalidUUID(err):
|
||||
return nil, ErrNotFound
|
||||
case isUniqueViolation(err):
|
||||
return nil, ErrConflict
|
||||
case isCheckViolation(err):
|
||||
return nil, ErrInvalidInput
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case tag.RowsAffected() == 0:
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return p.GetManagedService(ctx, ms.ID)
|
||||
}
|
||||
|
||||
func (p *Postgres) DeleteManagedService(ctx context.Context, id string) error {
|
||||
tag, err := p.pool.Exec(ctx, `DELETE FROM managed_services WHERE id = $1::uuid`, id)
|
||||
if isInvalidUUID(err) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+10
-1
@@ -135,7 +135,7 @@ type Store interface {
|
||||
|
||||
// DeleteTenant removes the tenant and everything that belongs to it
|
||||
// (entitlements, keys, subscriptions, usage, licences, outbox, documents,
|
||||
// mail). Audit events stay, with the tenant reference cleared.
|
||||
// projects, managed services, mail). Audit events stay, with the tenant reference cleared.
|
||||
// ErrNotFound when there is no such tenant.
|
||||
DeleteTenant(ctx context.Context, id string) error
|
||||
PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error)
|
||||
@@ -174,6 +174,15 @@ type Store interface {
|
||||
UpdateProject(ctx context.Context, p Project) (*Project, error)
|
||||
DeleteProject(ctx context.Context, id string) error
|
||||
|
||||
// Managed services (0012, portal#77), listed by created_at. One row per
|
||||
// (tenant, kind, url): ErrConflict otherwise.
|
||||
ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error)
|
||||
GetManagedService(ctx context.Context, id string) (*ManagedService, error)
|
||||
CreateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
|
||||
// UpdateManagedService writes name, url, sku, status, instance_id, notes.
|
||||
UpdateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
|
||||
DeleteManagedService(ctx context.Context, id string) error
|
||||
|
||||
// Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey
|
||||
// (false when the key existed). ClaimMail leases due unsent rows.
|
||||
EnqueueMail(ctx context.Context, m MailItem) (bool, error)
|
||||
|
||||
@@ -294,6 +294,44 @@ const (
|
||||
ProjectKindTopic = "topic"
|
||||
)
|
||||
|
||||
// ManagedService — infrastructure BreakPilot runs for a tenant (0012,
|
||||
// portal#77), for now Managed Git: one Gitea instance per customer.
|
||||
// InstanceID and Notes are staff-only; the tenant view leaves them out.
|
||||
type ManagedService struct {
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
Kind string `json:"kind"` // git
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
SKU string `json:"sku"`
|
||||
Status string `json:"status"` // provisioning | active | restricted | halted
|
||||
InstanceID string `json:"instance_id"`
|
||||
Notes string `json:"notes"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
const (
|
||||
ManagedServiceKindGit = "git"
|
||||
|
||||
ManagedServiceProvisioning = "provisioning"
|
||||
ManagedServiceActive = "active"
|
||||
ManagedServiceRestricted = "restricted"
|
||||
ManagedServiceHalted = "halted"
|
||||
)
|
||||
|
||||
// ValidManagedServiceKind and ValidManagedServiceStatus mirror the CHECK
|
||||
// constraints of 0012.
|
||||
func ValidManagedServiceKind(k string) bool { return k == ManagedServiceKindGit }
|
||||
|
||||
func ValidManagedServiceStatus(s string) bool {
|
||||
switch s {
|
||||
case ManagedServiceProvisioning, ManagedServiceActive, ManagedServiceRestricted, ManagedServiceHalted:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MailItem — one platform email to one recipient (migration 0009).
|
||||
type MailItem struct {
|
||||
ID int64 `json:"id"`
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS managed_services;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Managed services (portal#77): infrastructure BreakPilot runs for a tenant,
|
||||
-- for now Managed Git (one Gitea instance per customer, SKUs
|
||||
-- INF-GIT-{CLD,OPR}-{STD,BUS,ENT}). Provisioned by hand (v0); staff keep the
|
||||
-- record in the admin area and the portal shows it under "Verwaltete
|
||||
-- Infrastruktur". instance_id and notes are staff-only.
|
||||
CREATE TABLE managed_services (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('git')),
|
||||
name TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
sku TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'provisioning'
|
||||
CHECK (status IN ('provisioning', 'active', 'restricted', 'halted')),
|
||||
instance_id TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (tenant_id, kind, url)
|
||||
);
|
||||
CREATE INDEX managed_services_tenant ON managed_services (tenant_id);
|
||||
@@ -100,6 +100,7 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
|
||||
"api_keys",
|
||||
"audit_log",
|
||||
"products",
|
||||
"managed_services",
|
||||
}
|
||||
for _, table := range wantTables {
|
||||
var exists bool
|
||||
@@ -115,8 +116,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}} {
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}} {
|
||||
var exists bool
|
||||
err := db.QueryRow(
|
||||
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
|
||||
@@ -274,10 +275,30 @@ func TestSeed_canInsertAndQuery(t *testing.T) {
|
||||
t.Errorf("tenant readback: slug=%q status=%q", slug, status)
|
||||
}
|
||||
|
||||
// 0012: one row per (tenant, kind, url); kind and status are checked.
|
||||
insMS := `INSERT INTO managed_services (tenant_id, kind, name, url, sku, status) VALUES ($1, $2, 'Git', $3, 'INF-GIT-CLD-STD', $4)`
|
||||
if _, err := db.ExecContext(ctx, insMS, tid, "git", "https://git.k-00001.example", "active"); err != nil {
|
||||
t.Fatalf("insert managed service: %v", err)
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, insMS, tid, "git", "https://git.k-00001.example", "active"); err == nil {
|
||||
t.Error("duplicate (tenant, kind, url) was stored")
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, insMS, tid, "svn", "https://svn.k-00001.example", "active"); err == nil {
|
||||
t.Error("unknown kind was stored")
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, insMS, tid, "git", "https://git2.k-00001.example", "paused"); err == nil {
|
||||
t.Error("unknown status was stored")
|
||||
}
|
||||
|
||||
// FK cascade — delete tenant, projects/products/keys/audit_log handling.
|
||||
if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil {
|
||||
t.Fatalf("delete tenant: %v", err)
|
||||
}
|
||||
var nServices int
|
||||
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices)
|
||||
if nServices != 0 {
|
||||
t.Errorf("FK cascade incomplete: managed_services=%d", nServices)
|
||||
}
|
||||
var nProjects, nProducts, nKeys int
|
||||
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_projects WHERE tenant_id = $1`, tid).Scan(&nProjects)
|
||||
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_products WHERE tenant_id = $1`, tid).Scan(&nProducts)
|
||||
|
||||
+128
@@ -316,6 +316,25 @@ paths:
|
||||
url: { type: string, description: The object in the Prüfwerk dashboard. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/managed-services:
|
||||
get:
|
||||
summary: A tenant's managed services (Verwaltete Infrastruktur), oldest first.
|
||||
description: |
|
||||
Served by the `{id}/{sub}` route; user tokens reach their own tenant
|
||||
only and need the org role IT_ADMIN, OWNER or CXO (else 403
|
||||
FORBIDDEN_ROLE). Service clients read with tenants.read. Never
|
||||
carries instance_id or notes.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The services, by created_at.
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: object, required: [items], properties: { items: { type: array, items: { $ref: "#/components/schemas/ManagedService" } } } }
|
||||
"403": { description: The user's org role may not see managed services (FORBIDDEN_ROLE). }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/members:
|
||||
get:
|
||||
summary: List the tenant's Keycloak organization members.
|
||||
@@ -638,6 +657,71 @@ paths:
|
||||
"204": { description: Deleted. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/admin/tenants/{id}/managed-services:
|
||||
get:
|
||||
summary: A tenant's managed services with instance id and notes (staff).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The services, by created_at.
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: object, required: [items], properties: { items: { type: array, items: { $ref: "#/components/schemas/ManagedServiceAdmin" } } } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
post:
|
||||
summary: Record a managed service of the tenant (staff).
|
||||
description: |
|
||||
Error codes (400): invalid_kind, invalid_name, invalid_url,
|
||||
invalid_sku, invalid_status, invalid_instance_id, invalid_notes.
|
||||
The staff member (X-Staff-Subject / X-Staff-Email) is the audit
|
||||
actor of managed_service.created.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ManagedServiceCreate" } }
|
||||
responses:
|
||||
"201":
|
||||
description: Created.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ManagedServiceAdmin" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: The tenant has a service of this kind at this url (duplicate). }
|
||||
|
||||
/v1/admin/tenants/{id}/managed-services/{sid}:
|
||||
patch:
|
||||
summary: Change a managed service (staff); the fields given are changed.
|
||||
description: |
|
||||
The kind is fixed. Same validation as create. Audited as
|
||||
managed_service.updated with the changed fields and, when the
|
||||
status moves, old_status and new_status.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: sid, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ManagedServiceUpdate" } }
|
||||
responses:
|
||||
"200":
|
||||
description: The service.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ManagedServiceAdmin" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: The tenant has a service of this kind at this url (duplicate). }
|
||||
delete:
|
||||
summary: Delete the record of a managed service (staff).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: sid, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"204": { description: Deleted. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/documents/{doc}/download:
|
||||
get:
|
||||
summary: A five-minute download link for a published document.
|
||||
@@ -1440,6 +1524,50 @@ components:
|
||||
name: { type: string, minLength: 1, maxLength: 120 }
|
||||
kind: { type: string, enum: [product, topic], description: "product: one of the customer's products or machines; topic: e.g. CRA, Data Act" }
|
||||
description: { type: string, maxLength: 1000 }
|
||||
ManagedService:
|
||||
type: object
|
||||
required: [id, tenant_id, kind, name, url, sku, status, created_at, updated_at]
|
||||
properties:
|
||||
id: { type: string, format: uuid }
|
||||
tenant_id: { type: string, format: uuid }
|
||||
kind: { type: string, enum: [git] }
|
||||
name: { type: string }
|
||||
url: { type: string, description: "https:// URL of the instance" }
|
||||
sku: { type: string, example: INF-GIT-CLD-STD }
|
||||
status: { $ref: "#/components/schemas/ManagedServiceStatus" }
|
||||
created_at: { type: string, format: date-time }
|
||||
updated_at: { type: string, format: date-time }
|
||||
ManagedServiceAdmin:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ManagedService"
|
||||
- type: object
|
||||
required: [instance_id, notes]
|
||||
properties:
|
||||
instance_id: { type: string }
|
||||
notes: { type: string }
|
||||
ManagedServiceStatus:
|
||||
type: string
|
||||
enum: [provisioning, active, restricted, halted]
|
||||
ManagedServiceCreate:
|
||||
type: object
|
||||
required: [kind, name, url, sku]
|
||||
properties:
|
||||
kind: { type: string, enum: [git] }
|
||||
name: { type: string, minLength: 1, maxLength: 100 }
|
||||
url: { type: string, maxLength: 300, description: "absolute https:// URL with a host" }
|
||||
sku: { type: string, pattern: "^INF-GIT-(CLD|OPR)-(STD|BUS|ENT)$" }
|
||||
status: { $ref: "#/components/schemas/ManagedServiceStatus" }
|
||||
instance_id: { type: string, maxLength: 100, pattern: "^[a-z0-9-]*$" }
|
||||
notes: { type: string, maxLength: 2000 }
|
||||
ManagedServiceUpdate:
|
||||
type: object
|
||||
properties:
|
||||
name: { type: string, minLength: 1, maxLength: 100 }
|
||||
url: { type: string, maxLength: 300 }
|
||||
sku: { type: string, pattern: "^INF-GIT-(CLD|OPR)-(STD|BUS|ENT)$" }
|
||||
status: { $ref: "#/components/schemas/ManagedServiceStatus" }
|
||||
instance_id: { type: string, maxLength: 100, pattern: "^[a-z0-9-]*$" }
|
||||
notes: { type: string, maxLength: 2000 }
|
||||
TenantActivity:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
Reference in new issue
Block a user