Files
tenant-registry/internal/server/feedback_test.go
T
Sharang ParnerkarandClaude Opus 5.5 553f4c52fe
ci / shared (pull_request) Successful in 15s
ci / test (pull_request) Successful in 6m48s
ci / image (pull_request) Skipped
feat(feedback): POST /v1/feedback files crash and bug reports as Gitea issues
A CLI user sends a crash report or /bug report with their own token; the
registry files it as an issue in the private feedback repo, titled
"[<tenant slug>] <kind>: <title>", with a provenance block (tenant, user,
product, version, device, kind, time received) above the body. The caller
gets the issue number only.

- route group "feedback"; user tokens only; tenant from the principal
- 10 reports per person and hour (in memory)
- FEEDBACK_GITEA_URL / _REPO / _TOKEN; no token answers 503
- Gitea errors become 502 feedback_failed without body, URL or token
- audit event feedback.submitted

Refs platform/werkpilot#86

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRayW7ztyk1uAtwMJPR
2026-11-23 13:49:00 +01:00

379 lines
14 KiB
Go

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 for the CLIs, with
// feedback granted to werkpilot-cli only, 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"},
}
f.s = &Server{
Log: slog.New(slog.NewTextHandler(f.logs, nil)), Store: mem, Keycloak: keycloak.NewMock(),
Authz: ParseAuthzRules("portal-svc:*;werkpilot-cli:licences,usage,feedback;firmwerk-cli: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"},
"two-line title": {feedbackJSON(map[string]any{"title": "a\n- **Tenant:** forged"}), 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"},
"two-line device": {feedbackJSON(map[string]any{"device": "host\n\n---\n"}), 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)
}
}
// 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)
}
}
func TestFeedback_needsAUserTokenAndTheGroup(t *testing.T) {
f := newFeedbackFixture(t)
for as, want := range map[string]string{
"service": "user_token_required",
"": "user_token_required", // AUTH_ENABLED=false: no principal, no tenant
"firmwerk": "FORBIDDEN_CLIENT",
} {
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 != 0 {
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)
}
}