diff --git a/internal/server/authz.go b/internal/server/authz.go index c2a59d4..566d148 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -77,6 +77,8 @@ func routeGroup(method, path string) string { return "api-keys.verify" case strings.HasPrefix(path, "/v1/internal/keycloak/"): return "keycloak" + case strings.HasPrefix(path, "/v1/internal/intake/"): + return "intake" case strings.HasPrefix(path, "/v1/internal/erp/"): return "erp" case strings.HasPrefix(path, "/v1/entitlements"): @@ -137,6 +139,11 @@ func (s *Server) requireAuthz(next http.Handler) http.Handler { if p.IsUser() && isRoleDatasetPath(r.URL.Path) { group = "role-dataset.user" } + // The same for the R1 intake (intake.go): a person reports and reads + // their own reports with their own token. + if p.IsUser() && isIntakeUserPath(r.URL.Path) { + group = "intake.user" + } if !s.Authz.Allowed(p.ClientID, group) { s.Log.Warn("client not authorized for route group", "azp", p.ClientID, "group", group, "path", r.URL.Path) writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not call "+group) diff --git a/internal/server/intake.go b/internal/server/intake.go new file mode 100644 index 0000000..c8a38c6 --- /dev/null +++ b/internal/server/intake.go @@ -0,0 +1,363 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strconv" + "strings" + "time" + "unicode/utf8" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// R1 intake (0028; docgen#6 F01, P-R1-K05 Fassung 4 M21, M13): the one +// place where a security notice is recorded. A person of the workspace +// reports with their own token; the report is kept unchanged with the time +// it arrived and gets one stable reference, which is also the Meldereferenz +// of the confirmation (F-1). Later information is a supplement to the same +// reference, never a second report (M13–M15). +// +// POST /v1/tenants/{id}/intake/reports report (user token) +// GET /v1/tenants/{id}/intake/reports the caller's own reports +// GET /v1/tenants/{id}/intake/reports/{ref} one of them, with its handover state +// POST /v1/tenants/{id}/intake/reports/{ref}/supplements add to one of them +// +// Werkmeister takes each entry over into the R1 intake case and says what +// became of it (S-01, S-02); its service client has the route group intake: +// +// GET /v1/internal/intake/pending entries not settled yet +// POST /v1/internal/intake/entries/{entry}/receipts waiting, delivered, processed or refused +// +// Neither side reads the original here: the pending list carries the +// reference and the reporter's own answers that routing reads, never what +// was written. Reading the original needs the separate authority "Original +// einsehen" with an access log (F07, TV-1), which does not exist yet; until +// it does, no route returns it (fail closed). A reporter sees only their own +// reports and only their state (BM-7, AS-R1). + +// Limits of the fields of a report, in characters. +const ( + intakeWhatMax = 20000 + intakeShortMax = 500 + maxIntakeBody = 128 << 10 + intakePendingMax = 200 +) + +type intakeReportReq struct { + Danger string `json:"danger"` + About string `json:"about"` + What string `json:"what"` + When string `json:"when"` + Where string `json:"where"` + Contact string `json:"contact"` +} + +type intakeSupplementReq struct { + What string `json:"what"` +} + +type intakeReportView struct { + Reference string `json:"reference"` + ReceivedAt time.Time `json:"received_at"` + About string `json:"about"` + Danger string `json:"danger"` + // Handover is what became of the report itself: "" (not handed over + // yet), waiting, delivered, processed or refused. + Handover string `json:"handover"` + Entries []store.IntakeEntry `json:"entries,omitempty"` +} + +type intakeReceiptReq struct { + Status string `json:"status"` + Reason string `json:"reason"` + HandoffID string `json:"handoff_id"` + RunID string `json:"run_id"` +} + +// isIntakeUserPath reports whether path is /v1/tenants/{id}/intake or below. +func isIntakeUserPath(path string) bool { + rest, ok := strings.CutPrefix(path, "/v1/tenants/") + if !ok { + return false + } + parts := strings.Split(rest, "/") + return len(parts) >= 2 && parts[1] == "intake" +} + +// intakeUser: the reporting person, in their own workspace. +func (s *Server) intakeUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (*authn.Principal, *store.Tenant, bool) { + p, has := authn.PrincipalFrom(r.Context()) + if !has || !p.IsUser() { + writeError(w, http.StatusForbidden, "user_token_required", "a report is made and read with the token of the reporting person") + return nil, nil, false + } + t, ok := s.tenantInScope(ctx, w, r) + return p, t, ok +} + +// field checks one text of a report: trimmed, at most max characters, +// required or not. +func field(v string, max int, required bool) (string, bool) { + v = strings.TrimSpace(v) + if !utf8.ValidString(v) || utf8.RuneCountInString(v) > max || (required && v == "") { + return "", false + } + return v, true +} + +func oneOf(v, def string, allowed ...string) (string, bool) { + if v == "" && def != "" { + return def, true + } + for _, a := range allowed { + if v == a { + return v, true + } + } + return "", false +} + +// createIntakeReport is POST /v1/tenants/{id}/intake/reports. Only the +// description is required; nothing asks for an assessment (AK-AS11). The +// answer to "immediate danger to people?" comes first in the form and is +// required, "unknown" included (AK-AS10). +func (s *Server) createIntakeReport(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + r.Body = http.MaxBytesReader(w, r.Body, maxIntakeBody) + var in intakeReportReq + if !decodeJSON(w, r, &in) { + return + } + danger, ok := oneOf(in.Danger, "", "yes", "no", "unknown") + if !ok { + writeError(w, http.StatusBadRequest, "invalid_danger", "danger is yes, no or unknown") + return + } + about, ok := oneOf(in.About, store.IntakeAboutUnknown, store.IntakeAboutProduct, store.IntakeAboutITOT, store.IntakeAboutUnknown) + if !ok { + writeError(w, http.StatusBadRequest, "invalid_about", "about is product, it_ot or unknown") + return + } + what, ok := field(in.What, intakeWhatMax, true) + if !ok { + writeError(w, http.StatusBadRequest, "invalid_what", "what was noticed is required, at most 20000 characters") + return + } + original := map[string]string{"danger": danger, "about": about, "what": what} + for name, v := range map[string]string{"when": in.When, "where": in.Where, "contact": in.Contact} { + v, ok := field(v, intakeShortMax, false) + if !ok { + writeError(w, http.StatusBadRequest, "invalid_"+name, name+" has at most 500 characters") + return + } + if v != "" { + original[name] = v + } + } + p, t, ok := s.intakeUser(ctx, w, r) + if !ok { + return + } + raw, _ := json.Marshal(original) + rep, _, err := s.Store.CreateIntakeReport(ctx, store.IntakeCapture{TenantID: t.ID, Channel: store.IntakeChannelPortal, + ReporterSub: p.Subject, About: about, Danger: danger, Original: raw, At: s.now()}) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + // Metadata only: the reference and what it is about, never the text. + s.Log.Info("intake report recorded", "tenant_id", t.ID, "reference", rep.Reference, "about", about) + writeJSON(w, http.StatusCreated, intakeReportView{Reference: rep.Reference, ReceivedAt: rep.ReceivedAt, About: rep.About, Danger: rep.Danger}) +} + +// ownIntakeReport loads a report of the caller; anyone else's is not there. +func (s *Server) ownIntakeReport(ctx context.Context, w http.ResponseWriter, r *http.Request) (*authn.Principal, *store.IntakeReport, bool) { + p, t, ok := s.intakeUser(ctx, w, r) + if !ok { + return nil, nil, false + } + rep, err := s.Store.GetIntakeReport(ctx, t.ID, r.PathValue("ref")) + if err == nil && rep.ReporterSub != p.Subject { + err = store.ErrNotFound + } + if err != nil { + if !mapStoreError(w, err) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + } + return nil, nil, false + } + return p, rep, true +} + +func (s *Server) intakeView(ctx context.Context, rep *store.IntakeReport) (intakeReportView, error) { + entries, err := s.Store.IntakeEntries(ctx, rep.TenantID, rep.Reference) + if err != nil { + return intakeReportView{}, err + } + v := intakeReportView{Reference: rep.Reference, ReceivedAt: rep.ReceivedAt, About: rep.About, Danger: rep.Danger, Entries: entries} + for _, e := range entries { + if e.Kind == store.IntakeEntryCapture { + v.Handover = e.Status() + } + } + return v, nil +} + +// listIntakeReports is GET /v1/tenants/{id}/intake/reports: the caller's +// own reports, newest first. +func (s *Server) listIntakeReports(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + p, t, ok := s.intakeUser(ctx, w, r) + if !ok { + return + } + reps, err := s.Store.ListIntakeReports(ctx, t.ID, p.Subject) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + out := []intakeReportView{} + for i := range reps { + v, err := s.intakeView(ctx, &reps[i]) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + v.Entries = nil + out = append(out, v) + } + writeJSON(w, http.StatusOK, map[string]any{"items": out}) +} + +// getIntakeReport is GET /v1/tenants/{id}/intake/reports/{ref}. +func (s *Server) getIntakeReport(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + _, rep, ok := s.ownIntakeReport(ctx, w, r) + if !ok { + return + } + v, err := s.intakeView(ctx, rep) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, v) +} + +// addIntakeSupplement is POST /v1/tenants/{id}/intake/reports/{ref}/supplements: +// later information to the same reference (M13). +func (s *Server) addIntakeSupplement(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + r.Body = http.MaxBytesReader(w, r.Body, maxIntakeBody) + var in intakeSupplementReq + if !decodeJSON(w, r, &in) { + return + } + what, ok := field(in.What, intakeWhatMax, true) + if !ok { + writeError(w, http.StatusBadRequest, "invalid_what", "the supplement is required, at most 20000 characters") + return + } + p, rep, ok := s.ownIntakeReport(ctx, w, r) + if !ok { + return + } + raw, _ := json.Marshal(map[string]string{"what": what}) + e, err := s.Store.AddIntakeSupplement(ctx, rep.TenantID, rep.Reference, p.Subject, raw, s.now()) + if err != nil { + if !mapStoreError(w, err) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + } + return + } + s.Log.Info("intake supplement recorded", "tenant_id", rep.TenantID, "reference", rep.Reference, "entry", e.ID) + writeJSON(w, http.StatusCreated, map[string]any{"reference": rep.Reference, "entry": e}) +} + +// serviceOnly refuses a person's token on the internal intake routes. +func serviceOnly(w http.ResponseWriter, r *http.Request) (*authn.Principal, bool) { + p, has := authn.PrincipalFrom(r.Context()) + if has && p.IsUser() { + writeError(w, http.StatusForbidden, "service_token_required", "only the receiving service reads the intake queue") + return nil, false + } + return p, true +} + +// pendingIntake is GET /v1/internal/intake/pending?limit=: entries not +// settled yet, oldest first, across workspaces. +func (s *Server) pendingIntake(w http.ResponseWriter, r *http.Request) { + if _, ok := serviceOnly(w, r); !ok { + return + } + limit := 50 + if v := r.URL.Query().Get("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 || n > intakePendingMax { + writeError(w, http.StatusBadRequest, "invalid_limit", "limit is 1 to 200") + return + } + limit = n + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + items, err := s.Store.PendingIntake(ctx, limit) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"items": items}) +} + +// addIntakeReceipt is POST /v1/internal/intake/entries/{entry}/receipts. +// A receipt that repeats the newest one is 200 and adds nothing; after +// processed or refused the entry takes no receipt (409). +func (s *Server) addIntakeReceipt(w http.ResponseWriter, r *http.Request) { + p, ok := serviceOnly(w, r) + if !ok { + return + } + id, err := strconv.ParseInt(r.PathValue("entry"), 10, 64) + if err != nil || id < 1 { + writeError(w, http.StatusNotFound, "not_found", "resource does not exist") + return + } + r.Body = http.MaxBytesReader(w, r.Body, 4096) + var in intakeReceiptReq + if !decodeJSON(w, r, &in) { + return + } + by := "unauthenticated" + if p != nil { + by = p.ClientID + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + added, err := s.Store.AddIntakeReceipt(ctx, store.IntakeReceipt{EntryID: id, Status: in.Status, Reason: in.Reason, + HandoffID: in.HandoffID, RunID: in.RunID, By: by, At: s.now()}) + switch { + case errors.Is(err, store.ErrConflict): + writeError(w, http.StatusConflict, "settled", "the entry is settled and takes no further receipt") + case errors.Is(err, store.ErrInvalidInput): + writeError(w, http.StatusBadRequest, "invalid_receipt", "status is waiting, delivered, processed or refused; reason, handoff_id and run_id at most 80 characters") + case err != nil: + if !mapStoreError(w, err) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + } + case added: + writeJSON(w, http.StatusCreated, map[string]any{"added": true}) + default: + writeJSON(w, http.StatusOK, map[string]any{"added": false}) + } +} diff --git a/internal/server/intake_store_test.go b/internal/server/intake_store_test.go new file mode 100644 index 0000000..b737101 --- /dev/null +++ b/internal/server/intake_store_test.go @@ -0,0 +1,134 @@ +package server_test + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// The intake store on both stores: references in order, entries and +// receipts in order, what is pending, settled entries and unknown ones. +func TestIntakeStore(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + ctx := context.Background() + at := time.Date(2026, 11, 10, 9, 30, 0, 123456789, time.UTC) + capture := func(sub, about string) (*store.IntakeReport, *store.IntakeEntry) { + t.Helper() + r, e, err := h.store.CreateIntakeReport(ctx, store.IntakeCapture{TenantID: h.tenant.ID, Channel: store.IntakeChannelPortal, + ReporterSub: sub, About: about, Danger: "no", Original: json.RawMessage(`{"what":"x"}`), At: at}) + if err != nil { + t.Fatal(err) + } + return r, e + } + r1, e1 := capture("u-1", store.IntakeAboutProduct) + r2, e2 := capture("u-2", store.IntakeAboutITOT) + r3, _ := capture("u-1", store.IntakeAboutUnknown) + if r1.Reference != "SH-2026-00001" || r2.Reference != "SH-2026-00002" || r3.Reference != "SH-2026-00003" || + !r1.ReceivedAt.Equal(at.Truncate(time.Microsecond)) || e1.Kind != store.IntakeEntryCapture { + t.Fatalf("references: %+v %+v %+v", r1, r2, r3) + } + got, err := h.store.GetIntakeReport(ctx, h.tenant.ID, r1.Reference) + if err != nil || got.ReporterSub != "u-1" || got.About != store.IntakeAboutProduct || got.Danger != "no" || got.Channel != "portal" { + t.Fatalf("get: %+v %v", got, err) + } + mine, err := h.store.ListIntakeReports(ctx, h.tenant.ID, "u-1") + if err != nil || len(mine) != 2 || mine[0].Reference != r3.Reference || mine[1].Reference != r1.Reference { + t.Fatalf("u-1's reports: %+v %v", mine, err) + } + s1, err := h.store.AddIntakeSupplement(ctx, h.tenant.ID, r1.Reference, "u-1", json.RawMessage(`{"what":"y"}`), at.Add(time.Hour)) + if err != nil || s1.Kind != store.IntakeEntrySupplement || s1.ID <= e2.ID { + t.Fatalf("supplement: %+v %v", s1, err) + } + + receipt := func(id int64, status, reason string) (bool, error) { + return h.store.AddIntakeReceipt(ctx, store.IntakeReceipt{EntryID: id, Status: status, Reason: reason, By: "werkmeister-svc", At: at}) + } + for _, c := range []struct { + id int64 + status, reason string + added bool + err error + }{ + {e1.ID, store.IntakeWaiting, "target_unknown", true, nil}, + {e1.ID, store.IntakeWaiting, "target_unknown", false, nil}, + {e1.ID, store.IntakeWaiting, "target_ambiguous", true, nil}, + {e1.ID, store.IntakeProcessed, "", true, nil}, + {e1.ID, store.IntakeRefused, "", false, store.ErrConflict}, + {e2.ID, store.IntakeRefused, "not_accepted", true, nil}, + {e2.ID, store.IntakeWaiting, "", false, store.ErrConflict}, + {e2.ID, "lost", "", false, store.ErrInvalidInput}, + {999999, store.IntakeWaiting, "", false, store.ErrNotFound}, + } { + added, err := receipt(c.id, c.status, c.reason) + if added != c.added || !errors.Is(err, c.err) && !(c.err == nil && err == nil) { + t.Fatalf("%d %s %s: %v %v", c.id, c.status, c.reason, added, err) + } + } + entries, err := h.store.IntakeEntries(ctx, h.tenant.ID, r1.Reference) + if err != nil || len(entries) != 2 || entries[0].Status() != store.IntakeProcessed || len(entries[0].Receipts) != 3 || + entries[0].Receipts[1].Reason != "target_ambiguous" || entries[1].Status() != "" || string(entries[0].Content) == "" { + t.Fatalf("entries: %+v %v", entries, err) + } + pending, err := h.store.PendingIntake(ctx, 10) + if err != nil || len(pending) != 2 || pending[0].Reference != r3.Reference || pending[1].EntryID != s1.ID || + pending[1].About != store.IntakeAboutProduct || !pending[1].ReceivedAt.Equal(r1.ReceivedAt) { + t.Fatalf("pending: %+v %v", pending, err) + } + if p, _ := h.store.PendingIntake(ctx, 1); len(p) != 1 { + t.Fatalf("limit: %+v", p) + } + if _, err := receipt(s1.ID, store.IntakeDelivered, ""); err != nil { + t.Fatal(err) + } + if p, _ := h.store.PendingIntake(ctx, 10); p[1].Status != store.IntakeDelivered { + t.Fatalf("pending status: %+v", p) + } + + for name, err := range map[string]error{ + "unknown report": func() error { _, err := h.store.GetIntakeReport(ctx, h.tenant.ID, "SH-2026-00099"); return err }(), + "bad tenant": func() error { _, err := h.store.GetIntakeReport(ctx, "not-a-uuid", r1.Reference); return err }(), + "entries": func() error { _, err := h.store.IntakeEntries(ctx, h.tenant.ID, "SH-2026-00099"); return err }(), + "supplement": func() error { + _, err := h.store.AddIntakeSupplement(ctx, h.tenant.ID, "SH-2026-00099", "u-1", json.RawMessage(`{}`), at) + return err + }(), + "unknown tenant": func() error { + _, _, err := h.store.CreateIntakeReport(ctx, store.IntakeCapture{TenantID: "00000000-0000-0000-0000-00000000beef", + Channel: "portal", ReporterSub: "u", About: "unknown", Danger: "no", Original: json.RawMessage(`{}`), At: at}) + return err + }(), + } { + if !errors.Is(err, store.ErrNotFound) { + t.Fatalf("%s: %v", name, err) + } + } + for name, c := range map[string]store.IntakeCapture{ + "channel": {TenantID: h.tenant.ID, Channel: "mail", ReporterSub: "u", About: "unknown", Danger: "no", Original: json.RawMessage(`{}`)}, + "about": {TenantID: h.tenant.ID, Channel: "portal", ReporterSub: "u", About: "x", Danger: "no", Original: json.RawMessage(`{}`)}, + "danger": {TenantID: h.tenant.ID, Channel: "portal", ReporterSub: "u", About: "unknown", Danger: "x", Original: json.RawMessage(`{}`)}, + "reporter": {TenantID: h.tenant.ID, Channel: "portal", About: "unknown", Danger: "no", Original: json.RawMessage(`{}`)}, + "original": {TenantID: h.tenant.ID, Channel: "portal", ReporterSub: "u", About: "unknown", Danger: "no", Original: json.RawMessage(`[]`)}, + } { + if _, _, err := h.store.CreateIntakeReport(ctx, c); !errors.Is(err, store.ErrInvalidInput) { + t.Fatalf("%s: %v", name, err) + } + } + if _, err := h.store.AddIntakeSupplement(ctx, h.tenant.ID, r1.Reference, "", json.RawMessage(`{}`), at); !errors.Is(err, store.ErrInvalidInput) { + t.Fatalf("supplement without author: %v", err) + } + if l, err := h.store.ListIntakeReports(ctx, "not-a-uuid", "u-1"); err != nil || len(l) != 0 { + t.Fatalf("list of a bad tenant: %v %v", l, err) + } + if err := h.store.DeleteTenant(ctx, h.tenant.ID); err != nil { + t.Fatal(err) + } + if p, err := h.store.PendingIntake(ctx, 10); err != nil || len(p) != 0 { + t.Fatalf("after the tenant is purged: %+v %v", p, err) + } + }) +} diff --git a/internal/server/intake_test.go b/internal/server/intake_test.go new file mode 100644 index 0000000..db7862d --- /dev/null +++ b/internal/server/intake_test.go @@ -0,0 +1,190 @@ +package server + +import ( + "net/http" + "strings" + "testing" + "time" +) + +// intakeFixture: the role fixture with the stage rules this slice adds. +func intakeFixture(t *testing.T) *roleFixture { + t.Helper() + f := newRoleFixture(t) + f.s.Authz = ParseAuthzRules("portal-svc:tenants,users;portal-stage:role-dataset.user,intake.user;werkmeister-svc:tenants.read,intake") + return f +} + +func (f *roleFixture) intake(sub string) string { + return "/v1/tenants/" + f.tenant.ID + "/intake/reports" + sub +} + +const secretText = "Steuerung X-1 antwortet auf Port 502 ohne Anmeldung" + +// A person reports with a description only; the report gets the next +// reference, which the confirmation shows. Later information goes to the +// same reference. Only the reporter sees the report, and only its state. +func TestIntakeReportAndSupplement(t *testing.T) { + f := intakeFixture(t) + year := time.Now().UTC().Format("2006") + + code, out, raw := f.do(t, "staff", "POST", f.intake(""), `{"danger":"no","what":" `+secretText+` "}`) + if code != http.StatusCreated || out["reference"] != "SH-"+year+"-00001" || out["about"] != "unknown" || out["received_at"] == nil { + t.Fatalf("report: %d %s", code, raw) + } + ref := out["reference"].(string) + if code, out, raw := f.do(t, "ceo", "POST", f.intake(""), `{"danger":"yes","about":"product","what":"x","where":"Halle 2","contact":"Durchwahl 12"}`); code != http.StatusCreated || out["reference"] != "SH-"+year+"-00002" { + t.Fatalf("second report: %d %s", code, raw) + } + + code, out, raw = f.do(t, "staff", "GET", f.intake("/"+ref), "") + if code != http.StatusOK || out["handover"] != "" || len(out["entries"].([]any)) != 1 || strings.Contains(raw, "Port 502") { + t.Fatalf("own report: %d %s", code, raw) + } + for _, who := range []string{"ceo", "itadmin", "stranger"} { + if code, _, raw := f.do(t, who, "GET", f.intake("/"+ref), ""); code != http.StatusNotFound { + t.Fatalf("%s reads the report: %d %s", who, code, raw) + } + if code, _, _ := f.do(t, who, "POST", f.intake("/"+ref+"/supplements"), `{"what":"y"}`); code != http.StatusNotFound { + t.Fatalf("%s adds to it: %d", who, code) + } + } + if code, out, _ := f.do(t, "ceo", "GET", f.intake(""), ""); code != http.StatusOK || len(out["items"].([]any)) != 1 { + t.Fatalf("ceo's own list: %d %v", code, out) + } + + code, out, raw = f.do(t, "staff", "POST", f.intake("/"+ref+"/supplements"), `{"what":"Auch Port 102 offen"}`) + if code != http.StatusCreated || out["reference"] != ref || out["entry"].(map[string]any)["kind"] != "supplement" { + t.Fatalf("supplement: %d %s", code, raw) + } + code, out, _ = f.do(t, "staff", "GET", f.intake(""), "") + items := out["items"].([]any) + if code != http.StatusOK || len(items) != 1 || items[0].(map[string]any)["reference"] != ref || items[0].(map[string]any)["entries"] != nil { + t.Fatalf("one report, not two: %d %v", code, out) + } + if code, _, _ := f.do(t, "staff", "POST", f.intake("/SH-"+year+"-00099/supplements"), `{"what":"y"}`); code != http.StatusNotFound { + t.Fatalf("unknown reference: %d", code) + } +} + +func TestIntakeReportIsChecked(t *testing.T) { + f := intakeFixture(t) + long := strings.Repeat("x", 501) + for name, c := range map[string]struct { + as, body, err string + code int + }{ + "no danger": {"staff", `{"what":"x"}`, "invalid_danger", http.StatusBadRequest}, + "bad danger": {"staff", `{"danger":"vielleicht","what":"x"}`, "invalid_danger", http.StatusBadRequest}, + "bad about": {"staff", `{"danger":"no","about":"cloud","what":"x"}`, "invalid_about", http.StatusBadRequest}, + "no what": {"staff", `{"danger":"no","what":" "}`, "invalid_what", http.StatusBadRequest}, + "long what": {"staff", `{"danger":"no","what":"` + strings.Repeat("x", 20001) + `"}`, "invalid_what", http.StatusBadRequest}, + "long where": {"staff", `{"danger":"no","what":"x","where":"` + long + `"}`, "invalid_where", http.StatusBadRequest}, + "not json": {"staff", `{`, "invalid_body", http.StatusBadRequest}, + "service": {"werkmeister", `{"danger":"no","what":"x"}`, "FORBIDDEN_CLIENT", http.StatusForbidden}, + "other tenant": {"stranger", `{"danger":"no","what":"x"}`, "not_found", http.StatusNotFound}, + } { + code, _, raw := f.do(t, c.as, "POST", f.intake(""), c.body) + if code != c.code || !strings.Contains(raw, c.err) { + t.Fatalf("%s: %d %s", name, code, raw) + } + } + if code, _, raw := f.do(t, "staff", "POST", f.intake("/x/supplements"), `{"what":""}`); code != http.StatusBadRequest || !strings.Contains(raw, "invalid_what") { + t.Fatalf("empty supplement: %d %s", code, raw) + } + // Without the intake.user grant the portal's sign-in client reaches no + // intake route. + f.s.Authz = ParseAuthzRules("portal-stage:role-dataset.user") + if code, _, raw := f.do(t, "staff", "POST", f.intake(""), `{"danger":"no","what":"x"}`); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_CLIENT") { + t.Fatalf("without grant: %d %s", code, raw) + } + // Without rules (dev) a service token still cannot report. + f.s.Authz = nil + if code, _, raw := f.do(t, "werkmeister", "POST", f.intake(""), `{"danger":"no","what":"x"}`); code != http.StatusForbidden || !strings.Contains(raw, "user_token_required") { + t.Fatalf("service without rules: %d %s", code, raw) + } +} + +// Werkmeister reads what is not settled, without the text, and says what +// became of each entry; the reporter sees the handover state. +func TestIntakeIsTakenOver(t *testing.T) { + f := intakeFixture(t) + _, out, _ := f.do(t, "staff", "POST", f.intake(""), `{"danger":"unknown","about":"product","what":"`+secretText+`"}`) + ref := out["reference"].(string) + f.do(t, "staff", "POST", f.intake("/"+ref+"/supplements"), `{"what":"Nachtrag zu Port 502"}`) + + code, out, raw := f.do(t, "werkmeister", "GET", "/v1/internal/intake/pending?limit=10", "") + items, _ := out["items"].([]any) + if code != http.StatusOK || len(items) != 2 || strings.Contains(raw, "Port 502") { + t.Fatalf("pending: %d %s", code, raw) + } + first := items[0].(map[string]any) + if first["reference"] != ref || first["kind"] != "capture" || first["about"] != "product" || first["danger"] != "unknown" || first["tenant_id"] != f.tenant.ID { + t.Fatalf("pending capture: %v", first) + } + entry := "/v1/internal/intake/entries/" + itoa(int(first["entry_id"].(float64))) + "/receipts" + for _, c := range []struct { + body string + code int + }{ + {`{"status":"waiting","reason":"target_unknown"}`, http.StatusCreated}, + {`{"status":"waiting","reason":"target_unknown"}`, http.StatusOK}, + {`{"status":"delivered","handoff_id":"h-1"}`, http.StatusCreated}, + {`{"status":"processed","handoff_id":"h-1","run_id":"r-1"}`, http.StatusCreated}, + {`{"status":"processed","handoff_id":"h-1","run_id":"r-1"}`, http.StatusConflict}, + {`{"status":"refused"}`, http.StatusConflict}, + } { + if code, _, raw := f.do(t, "werkmeister", "POST", entry, c.body); code != c.code { + t.Fatalf("%s: %d %s", c.body, code, raw) + } + } + _, out, _ = f.do(t, "werkmeister", "GET", "/v1/internal/intake/pending", "") + if items := out["items"].([]any); len(items) != 1 || items[0].(map[string]any)["kind"] != "supplement" { + t.Fatalf("pending after processing: %v", out) + } + _, out, raw = f.do(t, "staff", "GET", f.intake("/"+ref), "") + receipts := out["entries"].([]any)[0].(map[string]any)["receipts"].([]any) + if out["handover"] != "processed" || len(receipts) != 3 || receipts[0].(map[string]any)["reason"] != "target_unknown" { + t.Fatalf("reporter's view: %s", raw) + } + + for name, c := range map[string]struct { + as, method, path, body string + code int + }{ + "bad status": {"werkmeister", "POST", entry, `{"status":"done"}`, http.StatusBadRequest}, + "bad status2": {"werkmeister", "POST", "/v1/internal/intake/entries/2/receipts", `{"status":"done"}`, http.StatusBadRequest}, + "long reason": {"werkmeister", "POST", "/v1/internal/intake/entries/2/receipts", `{"status":"waiting","reason":"` + strings.Repeat("r", 81) + `"}`, http.StatusBadRequest}, + "unknown": {"werkmeister", "POST", "/v1/internal/intake/entries/99/receipts", `{"status":"waiting"}`, http.StatusNotFound}, + "not an id": {"werkmeister", "POST", "/v1/internal/intake/entries/x/receipts", `{"status":"waiting"}`, http.StatusNotFound}, + "not json": {"werkmeister", "POST", "/v1/internal/intake/entries/2/receipts", `{`, http.StatusBadRequest}, + "limit": {"werkmeister", "GET", "/v1/internal/intake/pending?limit=201", "", http.StatusBadRequest}, + "user": {"staff", "GET", "/v1/internal/intake/pending", "", http.StatusForbidden}, + "portal svc": {"portal", "GET", "/v1/internal/intake/pending", "", http.StatusForbidden}, + } { + if code, _, raw := f.do(t, c.as, c.method, c.path, c.body); code != c.code { + t.Fatalf("%s: %d %s", name, code, raw) + } + } + f.s.Authz = nil + if code, _, raw := f.do(t, "staff", "GET", "/v1/internal/intake/pending", ""); code != http.StatusForbidden || !strings.Contains(raw, "service_token_required") { + t.Fatalf("user without rules: %d %s", code, raw) + } + if code, _, _ := f.do(t, "staff", "POST", "/v1/internal/intake/entries/2/receipts", `{"status":"waiting"}`); code != http.StatusForbidden { + t.Fatalf("user receipt without rules: %d", code) + } +} + +func TestIntakePaths(t *testing.T) { + for path, want := range map[string]bool{ + "/v1/tenants/t/intake/reports": true, "/v1/tenants/t/intake": true, + "/v1/tenants/t/role-dataset": false, "/v1/internal/intake/pending": false, "/v1/tenants/t": false, + } { + if isIntakeUserPath(path) != want { + t.Fatalf("%s", path) + } + } + if routeGroup("GET", "/v1/internal/intake/pending") != "intake" { + t.Fatal("route group") + } +} diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index e87b6d1..38e02a2 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -52,6 +52,12 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"}, {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/revisions/2"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports/SH-2026-00001"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports/SH-2026-00001/supplements"}, + {"GET", "/v1/internal/intake/pending?limit=10"}, + {"POST", "/v1/internal/intake/entries/1/receipts"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/resolve?decision_type=r1.release_d01"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"}, {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"}, diff --git a/internal/server/server.go b/internal/server/server.go index f5fcf70..5edba43 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -162,6 +162,13 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/revisions/{rev}", s.getRoleDatasetRevision) mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/resolve", s.resolveRoleDataset) // Prüfwerk settings (0025, t72): the workspace's Prüftag cap. + // R1 intake (0028, docgen#6 F01): intake.go. + mux.HandleFunc("POST /v1/tenants/{id}/intake/reports", s.createIntakeReport) + mux.HandleFunc("GET /v1/tenants/{id}/intake/reports", s.listIntakeReports) + mux.HandleFunc("GET /v1/tenants/{id}/intake/reports/{ref}", s.getIntakeReport) + mux.HandleFunc("POST /v1/tenants/{id}/intake/reports/{ref}/supplements", s.addIntakeSupplement) + mux.HandleFunc("GET /v1/internal/intake/pending", s.pendingIntake) + mux.HandleFunc("POST /v1/internal/intake/entries/{entry}/receipts", s.addIntakeReceipt) mux.HandleFunc("GET /v1/tenants/{id}/products/pruefwerk/settings", s.getPruefwerkSettings) mux.HandleFunc("PUT /v1/tenants/{id}/products/pruefwerk/settings", s.putPruefwerkSettings) diff --git a/internal/store/intake.go b/internal/store/intake.go new file mode 100644 index 0000000..fc8db2b --- /dev/null +++ b/internal/store/intake.go @@ -0,0 +1,111 @@ +package store + +import ( + "encoding/json" + "fmt" + "time" +) + +// R1 intake (0028, docgen#6 F01): the original capture of a security +// notice, its supplements and what became of each downstream. Nothing is +// ever changed. + +// Intake channels, what a report is about by the reporter's own account, and +// the reporter's answer to "immediate danger to people?". +const ( + IntakeChannelPortal = "portal" + + IntakeAboutProduct = "product" + IntakeAboutITOT = "it_ot" + IntakeAboutUnknown = "unknown" + + IntakeEntryCapture = "capture" + IntakeEntrySupplement = "supplement" + + IntakeWaiting = "waiting" + IntakeDelivered = "delivered" + IntakeProcessed = "processed" + IntakeRefused = "refused" +) + +// IntakeReference is the Eingangsreferenz of a tenant's seq-th report, +// received at. +func IntakeReference(at time.Time, seq int) string { + return fmt.Sprintf("SH-%04d-%05d", at.UTC().Year(), seq) +} + +// IntakeReport is one report: its reference, the time of the first R1 +// capture, the channel, the reporter and the reporter's own answers. +type IntakeReport struct { + TenantID string `json:"tenant_id"` + Reference string `json:"reference"` + ReceivedAt time.Time `json:"received_at"` + Channel string `json:"channel"` + ReporterSub string `json:"-"` + About string `json:"about"` + Danger string `json:"danger"` +} + +// IntakeEntry is the capture or a supplement, with its receipts, oldest +// first. Content is the original as entered. +type IntakeEntry struct { + ID int64 `json:"id"` + TenantID string `json:"-"` + Reference string `json:"-"` + Kind string `json:"kind"` + Content json.RawMessage `json:"-"` + By string `json:"-"` + At time.Time `json:"at"` + Receipts []IntakeReceipt `json:"receipts"` +} + +// Status is the newest receipt's status, "" before the first one. +func (e IntakeEntry) Status() string { + if len(e.Receipts) == 0 { + return "" + } + return e.Receipts[len(e.Receipts)-1].Status +} + +// IntakeReceipt is what became of an entry downstream. +type IntakeReceipt struct { + EntryID int64 `json:"-"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` + HandoffID string `json:"handoff_id,omitempty"` + RunID string `json:"run_id,omitempty"` + By string `json:"-"` + At time.Time `json:"at"` +} + +// Settled: processed or refused, after which no receipt follows. +func (r IntakeReceipt) Settled() bool { + return r.Status == IntakeProcessed || r.Status == IntakeRefused +} + +// IntakeCapture records a new report. +type IntakeCapture struct { + TenantID string + Channel string + ReporterSub string + About string + Danger string + Original json.RawMessage + At time.Time +} + +// PendingIntake is an entry not settled yet, with what routing reads of its +// report; never its content. +type PendingIntake struct { + EntryID int64 `json:"entry_id"` + TenantID string `json:"tenant_id"` + Reference string `json:"reference"` + Kind string `json:"kind"` + At time.Time `json:"at"` + ReceivedAt time.Time `json:"received_at"` + Channel string `json:"channel"` + About string `json:"about"` + Danger string `json:"danger"` + Status string `json:"status,omitempty"` + Reason string `json:"reason,omitempty"` +} diff --git a/internal/store/memory.go b/internal/store/memory.go index 82e7f54..942bf2b 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -48,8 +48,13 @@ type Memory struct { prodSets map[string]*TenantProductSettings // tenant_id + "/" + product (0025) - contractDocs []ContractDocument // every row, oldest first (0027) - contractDocID int64 + contractDocs []ContractDocument // every row, oldest first (0027) + + intakeReports []IntakeReport // every report, oldest first (0028) + intakeEntries []IntakeEntry // every entry with its receipts, oldest first + intakeCounters map[string]int // tenant_id → last seq + intakeEntryID int64 + contractDocID int64 } type apiKeyWithHash struct { @@ -61,23 +66,24 @@ type apiKeyWithHash struct { // NewMemory returns a fresh in-memory store with the seed acme tenant. func NewMemory() *Memory { m := &Memory{ - tenants: make(map[string]*Tenant), - bySlug: make(map[string]string), - products: make(map[string]map[string]*TenantProduct), - apiKeys: make(map[string]*apiKeyWithHash), - catalog: DefaultProducts(), - subs: make(map[string]*Subscription), - usageKey: make(map[string]int64), - receipts: make(map[string]time.Time), - licences: make(map[string]*Licence), - projects: make(map[string]*Project), - offers: make(map[string]*TrialOffer), - services: make(map[string]*ManagedService), - profiles: make(map[string]*CompanyProfile), - preparations: make(map[string]*Preparation), - assets: make(map[string]*StoreAsset), - profRevs: make(map[string][]CompanyProfile), - roleSets: make(map[string][]RoleDataset), + tenants: make(map[string]*Tenant), + bySlug: make(map[string]string), + products: make(map[string]map[string]*TenantProduct), + apiKeys: make(map[string]*apiKeyWithHash), + catalog: DefaultProducts(), + subs: make(map[string]*Subscription), + usageKey: make(map[string]int64), + receipts: make(map[string]time.Time), + licences: make(map[string]*Licence), + projects: make(map[string]*Project), + offers: make(map[string]*TrialOffer), + services: make(map[string]*ManagedService), + profiles: make(map[string]*CompanyProfile), + preparations: make(map[string]*Preparation), + assets: make(map[string]*StoreAsset), + profRevs: make(map[string][]CompanyProfile), + roleSets: make(map[string][]RoleDataset), + intakeCounters: make(map[string]int), documents: make(map[string]*Document), prodSets: make(map[string]*TenantProductSettings), @@ -607,6 +613,7 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { } } m.contractDocs = kept + m.deleteIntake(id) for kid, k := range m.apiKeys { if k.TenantID == id { delete(m.apiKeys, kid) diff --git a/internal/store/memory_intake.go b/internal/store/memory_intake.go new file mode 100644 index 0000000..d2652be --- /dev/null +++ b/internal/store/memory_intake.go @@ -0,0 +1,170 @@ +package store + +import ( + "context" + "encoding/json" + "slices" + "time" +) + +func validCapture(c IntakeCapture) bool { + return c.Channel == IntakeChannelPortal && c.ReporterSub != "" && len(c.ReporterSub) <= 200 && + slices.Contains([]string{IntakeAboutProduct, IntakeAboutITOT, IntakeAboutUnknown}, c.About) && + slices.Contains([]string{"yes", "no", "unknown"}, c.Danger) && isJSONObject(c.Original) +} + +func validReceipt(r IntakeReceipt) bool { + return slices.Contains([]string{IntakeWaiting, IntakeDelivered, IntakeProcessed, IntakeRefused}, r.Status) && + len(r.Reason) <= 80 && len(r.HandoffID) <= 80 && len(r.RunID) <= 80 && r.By != "" && len(r.By) <= 200 +} + +func isJSONObject(b json.RawMessage) bool { + var v map[string]any + return json.Unmarshal(b, &v) == nil && v != nil +} + +func (m *Memory) CreateIntakeReport(_ context.Context, c IntakeCapture) (*IntakeReport, *IntakeEntry, error) { + if !validCapture(c) { + return nil, nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[c.TenantID]; !ok { + return nil, nil, ErrNotFound + } + m.intakeCounters[c.TenantID]++ + at := c.At.UTC().Truncate(time.Microsecond) + r := IntakeReport{TenantID: c.TenantID, Reference: IntakeReference(at, m.intakeCounters[c.TenantID]), ReceivedAt: at, + Channel: c.Channel, ReporterSub: c.ReporterSub, About: c.About, Danger: c.Danger} + m.intakeReports = append(m.intakeReports, r) + e := m.addEntry(c.TenantID, r.Reference, IntakeEntryCapture, c.ReporterSub, c.Original, at) + return &r, &e, nil +} + +func (m *Memory) addEntry(tenantID, ref, kind, by string, content json.RawMessage, at time.Time) IntakeEntry { + m.intakeEntryID++ + e := IntakeEntry{ID: m.intakeEntryID, TenantID: tenantID, Reference: ref, Kind: kind, + Content: append(json.RawMessage(nil), content...), By: by, At: at, Receipts: []IntakeReceipt{}} + m.intakeEntries = append(m.intakeEntries, e) + return e +} + +func (m *Memory) report(tenantID, ref string) (IntakeReport, bool) { + for _, r := range m.intakeReports { + if r.TenantID == tenantID && r.Reference == ref { + return r, true + } + } + return IntakeReport{}, false +} + +func (m *Memory) GetIntakeReport(_ context.Context, tenantID, ref string) (*IntakeReport, error) { + m.mu.RLock() + defer m.mu.RUnlock() + r, ok := m.report(tenantID, ref) + if !ok { + return nil, ErrNotFound + } + return &r, nil +} + +func (m *Memory) ListIntakeReports(_ context.Context, tenantID, reporterSub string) ([]IntakeReport, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []IntakeReport{} + for i := len(m.intakeReports) - 1; i >= 0; i-- { + if r := m.intakeReports[i]; r.TenantID == tenantID && r.ReporterSub == reporterSub { + out = append(out, r) + } + } + return out, nil +} + +func (m *Memory) IntakeEntries(_ context.Context, tenantID, ref string) ([]IntakeEntry, error) { + m.mu.RLock() + defer m.mu.RUnlock() + if _, ok := m.report(tenantID, ref); !ok { + return nil, ErrNotFound + } + out := []IntakeEntry{} + for _, e := range m.intakeEntries { + if e.TenantID == tenantID && e.Reference == ref { + e.Receipts = slices.Clone(e.Receipts) + out = append(out, e) + } + } + return out, nil +} + +func (m *Memory) AddIntakeSupplement(_ context.Context, tenantID, ref, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error) { + if by == "" || len(by) > 200 || !isJSONObject(content) { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.report(tenantID, ref); !ok { + return nil, ErrNotFound + } + e := m.addEntry(tenantID, ref, IntakeEntrySupplement, by, content, at.UTC().Truncate(time.Microsecond)) + return &e, nil +} + +func (m *Memory) PendingIntake(_ context.Context, limit int) ([]PendingIntake, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []PendingIntake{} + for _, e := range m.intakeEntries { + if len(out) >= limit { + break + } + if n := len(e.Receipts); n > 0 && e.Receipts[n-1].Settled() { + continue + } + r, _ := m.report(e.TenantID, e.Reference) + p := PendingIntake{EntryID: e.ID, TenantID: e.TenantID, Reference: e.Reference, Kind: e.Kind, At: e.At, + ReceivedAt: r.ReceivedAt, Channel: r.Channel, About: r.About, Danger: r.Danger} + if n := len(e.Receipts); n > 0 { + p.Status, p.Reason = e.Receipts[n-1].Status, e.Receipts[n-1].Reason + } + out = append(out, p) + } + return out, nil +} + +func (m *Memory) AddIntakeReceipt(_ context.Context, r IntakeReceipt) (bool, error) { + if !validReceipt(r) { + return false, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + for i := range m.intakeEntries { + e := &m.intakeEntries[i] + if e.ID != r.EntryID { + continue + } + if n := len(e.Receipts); n > 0 { + last := e.Receipts[n-1] + if last.Settled() { + return false, ErrConflict + } + if sameReceipt(last, r) { + return false, nil + } + } + r.At = r.At.UTC().Truncate(time.Microsecond) + e.Receipts = append(e.Receipts, r) + return true, nil + } + return false, ErrNotFound +} + +// sameReceipt: a receipt that repeats the newest one adds nothing. +func sameReceipt(a, b IntakeReceipt) bool { + return a.Status == b.Status && a.Reason == b.Reason && a.HandoffID == b.HandoffID && a.RunID == b.RunID +} + +func (m *Memory) deleteIntake(tenantID string) { + delete(m.intakeCounters, tenantID) + m.intakeReports = slices.DeleteFunc(m.intakeReports, func(r IntakeReport) bool { return r.TenantID == tenantID }) + m.intakeEntries = slices.DeleteFunc(m.intakeEntries, func(e IntakeEntry) bool { return e.TenantID == tenantID }) +} diff --git a/internal/store/postgres_intake.go b/internal/store/postgres_intake.go new file mode 100644 index 0000000..665532d --- /dev/null +++ b/internal/store/postgres_intake.go @@ -0,0 +1,229 @@ +package store + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/jackc/pgx/v5" +) + +const intakeReportSelect = ` +SELECT tenant_id::text, reference, received_at, channel, reporter_sub, about, danger FROM intake_reports ` + +func scanIntakeReport(row pgx.Row) (*IntakeReport, error) { + var r IntakeReport + if err := row.Scan(&r.TenantID, &r.Reference, &r.ReceivedAt, &r.Channel, &r.ReporterSub, &r.About, &r.Danger); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + return &r, nil +} + +// CreateIntakeReport takes the tenant's next number and writes the report +// and its capture in one transaction. +func (p *Postgres) CreateIntakeReport(ctx context.Context, c IntakeCapture) (*IntakeReport, *IntakeEntry, error) { + if !validCapture(c) { + return nil, nil, ErrInvalidInput + } + tx, err := p.pool.Begin(ctx) + if err != nil { + return nil, nil, err + } + defer func() { _ = tx.Rollback(ctx) }() + var seq int + err = tx.QueryRow(ctx, ` + INSERT INTO intake_counters (tenant_id, last) VALUES ($1::uuid, 1) + ON CONFLICT (tenant_id) DO UPDATE SET last = intake_counters.last + 1 + RETURNING last`, c.TenantID).Scan(&seq) + switch { + case isFKViolation(err), isInvalidUUID(err): + return nil, nil, ErrNotFound + case err != nil: + return nil, nil, err + } + at := c.At.UTC().Truncate(time.Microsecond) + r := &IntakeReport{TenantID: c.TenantID, Reference: IntakeReference(at, seq), ReceivedAt: at, Channel: c.Channel, + ReporterSub: c.ReporterSub, About: c.About, Danger: c.Danger} + if _, err := tx.Exec(ctx, ` + INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) + VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)`, + r.TenantID, r.Reference, seq, at, r.Channel, r.ReporterSub, r.About, r.Danger); err != nil { + if isCheckViolation(err) { + return nil, nil, ErrInvalidInput + } + return nil, nil, err + } + e, err := insertIntakeEntry(ctx, tx, c.TenantID, r.Reference, IntakeEntryCapture, c.ReporterSub, c.Original, at) + if err != nil { + return nil, nil, err + } + if err := tx.Commit(ctx); err != nil { + return nil, nil, err + } + return r, e, nil +} + +func insertIntakeEntry(ctx context.Context, q interface { + QueryRow(context.Context, string, ...any) pgx.Row +}, tenantID, ref, kind, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error) { + e := &IntakeEntry{TenantID: tenantID, Reference: ref, Kind: kind, Content: content, By: by, At: at, Receipts: []IntakeReceipt{}} + err := q.QueryRow(ctx, ` + INSERT INTO intake_entries (tenant_id, reference, kind, content, by_sub, at) + VALUES ($1::uuid, $2, $3, $4::jsonb, $5, $6) RETURNING id`, + tenantID, ref, kind, string(content), by, at).Scan(&e.ID) + switch { + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isCheckViolation(err): + return nil, ErrInvalidInput + case err != nil: + return nil, err + } + return e, nil +} + +func (p *Postgres) GetIntakeReport(ctx context.Context, tenantID, ref string) (*IntakeReport, error) { + r, err := scanIntakeReport(p.pool.QueryRow(ctx, intakeReportSelect+`WHERE tenant_id = $1::uuid AND reference = $2`, tenantID, ref)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return r, err +} + +func (p *Postgres) ListIntakeReports(ctx context.Context, tenantID, reporterSub string) ([]IntakeReport, error) { + rows, err := p.pool.Query(ctx, intakeReportSelect+`WHERE tenant_id = $1::uuid AND reporter_sub = $2 ORDER BY seq DESC`, tenantID, reporterSub) + if err != nil { + return nil, err + } + defer rows.Close() + out := []IntakeReport{} + for rows.Next() { + r, err := scanIntakeReport(rows) + if err != nil { + return nil, err + } + out = append(out, *r) + } + if err := rows.Err(); isInvalidUUID(err) { + return []IntakeReport{}, nil + } else if err != nil { + return nil, err + } + return out, nil +} + +func (p *Postgres) IntakeEntries(ctx context.Context, tenantID, ref string) ([]IntakeEntry, error) { + if _, err := p.GetIntakeReport(ctx, tenantID, ref); err != nil { + return nil, err + } + rows, err := p.pool.Query(ctx, ` + SELECT e.id, e.kind, e.content, e.by_sub, e.at, + r.status, r.reason, r.handoff_id, r.run_id, r.by_client, r.at + FROM intake_entries e LEFT JOIN intake_receipts r ON r.entry_id = e.id + WHERE e.tenant_id = $1::uuid AND e.reference = $2 + ORDER BY e.id, r.id`, tenantID, ref) + if err != nil { + return nil, err + } + defer rows.Close() + out := []IntakeEntry{} + for rows.Next() { + var e IntakeEntry + var content []byte + var st, reason, handoff, run, by *string + var at *time.Time + if err := rows.Scan(&e.ID, &e.Kind, &content, &e.By, &e.At, &st, &reason, &handoff, &run, &by, &at); err != nil { + return nil, err + } + if n := len(out); n == 0 || out[n-1].ID != e.ID { + e.TenantID, e.Reference, e.Content, e.Receipts = tenantID, ref, json.RawMessage(content), []IntakeReceipt{} + out = append(out, e) + } + if st != nil { + last := &out[len(out)-1] + last.Receipts = append(last.Receipts, IntakeReceipt{EntryID: e.ID, Status: *st, Reason: *reason, + HandoffID: *handoff, RunID: *run, By: *by, At: *at}) + } + } + return out, rows.Err() +} + +func (p *Postgres) AddIntakeSupplement(ctx context.Context, tenantID, ref, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error) { + if by == "" || len(by) > 200 || !isJSONObject(content) { + return nil, ErrInvalidInput + } + return insertIntakeEntry(ctx, p.pool, tenantID, ref, IntakeEntrySupplement, by, content, at.UTC().Truncate(time.Microsecond)) +} + +func (p *Postgres) PendingIntake(ctx context.Context, limit int) ([]PendingIntake, error) { + rows, err := p.pool.Query(ctx, ` + SELECT e.id, e.tenant_id::text, e.reference, e.kind, e.at, rp.received_at, rp.channel, rp.about, rp.danger, + COALESCE(last.status, ''), COALESCE(last.reason, '') + FROM intake_entries e + JOIN intake_reports rp ON rp.tenant_id = e.tenant_id AND rp.reference = e.reference + LEFT JOIN LATERAL (SELECT status, reason FROM intake_receipts WHERE entry_id = e.id ORDER BY id DESC LIMIT 1) last ON true + WHERE NOT EXISTS (SELECT 1 FROM intake_receipts s WHERE s.entry_id = e.id AND s.status IN ('processed', 'refused')) + ORDER BY e.id LIMIT $1`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []PendingIntake{} + for rows.Next() { + var x PendingIntake + if err := rows.Scan(&x.EntryID, &x.TenantID, &x.Reference, &x.Kind, &x.At, &x.ReceivedAt, &x.Channel, &x.About, &x.Danger, &x.Status, &x.Reason); err != nil { + return nil, err + } + out = append(out, x) + } + return out, rows.Err() +} + +// AddIntakeReceipt locks the entry so that two receipts never race past the +// settled check. +func (p *Postgres) AddIntakeReceipt(ctx context.Context, r IntakeReceipt) (bool, error) { + if !validReceipt(r) { + return false, ErrInvalidInput + } + tx, err := p.pool.Begin(ctx) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback(ctx) }() + var id int64 + if err := tx.QueryRow(ctx, `SELECT id FROM intake_entries WHERE id = $1`, r.EntryID).Scan(&id); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return false, ErrNotFound + } + return false, err + } + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended('intake_receipt', $1))`, r.EntryID); err != nil { + return false, err + } + var last IntakeReceipt + err = tx.QueryRow(ctx, `SELECT status, reason, handoff_id, run_id FROM intake_receipts WHERE entry_id = $1 ORDER BY id DESC LIMIT 1`, r.EntryID). + Scan(&last.Status, &last.Reason, &last.HandoffID, &last.RunID) + switch { + case errors.Is(err, pgx.ErrNoRows): + case err != nil: + return false, err + case last.Settled(): + return false, ErrConflict + case sameReceipt(last, r): + return false, nil + } + if _, err := tx.Exec(ctx, ` + INSERT INTO intake_receipts (entry_id, status, reason, handoff_id, run_id, by_client, at) + VALUES ($1, $2, $3, $4, $5, $6, $7)`, + r.EntryID, r.Status, r.Reason, r.HandoffID, r.RunID, r.By, r.At.UTC()); err != nil { + if isUniqueViolation(err) { + return false, ErrConflict + } + return false, err + } + return true, tx.Commit(ctx) +} diff --git a/internal/store/store.go b/internal/store/store.go index 6e840ab..5026369 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -6,6 +6,7 @@ package store import ( "context" + "encoding/json" "errors" "time" ) @@ -249,6 +250,23 @@ type Store interface { SaveRoleDataset(ctx context.Context, w RoleDatasetWrite) (dataset *RoleDataset, changed bool, err error) GetRoleDatasetRevision(ctx context.Context, tenantID string, revision int) (*RoleDataset, error) + // R1 intake (0028): CreateIntakeReport records a report and its capture + // entry under the tenant's next reference (ErrNotFound for an unknown + // tenant, ErrInvalidInput for a value out of range). GetIntakeReport and + // IntakeEntries are ErrNotFound for an unknown reference; + // ListIntakeReports lists one reporter's reports, newest first. + // AddIntakeSupplement adds a supplement. PendingIntake lists entries not + // settled yet, oldest first, across tenants. AddIntakeReceipt adds a + // receipt unless it repeats the newest one (added=false); ErrConflict + // once the entry is settled, ErrNotFound for an unknown entry. + CreateIntakeReport(ctx context.Context, c IntakeCapture) (*IntakeReport, *IntakeEntry, error) + GetIntakeReport(ctx context.Context, tenantID, reference string) (*IntakeReport, error) + ListIntakeReports(ctx context.Context, tenantID, reporterSub string) ([]IntakeReport, error) + IntakeEntries(ctx context.Context, tenantID, reference string) ([]IntakeEntry, error) + AddIntakeSupplement(ctx context.Context, tenantID, reference, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error) + PendingIntake(ctx context.Context, limit int) ([]PendingIntake, error) + AddIntakeReceipt(ctx context.Context, r IntakeReceipt) (added bool, err error) + // Product settings (0025): the workspace's own choices per product, // untouched by the ERP recompute. GetTenantProductSettings is // ErrNotFound when none were saved; PutTenantProductSettings replaces diff --git a/migrations/0028_intake.down.sql b/migrations/0028_intake.down.sql new file mode 100644 index 0000000..c398472 --- /dev/null +++ b/migrations/0028_intake.down.sql @@ -0,0 +1,5 @@ +DROP TABLE IF EXISTS intake_receipts; +DROP TABLE IF EXISTS intake_entries; +DROP TABLE IF EXISTS intake_reports; +DROP TABLE IF EXISTS intake_counters; +DROP FUNCTION IF EXISTS intake_immutable(); diff --git a/migrations/0028_intake.up.sql b/migrations/0028_intake.up.sql new file mode 100644 index 0000000..8d0c4e5 --- /dev/null +++ b/migrations/0028_intake.up.sql @@ -0,0 +1,69 @@ +-- R1 intake (docgen#6 F01, P-R1-K05 Fassung 4 M21): the one place where a +-- security notice is recorded, unchanged, at its first arrival in R1. Each +-- report gets one stable Eingangsreferenz; the Meldereferenz the reporting +-- person sees is the same string (F-1). Everything here is insert-only: a +-- correction or a later piece of information is a new entry (M13), and what +-- became of an entry downstream is a new receipt. +CREATE TABLE intake_counters ( + tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE, + last INTEGER NOT NULL CHECK (last >= 1) +); + +-- One row per report: the reference, the time of the first R1 capture, the +-- channel it came in by, who reported and the reporter's own answers that +-- routing reads (M16: what it is about; M05: immediate danger). The original +-- itself is the report's capture entry. +CREATE TABLE intake_reports ( + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + reference TEXT NOT NULL CHECK (reference ~ '^SH-[0-9]{4}-[0-9]{5,}$'), + seq INTEGER NOT NULL CHECK (seq >= 1), + received_at TIMESTAMPTZ NOT NULL, + channel TEXT NOT NULL CHECK (channel IN ('portal')), + reporter_sub TEXT NOT NULL CHECK (char_length(reporter_sub) BETWEEN 1 AND 200), + about TEXT NOT NULL CHECK (about IN ('product', 'it_ot', 'unknown')), + danger TEXT NOT NULL CHECK (danger IN ('yes', 'no', 'unknown')), + PRIMARY KEY (tenant_id, reference), + UNIQUE (tenant_id, seq) +); + +-- The capture (the original, unchanged) and every supplement (Nachtrag). +CREATE TABLE intake_entries ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + tenant_id UUID NOT NULL, + reference TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('capture', 'supplement')), + content JSONB NOT NULL CHECK (jsonb_typeof(content) = 'object'), + by_sub TEXT NOT NULL CHECK (char_length(by_sub) BETWEEN 1 AND 200), + at TIMESTAMPTZ NOT NULL, + FOREIGN KEY (tenant_id, reference) REFERENCES intake_reports(tenant_id, reference) ON DELETE CASCADE +); +CREATE INDEX intake_entries_report ON intake_entries (tenant_id, reference, id); +CREATE UNIQUE INDEX intake_entries_one_capture ON intake_entries (tenant_id, reference) WHERE kind = 'capture'; + +-- What became of an entry downstream (werkmeister, S-01/S-02): waiting (no +-- receiving process yet), delivered, processed or refused. Processed and +-- refused settle the entry. +CREATE TABLE intake_receipts ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + entry_id BIGINT NOT NULL REFERENCES intake_entries(id) ON DELETE CASCADE, + status TEXT NOT NULL CHECK (status IN ('waiting', 'delivered', 'processed', 'refused')), + reason TEXT NOT NULL DEFAULT '' CHECK (char_length(reason) <= 80), + handoff_id TEXT NOT NULL DEFAULT '' CHECK (char_length(handoff_id) <= 80), + run_id TEXT NOT NULL DEFAULT '' CHECK (char_length(run_id) <= 80), + by_client TEXT NOT NULL CHECK (char_length(by_client) BETWEEN 1 AND 200), + at TIMESTAMPTZ NOT NULL +); +CREATE INDEX intake_receipts_entry ON intake_receipts (entry_id, id); +CREATE UNIQUE INDEX intake_receipts_one_settled ON intake_receipts (entry_id) WHERE status IN ('processed', 'refused'); + +CREATE FUNCTION intake_immutable() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION '%: rows are never changed; insert a new one', TG_TABLE_NAME; +END $$ LANGUAGE plpgsql; + +CREATE TRIGGER intake_reports_immutable BEFORE UPDATE ON intake_reports + FOR EACH ROW EXECUTE FUNCTION intake_immutable(); +CREATE TRIGGER intake_entries_immutable BEFORE UPDATE ON intake_entries + FOR EACH ROW EXECUTE FUNCTION intake_immutable(); +CREATE TRIGGER intake_receipts_immutable BEFORE UPDATE ON intake_receipts + FOR EACH ROW EXECUTE FUNCTION intake_immutable(); diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 1a94854..f0e5b93 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "strconv" "strings" "testing" "time" @@ -123,8 +124,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { } } - // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents). - 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"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}} { + // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents; 0028: intake). + 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"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}, {"intake_reports", "danger"}, {"intake_entries", "content"}, {"intake_receipts", "handoff_id"}, {"intake_counters", "last"}} { 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)", @@ -336,11 +337,45 @@ func TestSeed_canInsertAndQuery(t *testing.T) { t.Error("a contract document row was changed") } + // 0028: the R1 intake, insert-only, one capture per report, one + // settling receipt per entry. + if _, err := db.ExecContext(ctx, `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) + VALUES ($1, 'SH-2026-00001', 1, now(), 'portal', 'u-1', 'product', 'no')`, tid); err != nil { + t.Fatalf("insert intake report: %v", err) + } + insEntry := `INSERT INTO intake_entries (tenant_id, reference, kind, content, by_sub, at) VALUES ($1, 'SH-2026-00001', $2, '{"what":"x"}', 'u-1', now()) RETURNING id` + var entryID int64 + if err := db.QueryRowContext(ctx, insEntry, tid, "capture").Scan(&entryID); err != nil { + t.Fatalf("insert intake capture: %v", err) + } + if _, err := db.ExecContext(ctx, insEntry, tid, "capture"); err == nil { + t.Error("a second capture of the same report was stored") + } + insReceipt := `INSERT INTO intake_receipts (entry_id, status, by_client, at) VALUES ($1, $2, 'werkmeister-svc', now())` + if _, err := db.ExecContext(ctx, insReceipt, entryID, "processed"); err != nil { + t.Fatalf("insert intake receipt: %v", err) + } + for name, stmt := range map[string]string{ + "second settling receipt": `INSERT INTO intake_receipts (entry_id, status, by_client, at) VALUES (` + strconv.FormatInt(entryID, 10) + `, 'refused', 'w', now())`, + "bad reference": `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) VALUES ('` + tid + `', 'X-1', 2, now(), 'portal', 'u', 'product', 'no')`, + "changed report": `UPDATE intake_reports SET danger = 'yes'`, + "changed entry": `UPDATE intake_entries SET content = '{}'`, + "changed receipt": `UPDATE intake_receipts SET status = 'refused'`, + } { + if _, err := db.ExecContext(ctx, stmt); err == nil { + t.Errorf("intake: %s was stored", name) + } + } + // FK cascade — delete tenant, projects/products/keys/audit_log handling. if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil { t.Fatalf("delete tenant: %v", err) } - var nServices, nSettings, nContractDocs int + var nServices, nSettings, nContractDocs, nIntake int + _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_entries WHERE tenant_id = $1`, tid).Scan(&nIntake) + if nIntake != 0 { + t.Errorf("FK cascade incomplete: intake_entries=%d", nIntake) + } _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices) _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_product_settings WHERE tenant_id = $1`, tid).Scan(&nSettings) _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_contract_documents WHERE tenant_id = $1`, tid).Scan(&nContractDocs) diff --git a/openapi.yaml b/openapi.yaml index c194d33..7b6a269 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -539,6 +539,138 @@ paths: "409": { description: "revision_conflict (with current_revision) or catalogue_outdated (with catalogue_version)." } "413": { description: The document exceeds 256 KiB (too_large). } + /v1/tenants/{id}/intake/reports: + post: + summary: Report a security notice (R1 intake, Originalerfassung). + description: | + Only with the token of the reporting person (`user_token_required` + otherwise; route group `intake.user`). The report is kept unchanged + with the time it arrived and gets one stable reference, which is also + the Meldereferenz of the confirmation. Only `what` and `danger` are + required; nothing asks for an assessment. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: { schema: { $ref: "#/components/schemas/IntakeReportWrite" } } + responses: + "201": + description: Recorded. + content: + application/json: { schema: { $ref: "#/components/schemas/IntakeReport" } } + "400": { description: "invalid_danger, invalid_about, invalid_what, invalid_when, invalid_where or invalid_contact." } + "403": { description: user_token_required. } + "404": { $ref: "#/components/responses/NotFound" } + get: + summary: The caller's own reports, newest first, with their handover state. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The reports. + content: + application/json: + schema: + type: object + properties: + items: { type: array, items: { $ref: "#/components/schemas/IntakeReport" } } + "403": { description: user_token_required. } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/intake/reports/{ref}: + get: + summary: One of the caller's reports, with every entry and its receipts; never the text. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: ref, required: true, schema: { type: string } } + responses: + "200": + description: The report. + content: + application/json: { schema: { $ref: "#/components/schemas/IntakeReport" } } + "403": { description: user_token_required. } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/intake/reports/{ref}/supplements: + post: + summary: Add later information to one of the caller's reports (Nachtrag, same reference). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: ref, required: true, schema: { type: string } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [what] + properties: + what: { type: string, maxLength: 20000 } + responses: + "201": + description: Recorded. + content: + application/json: + schema: + type: object + properties: + reference: { type: string } + entry: { $ref: "#/components/schemas/IntakeEntry" } + "400": { description: invalid_what. } + "403": { description: user_token_required. } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/internal/intake/pending: + get: + summary: Intake entries not settled yet, oldest first, across workspaces (route group intake). + description: | + For the receiving service (Werkmeister). Each item carries the + reference and the reporter's own answers routing reads, never the + text. A person's token is refused (`service_token_required`). + parameters: + - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } } + responses: + "200": + description: The entries. + content: + application/json: + schema: + type: object + properties: + items: { type: array, items: { $ref: "#/components/schemas/PendingIntake" } } + "400": { description: invalid_limit. } + "403": { description: service_token_required or FORBIDDEN_CLIENT. } + + /v1/internal/intake/entries/{entry}/receipts: + post: + summary: What became of an intake entry downstream (route group intake). + description: | + waiting (no receiving process yet), delivered, processed or refused. + A receipt that repeats the newest one adds nothing (200). Processed + and refused settle the entry; a further receipt is 409 `settled`. + parameters: + - { in: path, name: entry, required: true, schema: { type: integer, minimum: 1 } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [status] + properties: + status: { type: string, enum: [waiting, delivered, processed, refused] } + reason: { type: string, maxLength: 80 } + handoff_id: { type: string, maxLength: 80 } + run_id: { type: string, maxLength: 80 } + responses: + "200": { description: Repeats the newest receipt; nothing added. } + "201": { description: Added. } + "400": { description: invalid_receipt. } + "403": { description: service_token_required or FORBIDDEN_CLIENT. } + "404": { $ref: "#/components/responses/NotFound" } + "409": { description: settled. } + /v1/tenants/{id}/role-dataset/revisions/{rev}: get: summary: One stored revision of the role dataset, as a decision was made under it. @@ -2375,6 +2507,55 @@ components: catalogue_version: { type: string, description: "The catalogue the client read; another one is refused (catalogue_outdated)." } expected_revision: { type: integer, minimum: 0 } authorize: { type: array, items: { type: string }, description: "Ids of deputies and standard releases management authorizes." } + IntakeReportWrite: + type: object + required: [danger, what] + properties: + danger: { type: string, enum: ["yes", "no", "unknown"], description: "Immediate danger to people? Asked first." } + about: { type: string, enum: [product, it_ot, unknown], default: unknown, description: The reporter's own account; no assessment. } + what: { type: string, maxLength: 20000, description: What was noticed. } + when: { type: string, maxLength: 500 } + where: { type: string, maxLength: 500, description: "Where, or which product." } + contact: { type: string, maxLength: 500, description: Contact for questions. } + IntakeReport: + type: object + properties: + reference: { type: string, example: SH-2026-00001, description: The Eingangsreferenz; the Meldereferenz is the same string. } + received_at: { type: string, format: date-time } + about: { type: string } + danger: { type: string } + handover: { type: string, enum: ["", waiting, delivered, processed, refused] } + entries: { type: array, items: { $ref: "#/components/schemas/IntakeEntry" } } + IntakeEntry: + type: object + properties: + id: { type: integer } + kind: { type: string, enum: [capture, supplement] } + at: { type: string, format: date-time } + receipts: + type: array + items: + type: object + properties: + status: { type: string } + reason: { type: string } + handoff_id: { type: string } + run_id: { type: string } + at: { type: string, format: date-time } + PendingIntake: + type: object + properties: + entry_id: { type: integer } + tenant_id: { type: string, format: uuid } + reference: { type: string } + kind: { type: string, enum: [capture, supplement] } + at: { type: string, format: date-time } + received_at: { type: string, format: date-time } + channel: { type: string } + about: { type: string } + danger: { type: string } + status: { type: string, description: "The newest receipt's status, if any." } + reason: { type: string } RoleDatasetState: type: object required: [tenant_id, revision, catalogue_version, data, derived, catalogue]