package server import ( "archive/tar" "bytes" "compress/gzip" "context" "crypto/sha256" "encoding/hex" "encoding/json" "mime/multipart" "net/http" "net/http/httptest" "strings" "testing" "git.breakpilot.com/platform/tenant-registry/internal/authn" "git.breakpilot.com/platform/tenant-registry/internal/config" "git.breakpilot.com/platform/tenant-registry/internal/storage" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // All data here is synthetic: "Muster Modellbau GmbH", product "Lok 100". type storeFixture struct { *teamFixture objects *storage.Memory } func newStoreFixture(t *testing.T, p *authn.Principal, rules ...string) *storeFixture { t.Helper() f := newTeamFixture(t, p, rules...) objs := storage.NewMemory() f.s.Objects = objs return &storeFixture{teamFixture: f, objects: objs} } // raw sends body with the given content type and headers. func (f *storeFixture) raw(t *testing.T, method, path, ctype string, body []byte, hdr map[string]string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(method, path, bytes.NewReader(body)) if ctype != "" { req.Header.Set("Content-Type", ctype) } for k, v := range hdr { req.Header.Set(k, v) } rr := httptest.NewRecorder() f.h.ServeHTTP(rr, req) return rr } func (f *storeFixture) upload(t *testing.T, fields map[string]string, filename string, content []byte) *httptest.ResponseRecorder { t.Helper() var buf bytes.Buffer mw := multipart.NewWriter(&buf) for _, k := range []string{"area", "legal_kind", "product_id", "title", "process"} { if v, ok := fields[k]; ok { _ = mw.WriteField(k, v) } } fw, _ := mw.CreateFormFile("file", filename) _, _ = fw.Write(content) _ = mw.Close() return f.raw(t, "POST", "/v1/tenants/"+f.tenant.ID+"/store/documents", mw.FormDataContentType(), buf.Bytes(), map[string]string{"X-Portal-User-Email": "cxo@muster.test"}) } func hexsum(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } func TestStoreUploadRules(t *testing.T) { f := newStoreFixture(t, portal, "portal-svc:*") pdf := []byte("%PDF-1.7 synthetic impressum") ctx := context.Background() product, _ := f.s.Store.CreateProject(ctx, store.Project{TenantID: f.tenant.ID, Name: "Lok 100", Kind: store.ProjectKindProduct, Level: store.ProjectLevelProduct}) topic, _ := f.s.Store.CreateProject(ctx, store.Project{TenantID: f.tenant.ID, Name: "CRA", Kind: store.ProjectKindTopic}) for name, c := range map[string]struct { fields map[string]string file string code int err string }{ "unknown area": {map[string]string{"area": "secret"}, "a.pdf", 400, "invalid_area"}, "legal without folder": {map[string]string{"area": "legal_web"}, "a.pdf", 400, "invalid_legal_kind"}, "legal unknown folder": {map[string]string{"area": "legal_web", "legal_kind": "faq"}, "a.pdf", 400, "invalid_legal_kind"}, "folder outside legal": {map[string]string{"area": "product_public", "legal_kind": "agb"}, "a.pdf", 400, "invalid_legal_kind"}, "product on public doc": {map[string]string{"area": "product_public", "product_id": product.ID}, "a.pdf", 400, "invalid_product"}, "topic as product": {map[string]string{"area": "internal", "product_id": topic.ID}, "a.pdf", 400, "invalid_product"}, "unsupported type": {map[string]string{"area": "internal"}, "a.exe", 415, "unsupported_type"}, "title too long": {map[string]string{"area": "internal", "title": strings.Repeat("t", 201)}, "a.pdf", 400, "invalid_title"}, } { rr := f.upload(t, c.fields, c.file, pdf) if rr.Code != c.code || !strings.Contains(rr.Body.String(), c.err) { t.Errorf("%s: %d %s", name, rr.Code, rr.Body.String()) } } if len(f.objects.Objects) != 0 { t.Fatalf("refused uploads stored %d objects", len(f.objects.Objects)) } legal := f.upload(t, map[string]string{"area": "legal_web", "legal_kind": "impressum"}, "Impressum.pdf", pdf) internalPlain := f.upload(t, map[string]string{"area": "internal", "title": " Risikobeurteilung Lok 100 ", "product_id": product.ID}, "rb.docx", []byte("PK synthetic")) internalSent := f.upload(t, map[string]string{"area": "internal", "process": "on"}, "Richtlinie.pdf", pdf) public := f.upload(t, map[string]string{"area": "product_public"}, "Datenblatt.pdf", pdf) var d1, d2, d3, d4 store.Document for i, rr := range []*httptest.ResponseRecorder{legal, internalPlain, internalSent, public} { if rr.Code != 201 { t.Fatalf("upload %d: %d %s", i, rr.Code, rr.Body.String()) } } _ = json.Unmarshal(legal.Body.Bytes(), &d1) _ = json.Unmarshal(internalPlain.Body.Bytes(), &d2) _ = json.Unmarshal(internalSent.Body.Bytes(), &d3) _ = json.Unmarshal(public.Body.Bytes(), &d4) if d1.Area != "legal_web" || d1.LegalKind != "impressum" || d1.ProcessingStatus != "pending" || d1.Status != "published" || d1.SHA256 != hexsum(pdf) || d1.Title != "Impressum" { t.Errorf("legal: %+v", d1) } if d2.ProcessingStatus != "none" || d2.Title != "Risikobeurteilung Lok 100" || len(d2.ProjectIDs) != 1 || d2.ProjectIDs[0] != product.ID { t.Errorf("internal without processing: %+v", d2) } if d3.ProcessingStatus != "pending" || d4.ProcessingStatus != "pending" { t.Errorf("processing: internal sent %q, public %q", d3.ProcessingStatus, d4.ProcessingStatus) } // The store lists them by area and folder; the tenant's document list (Werkmeister's) has them too. code, _, raw := f.call(t, "GET", "/v1/tenants/"+f.tenant.ID+"/store", "", nil) var list storeListResp _ = json.Unmarshal([]byte(raw), &list) if code != 200 || len(list.Items) != 4 || list.Items[0].Area != "legal_web" || list.Items[1].Area != "product_public" || len(list.LegalKinds) != 8 { t.Fatalf("store list: %d %s", code, raw) } docs, _ := f.s.Store.ListDocuments(ctx, f.tenant.ID, false) if len(docs) != 4 { t.Errorf("tenant documents: %d", len(docs)) } if ev := f.audit(t, "store.uploaded"); len(ev) != 4 || ev[0].Metadata["area"] == nil { t.Errorf("audit: %+v", ev) } } func TestStoreServesOnlyVerifiedBytes(t *testing.T) { f := newStoreFixture(t, portal, "portal-svc:*") pdf := []byte("%PDF-1.7 synthetic datenblatt") rr := f.upload(t, map[string]string{"area": "product_public"}, "Datenblatt Lok 100.pdf", pdf) var d store.Document _ = json.Unmarshal(rr.Body.Bytes(), &d) path := "/v1/tenants/" + f.tenant.ID + "/store/documents/" + d.ID got := f.raw(t, "GET", path+"/original", "", nil, nil) if got.Code != 200 || !bytes.Equal(got.Body.Bytes(), pdf) || got.Header().Get("Content-Type") != "application/pdf" || !strings.HasPrefix(got.Header().Get("Content-Disposition"), "inline;") || got.Header().Get("X-Content-SHA256") != d.SHA256 { t.Fatalf("original: %d %v", got.Code, got.Header()) } if rr := f.raw(t, "GET", path+"/prepared", "", nil, nil); rr.Code != 404 || !strings.Contains(rr.Body.String(), "not_prepared") { t.Errorf("prepared before delivery: %d %s", rr.Code, rr.Body.String()) } // A changed object is never served. for k := range f.objects.Objects { f.objects.Objects[k] = []byte("%PDF-1.7 tampered") } if rr := f.raw(t, "GET", path+"/original", "", nil, nil); rr.Code != 502 || !strings.Contains(rr.Body.String(), "digest_mismatch") || strings.Contains(rr.Body.String(), "tampered") { t.Errorf("tampered: %d %s", rr.Code, rr.Body.String()) } for k := range f.objects.Objects { delete(f.objects.Objects, k) } if rr := f.raw(t, "GET", path+"/original", "", nil, nil); rr.Code != 404 { t.Errorf("missing object: %d", rr.Code) } } func TestStoreIsTenantScoped(t *testing.T) { f := newStoreFixture(t, portal, "portal-svc:*") rr := f.upload(t, map[string]string{"area": "internal"}, "Richtlinie.pdf", []byte("%PDF synthetic")) var d store.Document _ = json.Unmarshal(rr.Body.Bytes(), &d) // A signed-in user of another workspace sees nothing of it. other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "00000000-0000-0000-0000-00000000beef"} g := newStoreFixture(t, other) g.s.Store, g.s.Objects = f.s.Store, f.objects base := "/v1/tenants/" + f.tenant.ID for _, p := range []string{base + "/store", base + "/store/documents/" + d.ID + "/original", base + "/store/assets/" + strings.Repeat("a", 64)} { if rr := g.raw(t, "GET", p, "", nil, nil); rr.Code != 404 { t.Errorf("%s: %d", p, rr.Code) } } // A published BreakPilot delivery is served like any store document; a draft is not. ctx := context.Background() report := []byte("%PDF-1.7 synthetic report") sum := sha256.Sum256(report) _ = f.objects.Put(ctx, "k/report", bytes.NewReader(report), int64(len(report)), "application/pdf") _, _ = f.s.Store.CreateDocument(ctx, store.Document{ID: "11111111-1111-1111-1111-111111111111", TenantID: f.tenant.ID, Title: "Report", Filename: "report.pdf", ContentType: "application/pdf", SHA256: hex.EncodeToString(sum[:]), ObjectKey: "k/report", Status: store.DocumentPublished}) _, _ = f.s.Store.CreateDocument(ctx, store.Document{ID: "22222222-2222-2222-2222-222222222222", TenantID: f.tenant.ID, Title: "Draft", ObjectKey: "k/draft", Status: store.DocumentDraft}) if rr := f.raw(t, "GET", base+"/store/documents/11111111-1111-1111-1111-111111111111/original", "", nil, nil); rr.Code != 200 || rr.Body.String() != string(report) { t.Errorf("delivery via store: %d", rr.Code) } if rr := f.raw(t, "GET", base+"/store/documents/22222222-2222-2222-2222-222222222222/original", "", nil, nil); rr.Code != 404 { t.Errorf("draft via store: %d", rr.Code) } } // bundle builds a synthetic store bundle (.tar.gz) in the Factory layout. type bundle struct { files map[string][]byte index []map[string]any caps []map[string]any } func newBundle() *bundle { return &bundle{files: map[string][]byte{}} } func (b *bundle) doc(id, title, class, kind string, original []byte, ext string) string { sum := hexsum(original) b.files["objects/"+sum+ext] = original d := map[string]any{"tenant_document_id": id, "content_digest": "sha256:" + sum, "title": title, "object_key": "objects/" + sum + ext} if class != "" { d["document_class"], d["legal_kind"] = class, kind } b.index = append(b.index, d) return sum } func (b *bundle) chunks(id string, assets ...[]byte) { pages := []any{} units := []any{map[string]any{"chunk_id": id + "#c00001", "unit_type": "TEXT_SECTION", "text": "Synthetischer Text"}} for i, a := range assets { sum := hexsum(a) b.files["figure_assets/sources/sha256/"+sum+".png"] = a if i == 0 { pages = append(pages, map[string]any{"page": 1, "page_image": map[string]any{"asset_digest": sum, "asset_status": "PNG_PAGE_RENDER_BOUND"}}) } else { units = append(units, map[string]any{"chunk_id": id + "#f00001", "unit_type": "FIGURE", "figure": map[string]any{"asset_digest": "sha256:" + sum}}) } } body, _ := json.Marshal(map[string]any{"status": "UNIFIED_V5", "text_source": "PDF_TEXT_LAYER", "chunk_list": units, "pages": pages}) b.files["chunks/"+id+".json"] = body } func (b *bundle) capture(id string) { body := []byte(`{"artifact":"CONSENT_BANNER_CAPTURE_V1","cmp":"synthetic","first_layer":{"title":"Cookies"}}`) sum := hexsum(body) b.files["presentation/consent_banner/"+sum+".json"] = body b.caps = append(b.caps, map[string]any{"tenant_document_id": id, "object_key": "presentation/consent_banner/" + sum + ".json", "digest": "sha256:" + sum}) } func (b *bundle) tgz(t *testing.T, prefix string) []byte { t.Helper() idx, _ := json.Marshal(map[string]any{"artifact": "LANE_B_INDEX_V1", "documents": b.index}) b.files["LANE_B_INDEX_V1.json"] = idx if len(b.caps) > 0 { c, _ := json.Marshal(map[string]any{"artifact": "CONSENT_BANNER_CAPTURES_V1", "captures": b.caps}) b.files["presentation/CONSENT_BANNER_CAPTURES_V1.json"] = c } b.files["LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json"] = []byte(`{"revision":8}`) var buf bytes.Buffer gz := gzip.NewWriter(&buf) tw := tar.NewWriter(gz) for name, body := range b.files { _ = tw.WriteHeader(&tar.Header{Name: prefix + name, Mode: 0o600, Size: int64(len(body)), Typeflag: tar.TypeReg}) _, _ = tw.Write(body) } _ = tw.Close() _ = gz.Close() return buf.Bytes() } var staff = map[string]string{"X-Staff-Subject": "staff-1", "X-Staff-Email": "staff@breakpilot.test"} func (f *storeFixture) importBundle(t *testing.T, body []byte, hdr map[string]string) (int, importResp, string) { t.Helper() rr := f.raw(t, "POST", "/v1/admin/tenants/"+f.tenant.ID+"/store/import", "application/gzip", body, hdr) var out importResp _ = json.Unmarshal(rr.Body.Bytes(), &out) return rr.Code, out, rr.Body.String() } func TestStoreImport(t *testing.T) { f := newStoreFixture(t, portal, "portal-svc:*") b := newBundle() b.doc("wsdoc-impressum", "Impressum", "LEGAL", "impressum", []byte("Muster Modellbau GmbH\nMusterstraße 1"), ".txt") b.doc("wsdoc-cookie", "Cookie-Banner", "LEGAL", "cookie", []byte("Wir verwenden Cookies."), ".txt") b.doc("wsdoc-lok100", "Lok 100 Datenblatt", "", "", []byte("%PDF-1.7 synthetic lok"), ".pdf") b.doc("wsdoc-faq", "FAQ", "LEGAL", "faq", []byte("unknown folder"), ".txt") b.doc("wsdoc-noasset", "Lok 200 Datenblatt", "", "", []byte("%PDF-1.7 synthetic lok 200"), ".pdf") b.chunks("wsdoc-impressum") b.chunks("wsdoc-lok100", []byte("PNG page 1"), []byte("PNG figure 1")) b.chunks("wsdoc-noasset", []byte("PNG page of lok 200")) b.capture("wsdoc-cookie") // The image of Lok 200 goes missing; a bogus original is listed but absent. for k, v := range b.files { if string(v) == "PNG page of lok 200" { delete(b.files, k) } } b.index = append(b.index, map[string]any{"tenant_document_id": "wsdoc-ghost", "content_digest": "sha256:" + strings.Repeat("b", 64), "title": "Ghost", "object_key": "objects/" + strings.Repeat("b", 64) + ".pdf"}) body := b.tgz(t, "bundle/") // wrapped in one directory, as `tar czf bundle.tgz bundle/` makes it if code, _, _ := f.importBundle(t, body, nil); code != http.StatusForbidden { t.Fatalf("import without staff: %d", code) } code, out, raw := f.importBundle(t, body, staff) if code != 200 || out.Revision != 8 || len(out.Pin) != 64 { t.Fatalf("import: %d %s", code, raw) } byID := map[string]ImportOutcome{} for _, o := range out.Documents { byID[o.ExternalID] = o } check := func(id, original, prepared, consent string) { t.Helper() o := byID[id] if o.Original != original || o.Prepared != prepared || o.Consent != consent { t.Errorf("%s: %+v", id, o) } } check("wsdoc-impressum", "imported", "imported", "absent") check("wsdoc-cookie", "imported", "absent", "imported") check("wsdoc-lok100", "imported", "imported", "absent") check("wsdoc-faq", "rejected", "absent", "absent") check("wsdoc-noasset", "imported", "rejected", "absent") check("wsdoc-ghost", "rejected", "absent", "absent") if byID["wsdoc-lok100"].Assets != 2 || byID["wsdoc-lok100"].Area != "product_public" || byID["wsdoc-cookie"].LegalKind != "cookie" { t.Errorf("lok100 / cookie: %+v %+v", byID["wsdoc-lok100"], byID["wsdoc-cookie"]) } if strings.Contains(raw, "Musterstraße") || strings.Contains(raw, "Synthetischer Text") { t.Error("the import answer carries document content") } // What was imported is served, checked. base := "/v1/tenants/" + f.tenant.ID + "/store" lok := byID["wsdoc-lok100"].DocumentID if rr := f.raw(t, "GET", base+"/documents/"+lok+"/prepared", "", nil, nil); rr.Code != 200 || !strings.Contains(rr.Body.String(), "UNIFIED_V5") { t.Errorf("prepared: %d", rr.Code) } if rr := f.raw(t, "GET", base+"/assets/"+hexsum([]byte("PNG figure 1")), "", nil, nil); rr.Code != 200 || rr.Body.String() != "PNG figure 1" || rr.Header().Get("Content-Type") != "image/png" { t.Errorf("asset: %d %v", rr.Code, rr.Header()) } cookie := byID["wsdoc-cookie"].DocumentID if rr := f.raw(t, "GET", base+"/documents/"+cookie+"/consent-banner", "", nil, nil); rr.Code != 200 || !strings.Contains(rr.Body.String(), "CONSENT_BANNER_CAPTURE_V1") { t.Errorf("consent: %d", rr.Code) } if rr := f.raw(t, "GET", base+"/documents/"+byID["wsdoc-impressum"].DocumentID+"/original", "", nil, nil); rr.Code != 200 || !strings.HasPrefix(rr.Header().Get("Content-Type"), "text/plain") { t.Errorf("text original: %d", rr.Code) } ctx := context.Background() d, _ := f.s.Store.GetDocument(ctx, lok) noasset, _ := f.s.Store.GetDocument(ctx, byID["wsdoc-noasset"].DocumentID) if d.ProcessingStatus != "ready" || noasset.ProcessingStatus != "pending" || d.ExternalID != "wsdoc-lok100" || d.UploadedBy != "staff@breakpilot.test" { t.Errorf("status: lok100 %+v, noasset %q", d, noasset.ProcessingStatus) } // Again: nothing new, nothing duplicated. _, again, _ := f.importBundle(t, body, staff) for _, o := range again.Documents { if o.Original == "imported" || o.Prepared == "imported" || o.Consent == "imported" { t.Errorf("rerun imported again: %+v", o) } } if docs, _ := f.s.Store.ListStoreDocuments(ctx, f.tenant.ID); len(docs) != 4 { t.Errorf("documents after rerun: %d", len(docs)) } if ev := f.audit(t, "store.imported"); len(ev) != 2 || ev[0].ActorType != "staff" { t.Errorf("audit: %+v", ev) } } func TestStoreImportRefusesUnsafeBundles(t *testing.T) { f := newStoreFixture(t, portal, "portal-svc:*") mk := func(entries ...*tar.Header) []byte { var buf bytes.Buffer gz := gzip.NewWriter(&buf) tw := tar.NewWriter(gz) for _, h := range entries { _ = tw.WriteHeader(h) if h.Typeflag == tar.TypeReg { _, _ = tw.Write(make([]byte, h.Size)) } } _ = tw.Close() _ = gz.Close() return buf.Bytes() } for name, body := range map[string][]byte{ "not gzip": []byte("plain text"), "dotdot": mk(&tar.Header{Name: "../evil.json", Size: 1, Mode: 0o600, Typeflag: tar.TypeReg}), "absolute": mk(&tar.Header{Name: "/etc/evil", Size: 1, Mode: 0o600, Typeflag: tar.TypeReg}), "symlink": mk(&tar.Header{Name: "objects/link", Linkname: "/etc/passwd", Typeflag: tar.TypeSymlink}), "no index": mk(&tar.Header{Name: "objects/x.pdf", Size: 3, Mode: 0o600, Typeflag: tar.TypeReg}), } { if code, _, raw := f.importBundle(t, body, staff); code != 400 || !strings.Contains(raw, "invalid_bundle") { t.Errorf("%s: %d %s", name, code, raw) } } f.s.Cfg = &config.Config{StoreImportMaxBytes: 64} big := newBundle() big.doc("wsdoc-big", "Big", "", "", bytes.Repeat([]byte("x"), 4096), ".txt") if code, _, raw := f.importBundle(t, big.tgz(t, ""), staff); code != http.StatusRequestEntityTooLarge { t.Errorf("too large: %d %s", code, raw) } } func TestCheckChunkFile(t *testing.T) { a, b := strings.Repeat("a", 64), strings.Repeat("b", 64) n, d, err := checkChunkFile([]byte(`{"chunk_list":[{"figure":{"asset_digest":"sha256:` + a + `"}},{}],"pages":[{"page_image":{"asset_digest":"` + b + `"}},{"page_image":{"asset_digest":"` + a + `"}}]}`)) if err != nil || n != 2 || len(d) != 2 || d[0] != a || d[1] != b { t.Fatalf("%d %v %v", n, d, err) } for _, bad := range []string{`[]`, `{"pages":[]}`, `{"chunk_list":[]}`, `{"chunk_list":[],"pages":[{"page_image":{"asset_digest":"xyz"}}]}`} { if _, _, err := checkChunkFile([]byte(bad)); err == nil { t.Errorf("accepted %s", bad) } } }