Files
tenant-registry/internal/server/intake.go
T
Sharang ParnerkarandClaude Opus 5.5 4c17affc1f
ci / shared (pull_request) Successful in 10s
ci / test (pull_request) Successful in 5m9s
ci / image (pull_request) Skipped
feat(intake): page the pending list and say when a capture is settled
The pending list is across workspaces, oldest first; entries that keep
waiting in one workspace (no receiving workflow, not booked) could fill
every page and hide those of all others. GET /v1/internal/intake/pending
takes after=<entry id>, so the reader pages on with the last id it got.

Each item says whether its report's capture is settled
(capture_settled), so a reader paging on can hold a supplement back
until its capture is handed over, also when the capture was on an
earlier page. Without after the route answers as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
2026-11-10 10:50:54 +01:00

375 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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?after=&limit=: entries
// not settled yet with an id above after, oldest first, across workspaces.
// A reader pages on with the last id it got, so that entries that keep
// waiting in one workspace never hide those of another.
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
}
var after int64
if v := r.URL.Query().Get("after"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 0 {
writeError(w, http.StatusBadRequest, "invalid_after", "after is an entry id, 0 or more")
return
}
after = n
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
items, err := s.Store.PendingIntake(ctx, after, 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})
}
}