Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
295 lines
9.5 KiB
Go
295 lines
9.5 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"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"`
|
|
}
|
|
|
|
// 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))
|
|
}
|
|
|
|
// 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)
|
|
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"
|
|
}
|
|
return "", ""
|
|
}
|
|
|
|
// 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)}
|
|
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 code, msg := normalizeProject(&p); code != "" {
|
|
writeError(w, http.StatusBadRequest, code, msg)
|
|
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: "service", Metadata: map[string]interface{}{"kind": created.Kind, "by": p.CreatedBy},
|
|
})
|
|
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.Name != nil {
|
|
p.Name = *in.Name
|
|
}
|
|
if in.Kind != nil {
|
|
p.Kind = *in.Kind
|
|
}
|
|
if in.Description != nil {
|
|
p.Description = *in.Description
|
|
}
|
|
if code, msg := normalizeProject(p); code != "" {
|
|
writeError(w, http.StatusBadRequest, code, msg)
|
|
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: "service", Metadata: map[string]interface{}{"by": s.projectActor(r)},
|
|
})
|
|
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: "service", Metadata: map[string]interface{}{"by": 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.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"`
|
|
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
|
|
}
|