Files
tenant-registry/internal/server/projects_test.go
T
sharangandClaude Opus 5.5 ad4fe8f3fd
ci / shared (push) Successful in 14s
ci / test (push) Successful in 26m6s
ci / image (push) Successful in 38s
feat(store): Unterlagen merge into the document store (#89)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:04:53 +00:00

282 lines
12 KiB
Go

package server_test
import (
"bytes"
"context"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/mail"
"git.breakpilot.com/platform/tenant-registry/internal/storage"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func createProject(t *testing.T, h *testHarness, tenantID string, body map[string]any) store.Project {
t.Helper()
resp, raw := h.do("POST", "/v1/tenants/"+tenantID+"/projects", body)
if resp.StatusCode != 201 {
t.Fatalf("create project: %d %s", resp.StatusCode, raw)
}
var p store.Project
_ = json.Unmarshal(raw, &p)
return p
}
func TestProjects_crud(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
base := "/v1/tenants/" + h.tenant.ID + "/projects"
vx := createProject(t, h, h.tenant.ID, map[string]any{"name": " Verpackungsanlage VX-200 ", "kind": "product", "description": "Linie 3"})
if vx.Name != "Verpackungsanlage VX-200" || vx.Kind != "product" || vx.Description != "Linie 3" || vx.TenantID != h.tenant.ID {
t.Fatalf("created: %+v", vx)
}
cra := createProject(t, h, h.tenant.ID, map[string]any{"name": "CRA", "kind": "TOPIC"})
// names are unique per tenant, ignoring case
if resp, raw := h.do("POST", base, map[string]any{"name": "cra", "kind": "topic"}); resp.StatusCode != 409 || !strings.Contains(string(raw), "name_taken") {
t.Fatalf("duplicate: %d %s", resp.StatusCode, raw)
}
for _, bad := range []map[string]any{{"name": "", "kind": "topic"}, {"name": "x", "kind": "machine"}, {"name": strings.Repeat("n", 121), "kind": "topic"}, {"name": "x", "kind": "topic", "description": strings.Repeat("d", 1001)}} {
if resp, raw := h.do("POST", base, bad); resp.StatusCode != 400 {
t.Fatalf("invalid %v: %d %s", bad, resp.StatusCode, raw)
}
}
// listed by name
_, raw := h.do("GET", base, nil)
var list struct{ Items []store.Project }
_ = json.Unmarshal(raw, &list)
if len(list.Items) != 2 || list.Items[0].Name != "CRA" || list.Items[1].ID != vx.ID {
t.Fatalf("list: %s", raw)
}
// patch changes only what is given; renaming onto another name conflicts
resp, raw := h.do("PATCH", base+"/"+cra.ID, map[string]any{"description": "Cyber Resilience Act"})
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"name":"CRA"`) || !strings.Contains(string(raw), "Cyber Resilience Act") {
t.Fatalf("patch: %d %s", resp.StatusCode, raw)
}
if resp, _ := h.do("PATCH", base+"/"+cra.ID, map[string]any{"name": "verpackungsanlage vx-200"}); resp.StatusCode != 409 {
t.Fatalf("rename conflict: %d", resp.StatusCode)
}
if resp, _ := h.do("PATCH", base+"/"+cra.ID, map[string]any{"kind": "machine"}); resp.StatusCode != 400 {
t.Fatalf("bad kind: %d", resp.StatusCode)
}
// another tenant's project is not reachable through this tenant
other, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "globex", Name: "Globex"})
gp := createProject(t, h, other.ID, map[string]any{"name": "CRA", "kind": "topic"})
if resp, _ := h.do("PATCH", base+"/"+gp.ID, map[string]any{"name": "x"}); resp.StatusCode != 404 {
t.Fatalf("cross-tenant patch: %d", resp.StatusCode)
}
if resp, _ := h.do("DELETE", base+"/"+gp.ID, nil); resp.StatusCode != 404 {
t.Fatalf("cross-tenant delete: %d", resp.StatusCode)
}
if resp, _ := h.do("DELETE", base+"/"+cra.ID, nil); resp.StatusCode != 204 {
t.Fatalf("delete: %d", resp.StatusCode)
}
if resp, _ := h.do("DELETE", base+"/"+cra.ID, nil); resp.StatusCode != 404 {
t.Fatalf("delete again: %d", resp.StatusCode)
}
_, raw = h.do("GET", "/v1/audit?tenant_id="+h.tenant.ID+"&limit=100", nil)
for _, a := range []string{"project.created", "project.updated", "project.deleted"} {
if !strings.Contains(string(raw), a) {
t.Fatalf("audit %s missing: %s", a, raw)
}
}
})
}
// uploadWith posts a document with extra form fields (own_document, project_ids).
func uploadWith(t *testing.T, h *testHarness, tenantID string, fields [][2]string, filename string) (*http.Response, []byte) {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
for _, f := range fields {
_ = mw.WriteField(f[0], f[1])
}
fw, _ := mw.CreateFormFile("file", filename)
_, _ = io.WriteString(fw, "%PDF-1.7")
_ = mw.Close()
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/admin/tenants/"+tenantID+"/documents", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(resp.Body)
return resp, raw
}
func TestProjects_documents(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
objs := storage.NewMemory()
h.app.Objects = objs
vx := createProject(t, h, h.tenant.ID, map[string]any{"name": "VX-200", "kind": "product"})
cra := createProject(t, h, h.tenant.ID, map[string]any{"name": "CRA", "kind": "topic"})
// upload straight into projects, repeated or comma-separated
resp, raw := uploadWith(t, h, h.tenant.ID, [][2]string{{"project_ids", vx.ID + "," + cra.ID}, {"project_ids", vx.ID}}, "dossier.pdf")
if resp.StatusCode != 201 {
t.Fatalf("upload: %d %s", resp.StatusCode, raw)
}
var d store.Document
_ = json.Unmarshal(raw, &d)
if len(d.ProjectIDs) != 2 || d.OwnDocument {
t.Fatalf("created: %+v", d)
}
// another tenant's project is refused and nothing stays behind
other, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "globex", Name: "Globex"})
gp := createProject(t, h, other.ID, map[string]any{"name": "Fremd", "kind": "topic"})
before := len(objs.Objects)
if resp, raw := uploadWith(t, h, h.tenant.ID, [][2]string{{"project_ids", gp.ID}}, "x.pdf"); resp.StatusCode != 400 {
t.Fatalf("foreign project on upload: %d %s", resp.StatusCode, raw)
}
if len(objs.Objects) != before {
t.Fatalf("object left behind")
}
_, raw = h.do("GET", "/v1/admin/tenants/"+h.tenant.ID+"/documents", nil)
if strings.Count(string(raw), `"id"`) != 1 {
t.Fatalf("row left behind: %s", raw)
}
// PATCH replaces the projects and sets own_document
resp, raw = h.do("PATCH", "/v1/admin/documents/"+d.ID, map[string]any{"project_ids": []string{cra.ID}, "own_document": true})
if resp.StatusCode != 200 {
t.Fatalf("patch: %d %s", resp.StatusCode, raw)
}
_ = json.Unmarshal(raw, &d)
if len(d.ProjectIDs) != 1 || d.ProjectIDs[0] != cra.ID || !d.OwnDocument || d.Area != store.AreaInternal {
t.Fatalf("patched: %+v", d)
}
// an own document uploaded by staff goes to the store's internal area
resp, raw = uploadWith(t, h, h.tenant.ID, [][2]string{{"own_document", "on"}, {"project_ids", vx.ID}}, "richtlinie.pdf")
var own store.Document
_ = json.Unmarshal(raw, &own)
if resp.StatusCode != 201 || own.Area != store.AreaInternal || !own.OwnDocument {
t.Fatalf("own upload: %d %s", resp.StatusCode, raw)
}
if resp, raw := h.do("PATCH", "/v1/admin/documents/"+d.ID, map[string]any{"project_ids": []string{gp.ID}}); resp.StatusCode != 400 || !strings.Contains(string(raw), "invalid_projects") {
t.Fatalf("foreign project on patch: %d %s", resp.StatusCode, raw)
}
if resp, _ := h.do("PATCH", "/v1/admin/documents/00000000-0000-0000-0000-000000000000", map[string]any{"own_document": true}); resp.StatusCode != 404 {
t.Fatalf("unknown document: %d", resp.StatusCode)
}
// deleting a project keeps the document, without the assignment
h.do("DELETE", "/v1/tenants/"+h.tenant.ID+"/projects/"+cra.ID, nil)
_, raw = h.do("GET", "/v1/admin/tenants/"+h.tenant.ID+"/documents", nil)
if !strings.Contains(string(raw), `"project_ids":[]`) || !strings.Contains(string(raw), `"own_document":true`) {
t.Fatalf("after project delete: %s", raw)
}
_, raw = h.do("GET", "/v1/audit?tenant_id="+h.tenant.ID+"&limit=100", nil)
if !strings.Contains(string(raw), "document.updated") {
t.Fatalf("audit: %s", raw)
}
})
}
// The tenant's own documents appear like any other, but publishing them
// sends no mail.
func TestProjects_ownDocumentsSendNoMail(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
h.app.Objects = storage.NewMemory()
h.app.Mail = &mail.Recorder{}
seedMembers(h, "acme")
_, raw := uploadWith(t, h, h.tenant.ID, [][2]string{{"own_document", "on"}, {"title", "Eigenes Handbuch"}}, "handbuch.pdf")
var d store.Document
_ = json.Unmarshal(raw, &d)
if !d.OwnDocument {
t.Fatalf("own flag not stored: %s", raw)
}
if resp, raw := h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil); resp.StatusCode != 200 {
t.Fatalf("publish: %d %s", resp.StatusCode, raw)
}
if n, err := h.app.DrainMail(context.Background()); err != nil || n != 0 {
t.Fatalf("mail for own document: %d %v", n, err)
}
_, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents", nil)
if !strings.Contains(string(raw), d.ID) {
t.Fatalf("own document not visible: %s", raw)
}
})
}
func TestProjects_targetsFromPruefwerk(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
p := createProject(t, h, h.tenant.ID, map[string]any{"name": "VX-200", "kind": "product"})
path := "/v1/tenants/" + h.tenant.ID + "/projects/" + p.ID + "/targets"
// no Prüfwerk configured for this environment: an empty, unavailable list
_, raw := h.do("GET", path, nil)
if !strings.Contains(string(raw), `"available":false`) || !strings.Contains(string(raw), `"items":[]`) {
t.Fatalf("unconfigured: %s", raw)
}
var gotAuth, gotURL string
pw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth, gotURL = r.Header.Get("Authorization"), r.URL.String()
if r.URL.Query().Get("project") == "boom" {
w.WriteHeader(500)
return
}
_, _ = io.WriteString(w, `{"items":[{"id":"6aba48d37507608342a05996","name":"STM32 U5","target_type":"firmware_rtos","open_findings":7,"open_vulnerabilities":3,"last_scan_at":"2026-09-28T11:07:41Z"},{"id":"x","name":"Y","target_type":"git","project_ids":["`+p.ID+`"]}]}`)
}))
defer pw.Close()
h.app.Cfg.PruefwerkPlatformURL = pw.URL + "/api/v1/platform/"
h.app.Cfg.PruefwerkURL = "https://pruefwerk-stage.breakpilot.com/"
_, raw = h.do("GET", path, nil)
var out struct {
Available bool
Items []struct {
ID, Name, URL string
OpenFindings int `json:"open_findings"`
OpenVulns int `json:"open_vulnerabilities"`
ProjectIDs []string `json:"project_ids"`
}
}
_ = json.Unmarshal(raw, &out)
if !out.Available || len(out.Items) != 2 || out.Items[0].OpenFindings != 7 ||
out.Items[0].OpenVulns != 3 || out.Items[1].OpenVulns != 0 ||
out.Items[0].URL != "https://pruefwerk-stage.breakpilot.com/targets/6aba48d37507608342a05996" ||
out.Items[0].ProjectIDs == nil || len(out.Items[1].ProjectIDs) != 1 {
t.Fatalf("targets: %s", raw)
}
if gotAuth != "Bearer mock-service-token" || gotURL != "/api/v1/platform/tenants/"+h.tenant.ID+"/targets?project="+p.ID {
t.Fatalf("request: %q %q", gotAuth, gotURL)
}
// another tenant's project answers 404 before Prüfwerk is asked
other, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "globex", Name: "Globex"})
gp := createProject(t, h, other.ID, map[string]any{"name": "Fremd", "kind": "topic"})
if resp, _ := h.do("GET", "/v1/tenants/"+h.tenant.ID+"/projects/"+gp.ID+"/targets", nil); resp.StatusCode != 404 {
t.Fatalf("foreign project: %d", resp.StatusCode)
}
})
}
// A change a workspace user makes through the portal is attributed to them.
func TestProjects_auditNamesThePortalUser(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/tenants/"+h.tenant.ID+"/projects", strings.NewReader(`{"name":"CRA","kind":"topic"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Portal-User-Email", "it@acme.de")
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 201 {
t.Fatalf("create: %v %v", err, resp)
}
_ = resp.Body.Close()
_, raw := h.do("GET", "/v1/audit?tenant_id="+h.tenant.ID+"&action=project.created", nil)
if !strings.Contains(string(raw), `"actor_name":"it@acme.de"`) || !strings.Contains(string(raw), `"actor_type":"user"`) {
t.Fatalf("audit: %s", raw)
}
})
}