package server import ( "bytes" "context" "encoding/json" "log/slog" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "git.breakpilot.com/platform/tenant-registry/internal/authn" "git.breakpilot.com/platform/tenant-registry/internal/config" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/store" ) const feedbackToken = "sentinel-feedback-token-0123456789" // fakeGiteaIssues records the issues it is sent and answers with reply. type fakeGiteaIssues struct { srv *httptest.Server mu sync.Mutex calls []giteaIssueCall reply func(w http.ResponseWriter) } type giteaIssueCall struct { Path, RawQuery, Auth string Title, Body string } func newFakeGiteaIssues(t *testing.T) *fakeGiteaIssues { t.Helper() f := &fakeGiteaIssues{reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusCreated) // id is Gitea's global id; the number is the one in the repo. _, _ = w.Write([]byte(`{"id":9001,"number":42,"html_url":"https://git.example/platform/werkpilot-feedback/issues/42"}`)) }} f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var in struct{ Title, Body string } _ = json.NewDecoder(r.Body).Decode(&in) f.mu.Lock() f.calls = append(f.calls, giteaIssueCall{Path: r.URL.Path, RawQuery: r.URL.RawQuery, Auth: r.Header.Get("Authorization"), Title: in.Title, Body: in.Body}) f.mu.Unlock() if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } f.reply(w) })) t.Cleanup(f.srv.Close) return f } func (f *fakeGiteaIssues) sent() []giteaIssueCall { f.mu.Lock() defer f.mu.Unlock() return append([]giteaIssueCall(nil), f.calls...) } type feedbackFixture struct { s *Server h http.Handler gitea *fakeGiteaIssues acme *store.Tenant other *store.Tenant logs *bytes.Buffer now time.Time } // newFeedbackFixture: the deployed AUTHZ_RULES shape (the CLIs hold // licences and usage, not feedback), and principals by name. func newFeedbackFixture(t *testing.T) *feedbackFixture { t.Helper() mem := store.NewMemory() acme, _ := mem.GetTenantBySlug(context.Background(), "acme") other, err := mem.CreateTenant(context.Background(), store.TenantCreate{Slug: "other", Name: "Other"}) if err != nil { t.Fatal(err) } f := &feedbackFixture{gitea: newFakeGiteaIssues(t), acme: acme, other: other, logs: &bytes.Buffer{}, now: time.Date(2026, 11, 23, 9, 30, 0, 0, time.UTC)} cli := func(client, sub, tenantID, email string) *authn.Principal { return &authn.Principal{Subject: sub, ClientID: client, TenantID: tenantID, Email: email, OrgRoles: []string{"USER"}} } as := map[string]*authn.Principal{ "user": cli("werkpilot-cli", "u-1", acme.ID, "dev@acme.test"), "colleague": cli("werkpilot-cli", "u-2", acme.ID, ""), "stranger": cli("werkpilot-cli", "u-x", other.ID, "x@other.test"), "firmwerk": cli("firmwerk-cli", "u-1", acme.ID, "dev@acme.test"), "service": {Subject: "svc-portal", ClientID: "portal-svc"}, "portal": cli("portal-prod", "u-1", acme.ID, "dev@acme.test"), "granted": cli("other-cli", "u-1", acme.ID, "dev@acme.test"), "firmwerk-svc": {Subject: "svc-fw", ClientID: "firmwerk-svc-prod"}, } f.s = &Server{ Log: slog.New(slog.NewTextHandler(f.logs, nil)), Store: mem, Keycloak: keycloak.NewMock(), Authz: ParseAuthzRules("portal-svc:*;werkpilot-cli:licences,usage;firmwerk-cli:licences,usage;portal-prod:role-dataset.user,intake.user;other-cli:feedback;firmwerk-svc-prod:licences,usage"), Cfg: &config.Config{FeedbackGiteaURL: f.gitea.srv.URL + "/", FeedbackGiteaRepo: "platform/werkpilot-feedback", FeedbackGiteaToken: feedbackToken}, Now: func() time.Time { return f.now }, } router := NewRouter(f.s) f.h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if p := as[r.Header.Get("X-Test-As")]; p != nil { r = r.WithContext(authn.WithPrincipal(r.Context(), p)) } router.ServeHTTP(w, r) }) return f } func (f *feedbackFixture) post(t *testing.T, as, body string) (int, map[string]any, string) { t.Helper() req := httptest.NewRequest(http.MethodPost, "/v1/feedback", strings.NewReader(body)) req.Header.Set("X-Test-As", as) rr := httptest.NewRecorder() f.h.ServeHTTP(rr, req) var out map[string]any _ = json.Unmarshal(rr.Body.Bytes(), &out) return rr.Code, out, rr.Body.String() } func feedbackJSON(over map[string]any) string { in := map[string]any{"product": "werkpilot", "kind": "crash", "title": " panic in the tool loop ", "body": "## Backtrace\n\n```\nthread 'main' panicked\n```\n\n---\nlast line\n", "version": "0.3.1", "device": "build-07"} for k, v := range over { if v == nil { delete(in, k) continue } in[k] = v } b, _ := json.Marshal(in) return string(b) } func TestFeedback_filesAnIssueWithProvenance(t *testing.T) { f := newFeedbackFixture(t) code, out, raw := f.post(t, "user", feedbackJSON(nil)) if code != http.StatusCreated || len(out) != 1 || out["id"] != float64(42) { t.Fatalf("file: %d %s", code, raw) } sent := f.gitea.sent() if len(sent) != 1 { t.Fatalf("gitea calls: %+v", sent) } c := sent[0] if c.Path != "/api/v1/repos/platform/werkpilot-feedback/issues" || c.RawQuery != "" || c.Auth != "token "+feedbackToken { t.Fatalf("request: path %q query %q auth %q", c.Path, c.RawQuery, c.Auth) } if c.Title != "[acme] crash: panic in the tool loop" { t.Fatalf("title %q", c.Title) } want := "- **Tenant:** acme (" + f.acme.ID + ")\n" + "- **User:** u-1 (dev@acme.test)\n" + "- **Product:** werkpilot\n" + "- **Version:** 0.3.1\n" + "- **Device:** build-07\n" + "- **Kind:** crash\n" + "- **Received:** 2026-11-23T09:30:00Z\n" + "\n---\n\n" + "## Backtrace\n\n```\nthread 'main' panicked\n```\n\n---\nlast line\n" if c.Body != want { t.Fatalf("body:\n%s\nwant:\n%s", c.Body, want) } events, _, err := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.acme.ID, Action: "feedback.submitted"}) if err != nil || len(events) != 1 { t.Fatalf("audit: %v %+v", err, events) } if ev := events[0]; ev.ActorID != "u-1" || ev.TargetID != "42" || ev.Product != "werkpilot" || ev.Metadata["kind"] != "crash" { t.Fatalf("audit event: %+v", ev) } // Without an e-mail the user line is the subject alone; a bug report // with no version or device still files. code, _, raw = f.post(t, "colleague", feedbackJSON(map[string]any{"kind": "bug", "version": nil, "device": nil})) if code != http.StatusCreated { t.Fatalf("bug: %d %s", code, raw) } c = f.gitea.sent()[1] if c.Title != "[acme] bug: panic in the tool loop" || !strings.Contains(c.Body, "- **User:** u-2\n") || !strings.Contains(c.Body, "- **Device:** \n") { t.Fatalf("bug issue: %q\n%s", c.Title, c.Body) } } func TestFeedback_disabledWithoutToken(t *testing.T) { f := newFeedbackFixture(t) f.s.Cfg.FeedbackGiteaToken = "" code, out, raw := f.post(t, "user", feedbackJSON(nil)) if code != http.StatusServiceUnavailable || out["error"] != "feedback_disabled" { t.Fatalf("disabled: %d %s", code, raw) } f.s.Cfg = nil if code, out, _ := f.post(t, "user", feedbackJSON(nil)); code != http.StatusServiceUnavailable || out["error"] != "feedback_disabled" { t.Fatalf("no config: %d %v", code, out) } if n := len(f.gitea.sent()); n != 0 { t.Fatalf("gitea called %d times", n) } } func TestFeedback_isChecked(t *testing.T) { f := newFeedbackFixture(t) for name, c := range map[string]struct { body string code int err string }{ "bad kind": {feedbackJSON(map[string]any{"kind": "idea"}), http.StatusBadRequest, "invalid_input"}, "no kind": {feedbackJSON(map[string]any{"kind": nil}), http.StatusBadRequest, "invalid_input"}, "empty title": {feedbackJSON(map[string]any{"title": " "}), http.StatusBadRequest, "invalid_input"}, "long title": {feedbackJSON(map[string]any{"title": strings.Repeat("ä", 201)}), http.StatusBadRequest, "invalid_input"}, "no product": {feedbackJSON(map[string]any{"product": nil}), http.StatusBadRequest, "invalid_input"}, "long product": {feedbackJSON(map[string]any{"product": strings.Repeat("p", 101)}), http.StatusBadRequest, "invalid_input"}, "long version": {feedbackJSON(map[string]any{"version": strings.Repeat("1", 101)}), http.StatusBadRequest, "invalid_input"}, "empty body": {feedbackJSON(map[string]any{"body": " \n "}), http.StatusBadRequest, "invalid_input"}, "no body": {feedbackJSON(map[string]any{"body": nil}), http.StatusBadRequest, "invalid_input"}, "not JSON": {`{"kind":`, http.StatusBadRequest, "invalid_input"}, "body over the cap": {feedbackJSON(map[string]any{"body": strings.Repeat("x", feedbackMaxBody+1)}), http.StatusRequestEntityTooLarge, "too_large"}, "request over limit": {feedbackJSON(map[string]any{"body": strings.Repeat("\x01", feedbackMaxRequest/6+1)}), http.StatusRequestEntityTooLarge, "too_large"}, } { code, out, raw := f.post(t, "user", c.body) if code != c.code || out["error"] != c.err { t.Errorf("%s: %d %s", name, code, raw) } } if n := len(f.gitea.sent()); n != 0 { t.Fatalf("gitea called %d times for refused reports", n) } // The limits themselves pass: 200 characters (not bytes) of title, a // body of exactly the cap. code, _, raw := f.post(t, "user", feedbackJSON(map[string]any{"title": strings.Repeat("ä", 200), "body": strings.Repeat("x", feedbackMaxBody)})) if code != http.StatusCreated { t.Fatalf("at the limits: %d %s", code, raw) } } // Line breaks and other control characters in the one-line fields become // spaces, so the provenance block keeps its seven lines. func TestFeedback_oneLineFieldsCannotForgeProvenance(t *testing.T) { f := newFeedbackFixture(t) code, _, raw := f.post(t, "user", feedbackJSON(map[string]any{ "title": "assertion failed\n left: 1\n right: 2\t\u2028", "version": "0.3.1\r\n- **Tenant:** forged", "device": "host\n\n---\n", "body": "b", })) if code != http.StatusCreated { t.Fatalf("file: %d %s", code, raw) } c := f.gitea.sent()[0] if c.Title != "[acme] crash: assertion failed left: 1 right: 2" { t.Fatalf("title %q", c.Title) } want := "- **Tenant:** acme (" + f.acme.ID + ")\n" + "- **User:** u-1 (dev@acme.test)\n" + "- **Product:** werkpilot\n" + "- **Version:** 0.3.1 - **Tenant:** forged\n" + "- **Device:** host ---\n" + "- **Kind:** crash\n" + "- **Received:** 2026-11-23T09:30:00Z\n" + "\n---\n\nb" if c.Body != want { t.Fatalf("body:\n%q\nwant:\n%q", c.Body, want) } } // The tenant is the token's: a tenant_id in the request changes nothing. func TestFeedback_tenantComesFromThePrincipal(t *testing.T) { f := newFeedbackFixture(t) code, _, raw := f.post(t, "stranger", feedbackJSON(map[string]any{"tenant_id": f.acme.ID, "tenant_slug": "acme"})) if code != http.StatusCreated { t.Fatalf("file: %d %s", code, raw) } c := f.gitea.sent()[0] if !strings.HasPrefix(c.Title, "[other] ") || !strings.Contains(c.Body, "- **Tenant:** other ("+f.other.ID+")\n") || strings.Contains(c.Body, f.acme.ID) { t.Fatalf("issue: %q\n%s", c.Title, c.Body) } if events, _, _ := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.acme.ID, Action: "feedback.submitted"}); len(events) != 0 { t.Fatalf("audited for acme: %+v", events) } } // The CLIs reach the route with the grants they already hold in the // deployed AUTHZ_RULES (licences, usage): a user token from a client with // licences counts as holding feedback. Other clients need the group itself. func TestFeedback_whoReachesIt(t *testing.T) { f := newFeedbackFixture(t) for _, as := range []string{"user", "firmwerk", "granted"} { if code, out, raw := f.post(t, as, feedbackJSON(nil)); code != http.StatusCreated || out["id"] != float64(42) { t.Errorf("%q: %d %s", as, code, raw) } } for as, want := range map[string]string{ "service": "user_token_required", "": "user_token_required", // AUTH_ENABLED=false: no principal, no tenant "portal": "FORBIDDEN_CLIENT", // a user token, but its client holds no licences "firmwerk-svc": "FORBIDDEN_CLIENT", // licences, but a service token } { if code, out, raw := f.post(t, as, feedbackJSON(nil)); code != http.StatusForbidden || out["error"] != want { t.Errorf("%q: %d %s", as, code, raw) } } if n := len(f.gitea.sent()); n != 3 { t.Fatalf("gitea called %d times", n) } } func TestFeedback_rateLimitedPerPerson(t *testing.T) { f := newFeedbackFixture(t) for i := range feedbackPerHour { if code, _, raw := f.post(t, "user", feedbackJSON(nil)); code != http.StatusCreated { t.Fatalf("report %d: %d %s", i+1, code, raw) } f.now = f.now.Add(time.Minute) } code, out, raw := f.post(t, "user", feedbackJSON(nil)) if code != http.StatusTooManyRequests || out["error"] != "rate_limited" { t.Fatalf("eleventh: %d %s", code, raw) } // Refused reports do not count, and the limit is per person. if code, _, _ := f.post(t, "user", feedbackJSON(map[string]any{"kind": "idea"})); code != http.StatusBadRequest { t.Fatalf("invalid while limited: %d", code) } if code, _, raw := f.post(t, "colleague", feedbackJSON(nil)); code != http.StatusCreated { t.Fatalf("colleague: %d %s", code, raw) } if n := len(f.gitea.sent()); n != feedbackPerHour+1 { t.Fatalf("gitea calls %d", n) } // An hour after the first report, that one slot is free again. f.now = f.now.Add(50*time.Minute + 30*time.Second) if code, _, raw := f.post(t, "user", feedbackJSON(nil)); code != http.StatusCreated { t.Fatalf("after the hour: %d %s", code, raw) } if code, _, _ := f.post(t, "user", feedbackJSON(nil)); code != http.StatusTooManyRequests { t.Fatalf("second after the hour: %d", code) } } // When Gitea fails the caller learns only that; neither Gitea's answer nor // the token reaches the response or the log. func TestFeedback_giteaFailureLeaksNothing(t *testing.T) { const marker = "GITEA-SAYS-SECRET-THING" for name, reply := range map[string]func(w http.ResponseWriter){ "500 with a body": func(w http.ResponseWriter) { w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte(`{"message":"` + marker + ` token ` + feedbackToken + ` rejected"}`)) }, "403": func(w http.ResponseWriter) { w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte(marker)) }, "201 without an issue": func(w http.ResponseWriter) { w.WriteHeader(http.StatusCreated) _, _ = w.Write([]byte(`{"message":"` + marker + `"}`)) }, "200 instead of 201": func(w http.ResponseWriter) { _, _ = w.Write([]byte(`{"number":7}`)) }, } { t.Run(name, func(t *testing.T) { f := newFeedbackFixture(t) f.gitea.reply = reply code, out, raw := f.post(t, "user", feedbackJSON(map[string]any{"title": "title-in-report", "body": "body-in-report"})) if code != http.StatusBadGateway || out["error"] != "feedback_failed" { t.Fatalf("failure: %d %s", code, raw) } for _, secret := range []string{marker, feedbackToken, f.gitea.srv.URL} { if strings.Contains(raw, secret) { t.Errorf("response carries %q: %s", secret, raw) } } logs := f.logs.String() for _, secret := range []string{marker, feedbackToken, "title-in-report", "body-in-report"} { if strings.Contains(logs, secret) { t.Errorf("log carries %q: %s", secret, logs) } } if !strings.Contains(logs, "feedback issue not created") { t.Errorf("failure not logged: %s", logs) } }) } } func TestFeedback_giteaUnreachable(t *testing.T) { f := newFeedbackFixture(t) addr := f.gitea.srv.URL f.gitea.srv.Close() code, out, raw := f.post(t, "user", feedbackJSON(nil)) if code != http.StatusBadGateway || out["error"] != "feedback_failed" { t.Fatalf("unreachable: %d %s", code, raw) } logs := f.logs.String() if strings.Contains(raw+logs, feedbackToken) || strings.Contains(raw+logs, addr) { t.Fatalf("token or URL leaked:\n%s\n%s", raw, logs) } } func TestFeedback_badRepoSetting(t *testing.T) { f := newFeedbackFixture(t) for _, repo := range []string{"", "werkpilot-feedback", "platform/", "a/b/c"} { f.s.Cfg.FeedbackGiteaRepo = repo if code, _, raw := f.post(t, "user", feedbackJSON(nil)); code != http.StatusBadGateway { t.Errorf("repo %q: %d %s", repo, code, raw) } } if n := len(f.gitea.sent()); n != 0 { t.Fatalf("gitea called %d times", n) } }