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/authz" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // Managed services (0012, portal#77): infrastructure BreakPilot runs for a // tenant: Managed Git (one Gitea instance per customer) and its build runners // (kind ci-runner, 0013; one dedicated machine each, url = the Git instance). 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)$`) ciRunnerSKURE = regexp.MustCompile(`^INF-CI-(CLD|OPR)-(STD|BUS|ENT)$`) instanceIDRE = regexp.MustCompile(`^[a-z0-9-]*$`) ) // 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 registry:services.read (IT_ADMIN, OWNER, // CXO, AUDITOR); service clients read with tenants.read. func (s *Server) listTenantManagedServices(w http.ResponseWriter, r *http.Request) { if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !authz.AnyGrants(p.OrgRoles, capServicesRead) { writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "managed services require the registry:services.read right") 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 or ci-runner" 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 ms.Kind == store.ManagedServiceKindCIRunner && !ciRunnerSKURE.MatchString(ms.SKU): return "invalid_sku", "sku must be INF-CI-CLD-* or INF-CI-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()) } }