Files
tenant-registry/internal/server/projects.go
Sharang ParnerkarandClaude Opus 5.5 c4b7686cc5
ci / shared (pull_request) Successful in 14s
ci / test (pull_request) Successful in 25m43s
ci / image (pull_request) Skipped
feat(projects): product hierarchy - family, product, component
A product project gets a level (family | product | component) and a
parent (migration 0020), so a machine with its robot arm, PLC, edge
server and Windows app, or a product family, can be modelled. Topics stay
flat; kind is unchanged and old clients get level "product" at the top.
The API checks the tree: allowed parents per level, same tenant, no
cycles, at most 4 levels, children still fitting after a level change.
The database keeps parents within the tenant and refuses to delete a
project with children (409 has_children). The list stays flat with
level and parent_id. A document's role follows the level of the project
it is linked to; no document schema change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:10:15 +02:00

440 lines
15 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// Projekte (0010): a tenant groups its documents and product objects by what
// they are about, one of the customer's products (kind "product") or a topic
// such as the CRA (kind "topic"). The portal writes on behalf of tenant
// admins (it checks their org role) and of staff (X-Staff-* headers); products
// read the list with their service token (tenants.read).
const headerPortalUserEmail = "X-Portal-User-Email"
type projectReq struct {
Name *string `json:"name"`
Kind *string `json:"kind"`
Description *string `json:"description"`
// Level and ParentID (0020): where a product sits in the hierarchy.
// An empty parent_id detaches the project.
Level *string `json:"level"`
ParentID *string `json:"parent_id"`
}
// apply copies the request's fields onto p.
func (in projectReq) apply(p *store.Project) {
if in.Name != nil {
p.Name = *in.Name
}
if in.Kind != nil {
p.Kind = *in.Kind
}
if in.Description != nil {
p.Description = *in.Description
}
if in.Level != nil {
p.Level = *in.Level
}
if in.ParentID != nil {
p.ParentID = *in.ParentID
}
}
// projectActor names who changed a project for the audit trail and
// created_by: the staff member, else the portal user, else the service.
func (s *Server) projectActor(r *http.Request) string {
if sub, email, ok := s.staffActor(r); ok {
return firstNonEmpty(email, sub)
}
return strings.TrimSpace(r.Header.Get(headerPortalUserEmail))
}
// projectActorType is "staff" for BreakPilot staff, "user" when the portal
// names a workspace user, "service" otherwise.
func (s *Server) projectActorType(r *http.Request) string {
if _, _, ok := s.staffActor(r); ok {
return "staff"
}
if strings.TrimSpace(r.Header.Get(headerPortalUserEmail)) != "" {
return "user"
}
return "service"
}
// listTenantProjects is GET /v1/tenants/{id}/projects.
func (s *Server) listTenantProjects(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
items, err := s.Store.ListProjects(ctx, t.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// normalizeProject trims the fields and checks them; the message is what the
// portal shows next to the form.
func normalizeProject(p *store.Project) (code, msg string) {
p.Name = strings.Join(strings.Fields(p.Name), " ")
p.Kind = strings.ToLower(strings.TrimSpace(p.Kind))
p.Description = strings.TrimSpace(p.Description)
p.Level = strings.ToLower(strings.TrimSpace(p.Level))
p.ParentID = strings.TrimSpace(p.ParentID)
if p.Kind == store.ProjectKindProduct && p.Level == "" {
p.Level = store.ProjectLevelProduct // clients without the hierarchy
}
switch {
case p.Name == "" || len([]rune(p.Name)) > 120:
return "invalid_name", "name must be 1 to 120 characters"
case p.Kind != store.ProjectKindProduct && p.Kind != store.ProjectKindTopic:
return "invalid_kind", "kind must be product or topic"
case len([]rune(p.Description)) > 1000:
return "invalid_description", "description must be at most 1000 characters"
case p.Kind == store.ProjectKindTopic && (p.Level != "" || p.ParentID != ""):
return "invalid_level", "a topic has no level and no parent"
case p.Kind == store.ProjectKindProduct && p.Level != store.ProjectLevelFamily && p.Level != store.ProjectLevelProduct && p.Level != store.ProjectLevelComponent:
return "invalid_level", "level must be family, product or component"
}
return "", ""
}
// maxProjectDepth: family -> product -> component -> component.
const maxProjectDepth = 4
// allowedParent: which level a parent may have for each level ("" = none).
var allowedParent = map[string][]string{
store.ProjectLevelFamily: {""},
store.ProjectLevelProduct: {"", store.ProjectLevelFamily},
store.ProjectLevelComponent: {store.ProjectLevelProduct, store.ProjectLevelComponent},
}
// checkHierarchy checks p's place in the tenant's tree (all = the tenant's
// projects as stored, p possibly among them with its old values): the parent
// exists and fits p's level, there is no cycle, the tree stays within
// maxProjectDepth, and p's children still fit when p's level changes.
func checkHierarchy(p store.Project, all []store.Project) (code, msg string) {
byID := map[string]store.Project{}
for _, x := range all {
byID[x.ID] = x
}
byID[p.ID] = p
if p.Kind != store.ProjectKindProduct {
for _, x := range all {
if x.ParentID == p.ID && p.ID != "" {
return "has_children", "a project with components or products below it must stay a product"
}
}
return "", ""
}
parentLevel := ""
if p.ParentID != "" {
parent, ok := byID[p.ParentID]
if !ok || parent.ID == p.ID {
return "invalid_parent", "the parent is not a product of this workspace"
}
if parent.Kind != store.ProjectKindProduct {
return "invalid_parent", "a topic cannot be a parent"
}
parentLevel = parent.Level
}
if !slices.Contains(allowedParent[p.Level], parentLevel) {
return "invalid_parent", fmt.Sprintf("a %s cannot sit below %s", p.Level, orNone(parentLevel))
}
// Walk up: no cycle, and count the depth above p.
depth, seen := 1, map[string]bool{p.ID: true}
for cur := p.ParentID; cur != ""; cur = byID[cur].ParentID {
if seen[cur] {
return "invalid_parent", "the parent is below this project"
}
seen[cur] = true
depth++
}
// Children keep fitting, and the deepest branch below stays in bounds.
var below func(id string) int
below = func(id string) int {
d := 0
for _, x := range all {
if x.ParentID == id && x.ID != id {
d = max(d, 1+below(x.ID))
}
}
return d
}
if p.ID != "" {
for _, x := range all {
if x.ParentID == p.ID && !slices.Contains(allowedParent[x.Level], p.Level) {
return "invalid_level", fmt.Sprintf("%q (a %s) cannot sit below a %s", x.Name, x.Level, p.Level)
}
}
depth += below(p.ID)
}
if depth > maxProjectDepth {
return "too_deep", fmt.Sprintf("the hierarchy is at most %d levels deep", maxProjectDepth)
}
return "", ""
}
func orNone(level string) string {
if level == "" {
return "nothing"
}
return "a " + level
}
// placeProject checks p against the tenant's other projects and writes the
// error when it does not fit.
func (s *Server) placeProject(ctx context.Context, w http.ResponseWriter, p store.Project) bool {
all, err := s.Store.ListProjects(ctx, p.TenantID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return false
}
if code, msg := checkHierarchy(p, all); code != "" {
status := http.StatusBadRequest
if code == "has_children" {
status = http.StatusConflict
}
writeError(w, status, code, msg)
return false
}
return true
}
// createTenantProject is POST /v1/tenants/{id}/projects.
func (s *Server) createTenantProject(w http.ResponseWriter, r *http.Request) {
var in projectReq
if !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
p := store.Project{TenantID: t.ID, CreatedBy: s.projectActor(r)}
in.apply(&p)
if code, msg := normalizeProject(&p); code != "" {
writeError(w, http.StatusBadRequest, code, msg)
return
}
if !s.placeProject(ctx, w, p) {
return
}
created, err := s.Store.CreateProject(ctx, p)
if err != nil {
s.writeProjectError(w, err)
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "project.created", TargetID: created.ID, TargetType: "project", TargetName: created.Name,
ActorType: s.projectActorType(r), ActorName: p.CreatedBy, Metadata: map[string]interface{}{"kind": created.Kind, "level": created.Level, "parent_id": created.ParentID},
})
writeJSON(w, http.StatusCreated, created)
}
// tenantProject loads {pid} and checks it belongs to the tenant in scope.
func (s *Server) tenantProject(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, *store.Project, bool) {
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return nil, nil, false
}
p, err := s.Store.GetProject(ctx, r.PathValue("pid"))
if err == nil && p.TenantID != t.ID {
err = store.ErrNotFound
}
if err != nil {
if mapStoreError(w, err) {
return nil, nil, false
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return nil, nil, false
}
return t, p, true
}
// updateTenantProject is PATCH /v1/tenants/{id}/projects/{pid}.
func (s *Server) updateTenantProject(w http.ResponseWriter, r *http.Request) {
var in projectReq
if !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, p, ok := s.tenantProject(ctx, w, r)
if !ok {
return
}
if in.Kind != nil && strings.EqualFold(strings.TrimSpace(*in.Kind), store.ProjectKindTopic) {
p.Level, p.ParentID = "", "" // a topic leaves the hierarchy
}
in.apply(p)
if code, msg := normalizeProject(p); code != "" {
writeError(w, http.StatusBadRequest, code, msg)
return
}
if !s.placeProject(ctx, w, *p) {
return
}
updated, err := s.Store.UpdateProject(ctx, *p)
if err != nil {
s.writeProjectError(w, err)
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "project.updated", TargetID: updated.ID, TargetType: "project", TargetName: updated.Name,
ActorType: s.projectActorType(r), ActorName: s.projectActor(r), Metadata: map[string]interface{}{"level": updated.Level, "parent_id": updated.ParentID},
})
writeJSON(w, http.StatusOK, updated)
}
// deleteTenantProject is DELETE /v1/tenants/{id}/projects/{pid}. Documents
// keep existing; they only lose the assignment. Products drop unknown ids on
// read.
func (s *Server) deleteTenantProject(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, p, ok := s.tenantProject(ctx, w, r)
if !ok {
return
}
if err := s.Store.DeleteProject(ctx, p.ID); err != nil {
s.writeProjectError(w, err)
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "project.deleted", TargetID: p.ID, TargetType: "project", TargetName: p.Name,
ActorType: s.projectActorType(r), ActorName: s.projectActor(r),
})
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) writeProjectError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrConflict):
writeError(w, http.StatusConflict, "name_taken", "a project with this name exists")
case errors.Is(err, store.ErrHasChildren):
writeError(w, http.StatusConflict, "has_children", "move or delete the products and components below it first")
case errors.Is(err, store.ErrInvalidInput):
writeError(w, http.StatusBadRequest, "invalid_input", "invalid project")
case mapStoreError(w, err):
default:
writeError(w, http.StatusInternalServerError, "internal", err.Error())
}
}
// projectTarget is one Prüfwerk object (target) of a project, as the portal
// lists it. URL opens it in the product.
type projectTarget struct {
ID string `json:"id"`
Name string `json:"name"`
TargetType string `json:"target_type"`
LastScanAt *time.Time `json:"last_scan_at,omitempty"`
OpenFindings int `json:"open_findings"`
// OpenVulnerabilities counts the known vulnerabilities in its
// components that still need a decision (Prüfwerk's open CVE alerts).
OpenVulnerabilities int `json:"open_vulnerabilities"`
ProjectIDs []string `json:"project_ids"`
URL string `json:"url,omitempty"`
}
// listProjectTargets is GET /v1/tenants/{id}/projects/{pid}/targets: the
// project's Prüfwerk objects, read from Prüfwerk's platform API with the
// registry's service token. When Prüfwerk cannot answer, the list is empty
// and "available" false, so the portal can say so instead of failing.
func (s *Server) listProjectTargets(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
defer cancel()
t, p, ok := s.tenantProject(ctx, w, r)
if !ok {
return
}
items, err := s.fetchPruefwerkTargets(ctx, t.ID, p.ID)
if err != nil {
s.Log.Warn("project targets unavailable", "tenant_id", t.ID, "project_id", p.ID, "err", err)
writeJSON(w, http.StatusOK, map[string]any{"items": []projectTarget{}, "available": false})
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": items, "available": true})
}
// pruefwerkBase is Prüfwerk's platform API root and dashboard URL for this
// environment, derived from the catalog (provision URL …/tenants/{id}/provision,
// launch URL).
func (s *Server) pruefwerkBase(ctx context.Context) (platform, launch string, err error) {
if s.Cfg != nil && s.Cfg.PruefwerkPlatformURL != "" {
return strings.TrimRight(s.Cfg.PruefwerkPlatformURL, "/"), strings.TrimRight(s.Cfg.PruefwerkURL, "/"), nil
}
p, err := s.Store.GetProduct(ctx, "pruefwerk")
if err != nil {
return "", "", err
}
prov := p.ProvisionURLs[s.env()]
const suffix = "/tenants/{id}/provision"
if !strings.HasSuffix(prov, suffix) {
return "", "", fmt.Errorf("pruefwerk: no provision URL for %q", s.env())
}
return strings.TrimSuffix(prov, suffix), strings.TrimRight(p.LaunchURLs[s.env()], "/"), nil
}
func (s *Server) fetchPruefwerkTargets(ctx context.Context, tenantID, projectID string) ([]projectTarget, error) {
base, launch, err := s.pruefwerkBase(ctx)
if err != nil {
return nil, err
}
u := base + "/tenants/" + url.PathEscape(tenantID) + "/targets?project=" + url.QueryEscape(projectID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
if tok, terr := s.Keycloak.ServiceToken(ctx); terr != nil {
return nil, terr
} else if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
return nil, fmt.Errorf("pruefwerk: %d %s", resp.StatusCode, b)
}
var body struct {
Items []projectTarget `json:"items"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 4<<20)).Decode(&body); err != nil {
return nil, fmt.Errorf("pruefwerk: %w", err)
}
out := make([]projectTarget, 0, len(body.Items))
for _, it := range body.Items {
if it.ProjectIDs == nil {
it.ProjectIDs = []string{}
}
if launch != "" && it.ID != "" {
it.URL = launch + "/targets/" + url.PathEscape(it.ID)
}
out = append(out, it)
}
return out, nil
}