diff --git a/internal/config/config.go b/internal/config/config.go index 2aa9ac2..bf3eb2f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -85,6 +85,11 @@ type Config struct { MailFromName string // PortalURL is the portal's public origin, for links in mail. PortalURL string + // PruefwerkPlatformURL / PruefwerkURL override where the registry reads a + // project's Prüfwerk objects (…/api/v1/platform) and links them (the + // dashboard). Unset: derived from the catalog for this environment. + PruefwerkPlatformURL string + PruefwerkURL string LiteLLMBaseURL string LiteLLMMasterKey string @@ -144,13 +149,15 @@ func Load() (*Config, error) { DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"), DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20, - SMTPHost: os.Getenv("SMTP_HOST"), - SMTPPort: getint("SMTP_PORT", 587), - SMTPUser: os.Getenv("SMTP_USER"), - SMTPPassword: os.Getenv("SMTP_PASSWORD"), - MailFrom: getenv("MAIL_FROM", "noreply@breakpilot.com"), - MailFromName: getenv("MAIL_FROM_NAME", "BreakPilot"), - PortalURL: getenv("PORTAL_URL", "https://app.breakpilot.com"), + SMTPHost: os.Getenv("SMTP_HOST"), + SMTPPort: getint("SMTP_PORT", 587), + SMTPUser: os.Getenv("SMTP_USER"), + SMTPPassword: os.Getenv("SMTP_PASSWORD"), + MailFrom: getenv("MAIL_FROM", "noreply@breakpilot.com"), + MailFromName: getenv("MAIL_FROM_NAME", "BreakPilot"), + PortalURL: getenv("PORTAL_URL", "https://app.breakpilot.com"), + PruefwerkPlatformURL: os.Getenv("PRUEFWERK_PLATFORM_URL"), + PruefwerkURL: os.Getenv("PRUEFWERK_URL"), LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"), LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"), diff --git a/internal/server/documents.go b/internal/server/documents.go index dac2915..7af64da 100644 --- a/internal/server/documents.go +++ b/internal/server/documents.go @@ -117,6 +117,8 @@ func (s *Server) adminUploadDocument(w http.ResponseWriter, r *http.Request) { } var title, description string + var own bool + var projectIDs []string var doc *store.Document for { part, perr := mr.NextPart() @@ -129,6 +131,18 @@ func (s *Server) adminUploadDocument(w http.ResponseWriter, r *http.Request) { return } switch part.FormName() { + case "own_document": + b, _ := io.ReadAll(io.LimitReader(part, 16)) + v := strings.ToLower(strings.TrimSpace(string(b))) + own = v == "on" || v == "true" || v == "1" + case "project_ids": + // Repeated fields or one comma-separated value. + b, _ := io.ReadAll(io.LimitReader(part, 8<<10)) + for _, id := range strings.Split(string(b), ",") { + if id = strings.TrimSpace(id); id != "" { + projectIDs = append(projectIDs, id) + } + } case "title", "description": b, _ := io.ReadAll(io.LimitReader(part, 4<<10)) if part.FormName() == "title" { @@ -187,6 +201,7 @@ func (s *Server) adminUploadDocument(w http.ResponseWriter, r *http.Request) { return } doc.Title, doc.Description = title, description + doc.OwnDocument, doc.ProjectIDs = own, projectIDs if sub, email, ok := s.staffActor(r); ok { doc.UploadedBy = firstNonEmpty(email, sub) } @@ -272,7 +287,68 @@ func (s *Server) adminPublishDocument(w http.ResponseWriter, r *http.Request) { TenantID: d.TenantID, Action: "document.published", TargetID: d.ID, TargetType: "document", TargetName: d.Title, ActorType: "service", }) - s.documentPublished(ctx, d) + // The tenant's own documents are kept here for them: they appear in the + // portal, but nobody is told "BreakPilot published a document". + if !d.OwnDocument { + s.documentPublished(ctx, d) + } + writeJSON(w, http.StatusOK, d) +} + +type documentUpdateReq struct { + ProjectIDs *[]string `json:"project_ids"` + OwnDocument *bool `json:"own_document"` +} + +// adminUpdateDocument is PATCH /v1/admin/documents/{doc}: staff assign a +// document to projects (replacing the set) and mark it as the tenant's own. +// Both work on drafts and published documents. +func (s *Server) adminUpdateDocument(w http.ResponseWriter, r *http.Request) { + var in documentUpdateReq + if !decodeJSON(w, r, &in) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + d, err := s.Store.GetDocument(ctx, r.PathValue("doc")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + meta := map[string]interface{}{} + if in.OwnDocument != nil && *in.OwnDocument != d.OwnDocument { + if d, err = s.Store.SetDocumentOwn(ctx, d.ID, *in.OwnDocument); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + meta["own_document"] = d.OwnDocument + } + if in.ProjectIDs != nil { + if d, err = s.Store.SetDocumentProjects(ctx, d.ID, *in.ProjectIDs); err != nil { + if errors.Is(err, store.ErrInvalidInput) { + writeError(w, http.StatusBadRequest, "invalid_projects", "every project must exist and belong to the document's tenant") + return + } + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + meta["project_ids"] = d.ProjectIDs + } + if len(meta) > 0 { + if sub, email, ok := s.staffActor(r); ok { + meta["by"] = firstNonEmpty(email, sub) + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: d.TenantID, Action: "document.updated", TargetID: d.ID, TargetType: "document", TargetName: d.Title, + ActorType: "service", Metadata: meta, + }) + } writeJSON(w, http.StatusOK, d) } diff --git a/internal/server/members.go b/internal/server/members.go index 04634a3..dd24ad5 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -78,6 +78,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) { s.listTenantMembers(w, r) case "documents": s.listTenantDocuments(w, r) + case "projects": + s.listTenantProjects(w, r) default: writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource") } diff --git a/internal/server/projects.go b/internal/server/projects.go new file mode 100644 index 0000000..63c9802 --- /dev/null +++ b/internal/server/projects.go @@ -0,0 +1,294 @@ +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 +} diff --git a/internal/server/projects_test.go b/internal/server/projects_test.go new file mode 100644 index 0000000..28be068 --- /dev/null +++ b/internal/server/projects_test.go @@ -0,0 +1,254 @@ +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 { + t.Fatalf("patched: %+v", d) + } + 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,"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"` + ProjectIDs []string `json:"project_ids"` + } + } + _ = json.Unmarshal(raw, &out) + if !out.Available || len(out.Items) != 2 || out.Items[0].OpenFindings != 7 || + 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) + } + }) +} diff --git a/internal/server/server.go b/internal/server/server.go index d7230e2..0cb9b0e 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -108,6 +108,11 @@ func NewRouter(s *Server) http.Handler { // the two coexist and the lookup keeps winning for its own prefix. mux.HandleFunc("GET /v1/tenants/{id}/{sub}", s.tenantSubresource) mux.HandleFunc("POST /v1/tenants/{id}/invites", s.inviteTenantMember) + // Projekte (0010): the list is a {sub} of tenantSubresource. + mux.HandleFunc("POST /v1/tenants/{id}/projects", s.createTenantProject) + mux.HandleFunc("PATCH /v1/tenants/{id}/projects/{pid}", s.updateTenantProject) + mux.HandleFunc("DELETE /v1/tenants/{id}/projects/{pid}", s.deleteTenantProject) + mux.HandleFunc("GET /v1/tenants/{id}/projects/{pid}/targets", s.listProjectTargets) // entitlements mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts) @@ -160,6 +165,7 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument) mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument) mux.HandleFunc("DELETE /v1/admin/documents/{doc}", s.adminDeleteDocument) + mux.HandleFunc("PATCH /v1/admin/documents/{doc}", s.adminUpdateDocument) // Notifications from products (F3; group "notify"). mux.HandleFunc("POST /v1/notifications", s.postNotification) diff --git a/internal/store/memory.go b/internal/store/memory.go index d8a9fc6..d4b95e6 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -35,6 +35,7 @@ type Memory struct { licences map[string]*Licence documents map[string]*Document + projects map[string]*Project mail []*MailItem mailID int64 } @@ -57,6 +58,7 @@ func NewMemory() *Memory { usageKey: make(map[string]int64), receipts: make(map[string]time.Time), licences: make(map[string]*Licence), + projects: make(map[string]*Project), documents: make(map[string]*Document), } @@ -534,6 +536,11 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { delete(m.documents, did) } } + for pid, pr := range m.projects { + if pr.TenantID == id { + delete(m.projects, pid) + } + } usage := m.usage[:0] for _, u := range m.usage { if u.TenantID != id { diff --git a/internal/store/memory_documents.go b/internal/store/memory_documents.go index e9e92f1..84e2188 100644 --- a/internal/store/memory_documents.go +++ b/internal/store/memory_documents.go @@ -24,11 +24,62 @@ func (m *Memory) CreateDocument(_ context.Context, d Document) (*Document, error if d.Status == "" { d.Status = DocumentDraft } + ids, ok := m.tenantProjectIDs(d.TenantID, d.ProjectIDs) + if !ok { + return nil, ErrInvalidInput + } + d.ProjectIDs = ids d.CreatedAt, d.UpdatedAt = now, now row := d m.documents[d.ID] = &row - out := row - return &out, nil + return row.copy(), nil +} + +// copy returns the document with its own ProjectIDs slice. +func (d *Document) copy() *Document { + out := *d + out.ProjectIDs = append([]string{}, d.ProjectIDs...) + return &out +} + +// tenantProjectIDs deduplicates and sorts ids and reports whether every one +// is a project of the tenant. Caller holds the lock. +func (m *Memory) tenantProjectIDs(tenantID string, ids []string) ([]string, bool) { + out := dedupe(ids) + for _, id := range out { + p, ok := m.projects[id] + if !ok || p.TenantID != tenantID { + return nil, false + } + } + sort.Strings(out) + return out, true +} + +func (m *Memory) SetDocumentProjects(_ context.Context, docID string, projectIDs []string) (*Document, error) { + m.mu.Lock() + defer m.mu.Unlock() + d, ok := m.documents[docID] + if !ok { + return nil, ErrNotFound + } + ids, ok := m.tenantProjectIDs(d.TenantID, projectIDs) + if !ok { + return nil, ErrInvalidInput + } + d.ProjectIDs, d.UpdatedAt = ids, time.Now().UTC() + return d.copy(), nil +} + +func (m *Memory) SetDocumentOwn(_ context.Context, docID string, own bool) (*Document, error) { + m.mu.Lock() + defer m.mu.Unlock() + d, ok := m.documents[docID] + if !ok { + return nil, ErrNotFound + } + d.OwnDocument, d.UpdatedAt = own, time.Now().UTC() + return d.copy(), nil } func (m *Memory) GetDocument(_ context.Context, id string) (*Document, error) { @@ -38,8 +89,7 @@ func (m *Memory) GetDocument(_ context.Context, id string) (*Document, error) { if !ok { return nil, ErrNotFound } - out := *d - return &out, nil + return d.copy(), nil } func (m *Memory) ListDocuments(_ context.Context, tenantID string, publishedOnly bool) ([]Document, error) { @@ -50,7 +100,7 @@ func (m *Memory) ListDocuments(_ context.Context, tenantID string, publishedOnly if d.TenantID != tenantID || (publishedOnly && d.Status != DocumentPublished) { continue } - out = append(out, *d) + out = append(out, *d.copy()) } sort.Slice(out, func(i, j int) bool { if out[i].CreatedAt.Equal(out[j].CreatedAt) { @@ -72,8 +122,7 @@ func (m *Memory) PublishDocument(_ context.Context, id, by string, at time.Time) at = at.UTC() d.Status, d.PublishedBy, d.PublishedAt, d.UpdatedAt = DocumentPublished, by, &at, at } - out := *d - return &out, nil + return d.copy(), nil } func (m *Memory) DeleteDocument(_ context.Context, id string) error { diff --git a/internal/store/memory_projects.go b/internal/store/memory_projects.go new file mode 100644 index 0000000..93ec266 --- /dev/null +++ b/internal/store/memory_projects.go @@ -0,0 +1,116 @@ +package store + +import ( + "context" + "sort" + "strings" + "time" + + "github.com/google/uuid" +) + +func (m *Memory) validProject(p Project) bool { + n := len([]rune(p.Name)) + return n >= 1 && n <= 120 && len([]rune(p.Description)) <= 1000 && + (p.Kind == ProjectKindProduct || p.Kind == ProjectKindTopic) +} + +// nameTaken reports whether another project of the tenant has the name +// (case-insensitively). Caller holds the lock. +func (m *Memory) nameTaken(p Project) bool { + for _, x := range m.projects { + if x.TenantID == p.TenantID && x.ID != p.ID && strings.EqualFold(x.Name, p.Name) { + return true + } + } + return false +} + +func (m *Memory) ListProjects(_ context.Context, tenantID string) ([]Project, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []Project{} + for _, p := range m.projects { + if p.TenantID == tenantID { + out = append(out, *p) + } + } + sort.Slice(out, func(i, j int) bool { + a, b := strings.ToLower(out[i].Name), strings.ToLower(out[j].Name) + if a == b { + return out[i].ID < out[j].ID + } + return a < b + }) + return out, nil +} + +func (m *Memory) GetProject(_ context.Context, id string) (*Project, error) { + m.mu.RLock() + defer m.mu.RUnlock() + p, ok := m.projects[id] + if !ok { + return nil, ErrNotFound + } + out := *p + return &out, nil +} + +func (m *Memory) CreateProject(_ context.Context, p Project) (*Project, error) { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[p.TenantID]; !ok { + return nil, ErrNotFound + } + if !m.validProject(p) { + return nil, ErrInvalidInput + } + p.ID = uuid.NewString() + if m.nameTaken(p) { + return nil, ErrConflict + } + now := time.Now().UTC() + p.CreatedAt, p.UpdatedAt = now, now + row := p + m.projects[p.ID] = &row + out := row + return &out, nil +} + +func (m *Memory) UpdateProject(_ context.Context, p Project) (*Project, error) { + m.mu.Lock() + defer m.mu.Unlock() + cur, ok := m.projects[p.ID] + if !ok { + return nil, ErrNotFound + } + p.TenantID = cur.TenantID + if !m.validProject(p) { + return nil, ErrInvalidInput + } + if m.nameTaken(p) { + return nil, ErrConflict + } + cur.Name, cur.Kind, cur.Description, cur.UpdatedAt = p.Name, p.Kind, p.Description, time.Now().UTC() + out := *cur + return &out, nil +} + +func (m *Memory) DeleteProject(_ context.Context, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.projects[id]; !ok { + return ErrNotFound + } + delete(m.projects, id) + for _, d := range m.documents { + kept := d.ProjectIDs[:0:0] + for _, pid := range d.ProjectIDs { + if pid != id { + kept = append(kept, pid) + } + } + d.ProjectIDs = kept + } + return nil +} diff --git a/internal/store/postgres_documents.go b/internal/store/postgres_documents.go index 9b246bc..8baaf1d 100644 --- a/internal/store/postgres_documents.go +++ b/internal/store/postgres_documents.go @@ -10,13 +10,17 @@ import ( const documentSelect = ` SELECT id::text, tenant_id::text, title, description, filename, content_type, size_bytes, sha256, - object_key, status, uploaded_by, COALESCE(published_by, ''), published_at, created_at, updated_at + object_key, status, uploaded_by, COALESCE(published_by, ''), published_at, created_at, updated_at, + own_document, + COALESCE((SELECT array_agg(dp.project_id::text ORDER BY dp.project_id) FROM document_projects dp + WHERE dp.document_id = documents.id), '{}') FROM documents ` func scanDocument(row pgx.Row) (*Document, error) { var d Document if err := row.Scan(&d.ID, &d.TenantID, &d.Title, &d.Description, &d.Filename, &d.ContentType, &d.SizeBytes, &d.SHA256, - &d.ObjectKey, &d.Status, &d.UploadedBy, &d.PublishedBy, &d.PublishedAt, &d.CreatedAt, &d.UpdatedAt); err != nil { + &d.ObjectKey, &d.Status, &d.UploadedBy, &d.PublishedBy, &d.PublishedAt, &d.CreatedAt, &d.UpdatedAt, + &d.OwnDocument, &d.ProjectIDs); err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } @@ -33,11 +37,20 @@ func (p *Postgres) CreateDocument(ctx context.Context, d Document) (*Document, e d.Status = DocumentDraft } _, err := p.pool.Exec(ctx, ` - INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by) - VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, - d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy) + INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by, own_document) + VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy, d.OwnDocument) switch { case err == nil: + if len(d.ProjectIDs) > 0 { + out, perr := p.SetDocumentProjects(ctx, d.ID, d.ProjectIDs) + if perr != nil { + // No half-created document: without its projects it goes again. + _, _ = p.pool.Exec(context.WithoutCancel(ctx), `DELETE FROM documents WHERE id = $1::uuid`, d.ID) + return nil, perr + } + return out, nil + } return p.GetDocument(ctx, d.ID) case isFKViolation(err), isInvalidUUID(err): return nil, ErrNotFound @@ -109,3 +122,73 @@ func (p *Postgres) DeleteDocument(ctx context.Context, id string) error { } return nil } + +func (p *Postgres) SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error) { + d, err := p.GetDocument(ctx, docID) + if err != nil { + return nil, err + } + ids := dedupe(projectIDs) + tx, err := p.pool.Begin(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback(ctx) }() + if len(ids) > 0 { + // Every project must exist and belong to the document's tenant. + var n int + err := tx.QueryRow(ctx, `SELECT count(*) FROM projects WHERE id = ANY($1::uuid[]) AND tenant_id = $2::uuid`, ids, d.TenantID).Scan(&n) + if isInvalidUUID(err) { + return nil, ErrInvalidInput + } + if err != nil { + return nil, err + } + if n != len(ids) { + return nil, ErrInvalidInput + } + } + if _, err := tx.Exec(ctx, `DELETE FROM document_projects WHERE document_id = $1::uuid`, docID); err != nil { + return nil, err + } + if len(ids) > 0 { + if _, err := tx.Exec(ctx, `INSERT INTO document_projects (document_id, project_id) + SELECT $1::uuid, unnest($2::uuid[])`, docID, ids); err != nil { + return nil, err + } + } + if _, err := tx.Exec(ctx, `UPDATE documents SET updated_at = now() WHERE id = $1::uuid`, docID); err != nil { + return nil, err + } + if err := tx.Commit(ctx); err != nil { + return nil, err + } + return p.GetDocument(ctx, docID) +} + +func (p *Postgres) SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error) { + tag, err := p.pool.Exec(ctx, `UPDATE documents SET own_document = $2, updated_at = now() WHERE id = $1::uuid`, docID, own) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + if tag.RowsAffected() == 0 { + return nil, ErrNotFound + } + return p.GetDocument(ctx, docID) +} + +// dedupe keeps the first occurrence of every id. +func dedupe(ids []string) []string { + seen := map[string]bool{} + out := []string{} + for _, id := range ids { + if id != "" && !seen[id] { + seen[id] = true + out = append(out, id) + } + } + return out +} diff --git a/internal/store/postgres_projects.go b/internal/store/postgres_projects.go new file mode 100644 index 0000000..0cfe9a7 --- /dev/null +++ b/internal/store/postgres_projects.go @@ -0,0 +1,104 @@ +package store + +import ( + "context" + "errors" + + "github.com/jackc/pgx/v5" +) + +const projectSelect = ` +SELECT id::text, tenant_id::text, name, kind, description, created_by, created_at, updated_at +FROM projects ` + +func scanProject(row pgx.Row) (*Project, error) { + var p Project + if err := row.Scan(&p.ID, &p.TenantID, &p.Name, &p.Kind, &p.Description, &p.CreatedBy, &p.CreatedAt, &p.UpdatedAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + return &p, nil +} + +func (p *Postgres) ListProjects(ctx context.Context, tenantID string) ([]Project, error) { + rows, err := p.pool.Query(ctx, projectSelect+`WHERE tenant_id = $1::uuid ORDER BY lower(name), id`, tenantID) + if isInvalidUUID(err) { + return []Project{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []Project{} + for rows.Next() { + pr, err := scanProject(rows) + if err != nil { + return nil, err + } + out = append(out, *pr) + } + return out, rows.Err() +} + +func (p *Postgres) GetProject(ctx context.Context, id string) (*Project, error) { + pr, err := scanProject(p.pool.QueryRow(ctx, projectSelect+`WHERE id = $1::uuid`, id)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return pr, err +} + +func (p *Postgres) CreateProject(ctx context.Context, pr Project) (*Project, error) { + var id string + err := p.pool.QueryRow(ctx, ` + INSERT INTO projects (tenant_id, name, kind, description, created_by) + VALUES ($1::uuid, $2, $3, $4, $5) RETURNING id::text`, + pr.TenantID, pr.Name, pr.Kind, pr.Description, pr.CreatedBy).Scan(&id) + switch { + case err == nil: + return p.GetProject(ctx, id) + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isUniqueViolation(err): + return nil, ErrConflict + case isCheckViolation(err): + return nil, ErrInvalidInput + default: + return nil, err + } +} + +func (p *Postgres) UpdateProject(ctx context.Context, pr Project) (*Project, error) { + tag, err := p.pool.Exec(ctx, ` + UPDATE projects SET name = $2, kind = $3, description = $4, updated_at = now() + WHERE id = $1::uuid`, pr.ID, pr.Name, pr.Kind, pr.Description) + switch { + case isInvalidUUID(err): + return nil, ErrNotFound + case isUniqueViolation(err): + return nil, ErrConflict + case isCheckViolation(err): + return nil, ErrInvalidInput + case err != nil: + return nil, err + case tag.RowsAffected() == 0: + return nil, ErrNotFound + } + return p.GetProject(ctx, pr.ID) +} + +func (p *Postgres) DeleteProject(ctx context.Context, id string) error { + tag, err := p.pool.Exec(ctx, `DELETE FROM projects WHERE id = $1::uuid`, id) + if isInvalidUUID(err) { + return ErrNotFound + } + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} diff --git a/internal/store/store.go b/internal/store/store.go index 205a2b8..4e13987 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -140,6 +140,18 @@ type Store interface { DeleteTenant(ctx context.Context, id string) error PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error) DeleteDocument(ctx context.Context, id string) error + // SetDocumentProjects replaces a document's projects; every project must + // belong to the document's tenant (ErrInvalidInput otherwise). + SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error) + SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error) + + // Projects (0010). Names are unique per tenant, case-insensitively + // (ErrConflict). Deleting a project removes it from its documents. + ListProjects(ctx context.Context, tenantID string) ([]Project, error) + GetProject(ctx context.Context, id string) (*Project, error) + CreateProject(ctx context.Context, p Project) (*Project, error) + UpdateProject(ctx context.Context, p Project) (*Project, error) + DeleteProject(ctx context.Context, id string) error // Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey // (false when the key existed). ClaimMail leases due unsent rows. diff --git a/internal/store/types.go b/internal/store/types.go index 3ceb36a..d5d97b9 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -264,6 +264,11 @@ type Document struct { PublishedAt *time.Time `json:"published_at,omitempty"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` + // OwnDocument marks the tenant's own file kept here for them: visible + // like any other, but publishing it sends no notification (0010). + OwnDocument bool `json:"own_document"` + // ProjectIDs are the tenant projects the document belongs to (0010). + ProjectIDs []string `json:"project_ids"` } const ( @@ -271,6 +276,24 @@ const ( DocumentPublished = "published" ) +// Project — a tenant's grouping of documents and product objects (0010): +// one of the customer's products or machines, or a topic such as the CRA. +type Project struct { + ID string `json:"id"` + TenantID string `json:"tenant_id"` + Name string `json:"name"` + Kind string `json:"kind"` // product | topic + Description string `json:"description"` + CreatedBy string `json:"created_by,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +const ( + ProjectKindProduct = "product" + ProjectKindTopic = "topic" +) + // MailItem — one platform email to one recipient (migration 0009). type MailItem struct { ID int64 `json:"id"` diff --git a/migrations/0010_projects.down.sql b/migrations/0010_projects.down.sql new file mode 100644 index 0000000..da4fa40 --- /dev/null +++ b/migrations/0010_projects.down.sql @@ -0,0 +1,3 @@ +ALTER TABLE documents DROP COLUMN IF EXISTS own_document; +DROP TABLE IF EXISTS document_projects; +DROP TABLE IF EXISTS projects; diff --git a/migrations/0010_projects.up.sql b/migrations/0010_projects.up.sql new file mode 100644 index 0000000..e020b6c --- /dev/null +++ b/migrations/0010_projects.up.sql @@ -0,0 +1,29 @@ +-- Projekte (v0.1.1): a tenant groups its documents and product objects (for +-- example Prüfwerk targets) by what they are about, either one of the +-- customer's own products or machines (kind 'product') or a topic such as +-- the CRA or the Data Act (kind 'topic'). Purely organisational: nothing that +-- gets checked depends on it. Staff and tenant admins create them. +-- (tenant_projects from 0001 is an unused placeholder and stays untouched.) +CREATE TABLE projects ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 120), + kind TEXT NOT NULL CHECK (kind IN ('product', 'topic')), + description TEXT NOT NULL DEFAULT '' CHECK (char_length(description) <= 1000), + created_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX projects_tenant_name ON projects (tenant_id, lower(name)); + +-- A document belongs to any number of the tenant's projects. +CREATE TABLE document_projects ( + document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE, + project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + PRIMARY KEY (document_id, project_id) +); +CREATE INDEX document_projects_project ON document_projects (project_id); + +-- The tenant's own documents, kept here for them: shown like any other, +-- but publishing one sends no notification mail. +ALTER TABLE documents ADD COLUMN own_document BOOLEAN NOT NULL DEFAULT false; diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 71bccab..ae1f450 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -114,8 +114,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { } } - // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox). - for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}} { + // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects). + for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}} { var exists bool err := db.QueryRow( "SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)", diff --git a/openapi.yaml b/openapi.yaml index 352cea0..a7f0412 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -220,6 +220,102 @@ paths: schema: { type: object, properties: { items: { type: array, items: { $ref: "#/components/schemas/Document" } } } } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/projects: + get: + summary: A tenant's projects (Projekte), by name. + description: | + Served by the `{id}/{sub}` route; user tokens reach their own tenant + only. Products read it with their service token (tenants.read) to + validate project ids on their own objects. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The projects. + content: + application/json: + schema: { type: object, properties: { items: { type: array, items: { $ref: "#/components/schemas/Project" } } } } + "404": { $ref: "#/components/responses/NotFound" } + post: + summary: Create a project. + description: | + The portal calls this for staff (X-Staff-* headers) and for tenant + admins (it checks their org role and names them in + X-Portal-User-Email). Names are unique per tenant, ignoring case. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: { schema: { $ref: "#/components/schemas/ProjectWrite" } } + responses: + "201": + description: Created. + content: + application/json: { schema: { $ref: "#/components/schemas/Project" } } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { description: A project with this name exists (name_taken). } + + /v1/tenants/{id}/projects/{pid}: + patch: + summary: Rename or change a project (fields given are changed). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: pid, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: { schema: { $ref: "#/components/schemas/ProjectWrite" } } + responses: + "200": + description: The project. + content: + application/json: { schema: { $ref: "#/components/schemas/Project" } } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { description: A project with this name exists (name_taken). } + delete: + summary: Delete a project. Its documents stay; they lose the assignment. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: pid, required: true, schema: { type: string, format: uuid } } + responses: + "204": { description: Deleted. } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/projects/{pid}/targets: + get: + summary: The project's Prüfwerk objects (read from Prüfwerk). + description: | + The registry asks Prüfwerk's platform API with its service token. + When Prüfwerk cannot answer, `items` is empty and `available` false. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: pid, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The objects. + content: + application/json: + schema: + type: object + properties: + available: { type: boolean } + items: + type: array + items: + type: object + properties: + id: { type: string } + name: { type: string } + target_type: { type: string } + last_scan_at: { type: string, format: date-time } + open_findings: { type: integer } + project_ids: { type: array, items: { type: string } } + url: { type: string, description: The object in the Prüfwerk dashboard. } + "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/members: get: summary: List the tenant's Keycloak organization members. @@ -482,6 +578,8 @@ paths: properties: title: { type: string, maxLength: 200 } description: { type: string, maxLength: 2000 } + own_document: { type: string, enum: ["on", "true", "1"], description: "The tenant's own document: publishing it sends no mail." } + project_ids: { type: string, description: "Project ids of the tenant; repeat the field or separate with commas." } file: { type: string, format: binary } responses: "201": @@ -507,6 +605,31 @@ paths: "404": { $ref: "#/components/responses/NotFound" } /v1/admin/documents/{doc}: + patch: + summary: Assign a document to projects and mark it as the tenant's own (staff). + description: | + `project_ids` replaces the set (an empty list removes all); every + project must belong to the document's tenant. `own_document` marks + the tenant's own files: shown like any other, but publishing them + sends no notification. Works on drafts and published documents. + parameters: + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + project_ids: { type: array, items: { type: string, format: uuid } } + own_document: { type: boolean } + responses: + "200": + description: The updated document. + content: + application/json: { schema: { $ref: "#/components/schemas/Document" } } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } delete: summary: Delete a document and its file (staff). parameters: @@ -1298,6 +1421,25 @@ components: published_by: { type: string } published_at: { type: string, format: date-time } created_at: { type: string, format: date-time } + own_document: { type: boolean, description: "The tenant's own file; publishing sends no mail." } + project_ids: { type: array, items: { type: string, format: uuid } } + Project: + type: object + properties: + id: { type: string, format: uuid } + tenant_id: { type: string, format: uuid } + name: { type: string } + kind: { type: string, enum: [product, topic] } + description: { type: string } + created_by: { type: string } + created_at: { type: string, format: date-time } + updated_at: { type: string, format: date-time } + ProjectWrite: + type: object + properties: + name: { type: string, minLength: 1, maxLength: 120 } + kind: { type: string, enum: [product, topic], description: "product: one of the customer's products or machines; topic: e.g. CRA, Data Act" } + description: { type: string, maxLength: 1000 } TenantActivity: type: object properties: