feat(feedback): POST /v1/feedback files crash and bug reports as Gitea issues #147

Open
sharang wants to merge 3 commits from feat/feedback-endpoint into main
pull from: feat/feedback-endpoint
13 changed files with 770 additions and 16 deletions

No files matched your search

+2
View File
@@ -47,6 +47,8 @@ Env vars (override at the shell):
| `KEYCLOAK_CLIENT_SECRET` | empty | Service-account client secret |
| `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route |
| `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` |
| `FEEDBACK_GITEA_TOKEN` | empty (`POST /v1/feedback` answers 503) | Secret. Gitea token of a bot account that may create issues in the feedback repo; sent only in the `Authorization` header. On-prem it needs `FEEDBACK_GITEA_URL` and `FEEDBACK_GITEA_REPO` set explicitly |
| `FEEDBACK_GITEA_URL` / `FEEDBACK_GITEA_REPO` | `https://git.breakpilot.com` / `platform/werkpilot-feedback` | Where crash and /bug reports from the CLIs are filed as issues (`owner/name`, a private repo) |
| `DOCUMENTS_S3_ENDPOINT` / `_REGION` / `_BUCKET` / `_ACCESS_KEY` / `_SECRET_KEY` | empty (document routes 503) | Object storage for tenant documents; the bucket is created in the region when missing |
| `DOCUMENTS_MAX_MB` | `200` | Upload limit per document |
| `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASSWORD` | empty (mail queues up unsent) | Relay for platform mail (STARTTLS on 587, TLS on 465) |
+15
View File
@@ -136,6 +136,13 @@ type Config struct {
LiteLLMModels []string
LiteLLMBudgetTrial float64
LiteLLMBudgetDefault float64
// Feedback (POST /v1/feedback, werkpilot#86): crash reports and /bug
// reports become issues in a private Gitea repo ("owner/name"). An empty
// token turns the endpoint off (503).
FeedbackGiteaURL string
FeedbackGiteaRepo string
FeedbackGiteaToken string
}
func Load() (*Config, error) {
@@ -235,6 +242,10 @@ func Load() (*Config, error) {
LiteLLMBudgetTrial: getfloat("LITELLM_BUDGET_TRIAL", 5),
LiteLLMBudgetDefault: getfloat("LITELLM_BUDGET_DEFAULT", 50),
FeedbackGiteaURL: getenv("FEEDBACK_GITEA_URL", "https://git.breakpilot.com"),
FeedbackGiteaRepo: getenv("FEEDBACK_GITEA_REPO", "platform/werkpilot-feedback"),
FeedbackGiteaToken: os.Getenv("FEEDBACK_GITEA_TOKEN"),
Products: getlist("PRODUCTS", nil),
LaunchURLs: launch,
ProvisionURLs: provision,
@@ -280,6 +291,10 @@ func (c *Config) checkOnPrem() error {
if c.LiteLLMMasterKey != "" {
need("LITELLM_BASE_URL")
}
if c.FeedbackGiteaToken != "" {
need("FEEDBACK_GITEA_URL")
need("FEEDBACK_GITEA_REPO")
}
if len(missing) > 0 {
return fmt.Errorf("APP_ENV=onprem needs %s", strings.Join(missing, ", "))
}
+6
View File
@@ -9,6 +9,9 @@ func TestLoad_defaults(t *testing.T) {
t.Setenv("ADDR", "")
t.Setenv("KEYCLOAK_ISSUER", "")
t.Setenv("DATABASE_URL", "")
t.Setenv("FEEDBACK_GITEA_URL", "")
t.Setenv("FEEDBACK_GITEA_REPO", "")
t.Setenv("FEEDBACK_GITEA_TOKEN", "")
cfg, err := Load()
if err != nil {
@@ -26,6 +29,9 @@ func TestLoad_defaults(t *testing.T) {
if cfg.DatabaseURL != "" {
t.Errorf("DatabaseURL = %q, want empty default", cfg.DatabaseURL)
}
if cfg.FeedbackGiteaURL != "https://git.breakpilot.com" || cfg.FeedbackGiteaRepo != "platform/werkpilot-feedback" || cfg.FeedbackGiteaToken != "" {
t.Errorf("feedback = %q %q token set %v", cfg.FeedbackGiteaURL, cfg.FeedbackGiteaRepo, cfg.FeedbackGiteaToken != "")
}
}
func TestLoad_overrides(t *testing.T) {
+2
View File
@@ -33,6 +33,7 @@ func onPremEnv(t *testing.T) {
t.Setenv(k, v)
}
for _, k := range []string{"ERP_BASE_URL", "ERP_WEBHOOK_SECRET", "CONTRACT_DOCUMENTS", "LITELLM_MASTER_KEY", "LITELLM_BASE_URL", "SMTP_USER",
"FEEDBACK_GITEA_TOKEN", "FEEDBACK_GITEA_URL", "FEEDBACK_GITEA_REPO",
"LEGAL_IMPRINT_URL", "LEGAL_PRIVACY_URL", "MAIL_CONTACT", "MAIL_FROM_NAME"} {
t.Setenv(k, "")
}
@@ -73,6 +74,7 @@ func TestLoad_onPremRefusesCloudDefaults(t *testing.T) {
{"an ERP", "ERP_BASE_URL", "https://erp.onprem.test", "no ERP"},
{"contract documents", "CONTRACT_DOCUMENTS", "on", "contract documents"},
{"LLM key without gateway", "LITELLM_MASTER_KEY", "x", "LITELLM_BASE_URL"},
{"feedback token without its repo", "FEEDBACK_GITEA_TOKEN", "x", "FEEDBACK_GITEA_URL, FEEDBACK_GITEA_REPO"},
{"product without tile", "PRODUCTS", "pruefwerk,firmwerk", `"firmwerk"`},
{"our sender", "MAIL_FROM", "noreply@breakpilot.com", "MAIL_FROM points at breakpilot.com"},
{"our portal", "PORTAL_URL", "https://app.breakpilot.com", "PORTAL_URL points"},
+66 -12
View File
@@ -1,8 +1,10 @@
// Package gitea reads the user list of a Managed Git instance (t81): one
// Gitea per customer, read with a token of scope read:admin.
// Gitea per customer, read with a token of scope read:admin. It also files
// issues, for feedback reports (werkpilot#86).
package gitea
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -86,12 +88,73 @@ func (c *Client) ListUsers(ctx context.Context, baseURL, token string) ([]User,
}
func (c *Client) page(ctx context.Context, u, token string) ([]User, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
resp, err := c.do(ctx, http.MethodGet, u, token, nil)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxBody))
return nil, &ErrStatus{Code: resp.StatusCode}
}
var users []User
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&users); err != nil {
return nil, errors.New("gitea: response is not a user list")
}
return users, nil
}
// CreateIssue opens an issue in repo ("owner/name") of the instance at
// baseURL (POST /api/v1/repos/{owner}/{repo}/issues) and returns its number
// in that repo. Errors carry no response body, URL or token.
func (c *Client) CreateIssue(ctx context.Context, baseURL, token, repo, title, body string) (int64, error) {
if token == "" {
return 0, errors.New("gitea: no token")
}
owner, name, ok := strings.Cut(repo, "/")
if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
return 0, errors.New("gitea: repo is not owner/name")
}
u, err := url.Parse(strings.TrimRight(baseURL, "/") + "/api/v1/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(name) + "/issues")
if err != nil || u.Host == "" {
return 0, errors.New("gitea: invalid instance url")
}
payload, err := json.Marshal(map[string]string{"title": title, "body": body})
if err != nil {
return 0, errors.New("gitea: encode issue")
}
resp, err := c.do(ctx, http.MethodPost, u.String(), token, payload)
if err != nil {
return 0, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxBody))
return 0, &ErrStatus{Code: resp.StatusCode}
}
var issue struct {
Number int64 `json:"number"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&issue); err != nil || issue.Number <= 0 {
return 0, errors.New("gitea: response is not an issue")
}
return issue.Number, nil
}
func (c *Client) do(ctx context.Context, method, u, token string, body []byte) (*http.Response, error) {
var rd io.Reader
if body != nil {
rd = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, u, rd)
if err != nil {
return nil, errors.New("gitea: build request")
}
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http().Do(req)
if err != nil {
// Not the *url.Error itself: it names the instance's URL, and the
@@ -105,14 +168,5 @@ func (c *Client) page(ctx context.Context, u, token string) ([]User, error) {
}
return nil, errors.New("gitea: request failed")
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxBody))
return nil, &ErrStatus{Code: resp.StatusCode}
}
var users []User
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&users); err != nil {
return nil, errors.New("gitea: response is not a user list")
}
return users, nil
return resp, nil
}
+38
View File
@@ -100,3 +100,41 @@ func TestUser_signedIn(t *testing.T) {
t.Error("a real sign-in does not count")
}
}
func TestCreateIssue_postsAndReturnsTheNumber(t *testing.T) {
var got struct{ Title, Body string }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.EscapedPath() != "/api/v1/repos/plat%20form/fb/issues" || r.Header.Get("Authorization") != "token "+token ||
r.Header.Get("Content-Type") != "application/json" || r.URL.RawQuery != "" {
w.WriteHeader(http.StatusBadRequest)
return
}
_ = json.NewDecoder(r.Body).Decode(&got)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":555,"number":3}`))
}))
defer srv.Close()
n, err := (&Client{}).CreateIssue(context.Background(), srv.URL+"/", token, "plat form/fb", "t", "b\n---\nc")
if err != nil || n != 3 || got.Title != "t" || got.Body != "b\n---\nc" {
t.Fatalf("n=%d err=%v got=%+v", n, err, got)
}
}
func TestCreateIssue_errorsCarryNoBodyOrToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
_, _ = w.Write([]byte(`{"message":"token ` + token + ` cannot write"}`))
}))
defer srv.Close()
if _, err := (&Client{}).CreateIssue(context.Background(), srv.URL, token, "o/r", "t", "b"); err == nil || err.Error() != "gitea: status 422" {
t.Fatalf("err: %v", err)
}
for _, repo := range []string{"", "o", "o/", "/r", "o/r/x"} {
if _, err := (&Client{}).CreateIssue(context.Background(), srv.URL, token, repo, "t", "b"); err == nil || strings.Contains(err.Error(), token) {
t.Errorf("repo %q: %v", repo, err)
}
}
if _, err := (&Client{}).CreateIssue(context.Background(), srv.URL, "", "o/r", "t", "b"); err == nil {
t.Fatal("no token must fail")
}
}
+8
View File
@@ -110,6 +110,8 @@ func routeGroup(method, path string) string {
return "tenants.read"
case strings.HasPrefix(path, "/v1/licences"):
return "licences"
case path == "/v1/feedback":
return "feedback"
case strings.HasPrefix(path, "/v1/trial-offers"):
return "tenants.write"
case strings.HasPrefix(path, "/v1/tenants"):
@@ -151,6 +153,12 @@ func (s *Server) requireAuthz(next http.Handler) http.Handler {
if p.IsUser() && isIntakeUserPath(r.URL.Path) {
group = "intake.user"
}
// A CLI that signs people in (group licences: werkpilot-cli,
// firmwerk-cli) may also send their feedback (werkpilot#86) without
// another grant; the handler takes user tokens only.
if group == "feedback" && p.IsUser() && !s.Authz.Allowed(p.ClientID, group) && s.Authz.Allowed(p.ClientID, "licences") {
group = "licences"
}
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)
+6 -1
View File
@@ -3,7 +3,7 @@ package server
import "testing"
func TestAuthzRules(t *testing.T) {
a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read; werkpilot-svc:tenants.read; root:* ;broken")
a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read; werkpilot-svc:tenants.read; werkpilot-cli:licences,usage,feedback; firmwerk-cli:licences,usage; root:* ;broken")
cases := []struct {
azp, method, path string
want bool
@@ -30,6 +30,11 @@ func TestAuthzRules(t *testing.T) {
{"portal-svc", "GET", "/v1/internal/connections/c1", false},
{"portal-svc", "POST", "/v1/tenants/t1/connections", true},
{"pruefwerk-svc", "POST", "/v1/tenants/t1/connection-invites", false},
// Feedback (werkpilot#86): its own group. User tokens from clients
// with licences also pass (requireAuthz, feedback_test.go).
{"werkpilot-cli", "POST", "/v1/feedback", true},
{"firmwerk-cli", "POST", "/v1/feedback", false},
{"portal-svc", "POST", "/v1/feedback", false},
}
for _, c := range cases {
if got := a.Allowed(c.azp, routeGroup(c.method, c.path)); got != c.want {
+153
View File
@@ -0,0 +1,153 @@
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// ─── feedback (werkpilot#86) ──────────────────────────────────────────────
//
// `werkpilot` sends crash reports and /bug reports with the user's own
// token. Each becomes an issue in a private Gitea repo, headed by where it
// came from; the tenant is the token's, never the caller's say. The caller
// gets the issue number only: the repo is internal.
const (
feedbackMaxBody = 200000
feedbackMaxTitle = 200
feedbackMaxShort = 100
feedbackPerHour = 10
feedbackMaxRequest = 2 << 20 // the body JSON-escaped, with room to spare
)
type feedbackReq struct {
Product string `json:"product"`
Kind string `json:"kind"`
Title string `json:"title"`
Body string `json:"body"`
Version string `json:"version"`
Device string `json:"device"`
}
func (s *Server) postFeedback(w http.ResponseWriter, r *http.Request) {
cfg := s.cfg()
if cfg.FeedbackGiteaToken == "" {
writeError(w, http.StatusServiceUnavailable, "feedback_disabled", "feedback is not configured")
return
}
p, has := authn.PrincipalFrom(r.Context())
if !has || !p.IsUser() {
writeError(w, http.StatusForbidden, "user_token_required", "feedback is sent with the token of the person sending it")
return
}
var in feedbackReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, feedbackMaxRequest)).Decode(&in); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the report is larger than "+strconv.Itoa(feedbackMaxBody)+" bytes")
return
}
writeError(w, http.StatusBadRequest, "invalid_input", "request body is not valid JSON")
return
}
if len(in.Body) > feedbackMaxBody {
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the report is larger than "+strconv.Itoa(feedbackMaxBody)+" bytes")
return
}
if msg := in.validate(); msg != "" {
writeError(w, http.StatusBadRequest, "invalid_input", msg)
return
}
now := s.now()
if !s.feedbackLimiter.allow(p.Subject, now, feedbackPerHour) {
writeError(w, http.StatusTooManyRequests, "rate_limited", "at most "+strconv.Itoa(feedbackPerHour)+" reports per hour")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
slug := p.TenantSlug
if t, err := s.Store.GetTenant(ctx, p.TenantID); err == nil {
slug = t.Slug
}
title := "[" + slug + "] " + in.Kind + ": " + in.Title
number, err := s.Gitea.CreateIssue(ctx, cfg.FeedbackGiteaURL, cfg.FeedbackGiteaToken, cfg.FeedbackGiteaRepo, title, feedbackIssueBody(in, p, slug, now))
if err != nil {
s.Log.Error("feedback issue not created", "err", err, "tenant_id", p.TenantID, "kind", in.Kind)
writeError(w, http.StatusBadGateway, "feedback_failed", "the report could not be filed")
return
}
s.emitAudit(ctx, r, store.AuditEvent{TenantID: p.TenantID, Action: "feedback.submitted", TargetID: strconv.FormatInt(number, 10), TargetType: "feedback",
ActorID: p.Subject, ActorName: p.Email, ActorType: "user", Product: in.Product,
Metadata: map[string]interface{}{"kind": in.Kind, "version": in.Version, "device": in.Device}})
writeJSON(w, http.StatusCreated, map[string]int64{"id": number})
}
// validate trims the fields in place and names the first one that fails.
// The single-line fields go into the issue's title and provenance lines, so
// their line breaks and other control characters become spaces: a panic
// message used as a title still files, and nobody forges a provenance line.
func (in *feedbackReq) validate() string {
var ok bool
if in.Kind != "crash" && in.Kind != "bug" {
return "kind must be crash or bug"
}
if in.Title, ok = singleLine(in.Title, feedbackMaxTitle, true); !ok {
return "title: 1 to " + strconv.Itoa(feedbackMaxTitle) + " characters"
}
if in.Product, ok = singleLine(in.Product, feedbackMaxShort, true); !ok {
return "product: 1 to " + strconv.Itoa(feedbackMaxShort) + " characters"
}
if in.Version, ok = singleLine(in.Version, feedbackMaxShort, false); !ok {
return "version: at most " + strconv.Itoa(feedbackMaxShort) + " characters"
}
if in.Device, ok = singleLine(in.Device, feedbackMaxShort, false); !ok {
return "device: at most " + strconv.Itoa(feedbackMaxShort) + " characters"
}
if strings.TrimSpace(in.Body) == "" || !utf8.ValidString(in.Body) {
return "body is required"
}
return ""
}
func singleLine(v string, max int, required bool) (string, bool) {
v = strings.Map(func(r rune) rune {
if unicode.IsControl(r) || r == '\u2028' || r == '\u2029' {
return ' '
}
return r
}, v)
return field(v, max, required)
}
// feedbackIssueBody is the provenance block, a rule, then the report as sent.
func feedbackIssueBody(in feedbackReq, p *authn.Principal, slug string, received time.Time) string {
user := p.Subject
if p.Email != "" {
user += " (" + p.Email + ")"
}
var b strings.Builder
for _, line := range [][2]string{
{"Tenant", slug + " (" + p.TenantID + ")"},
{"User", user},
{"Product", in.Product},
{"Version", in.Version},
{"Device", in.Device},
{"Kind", in.Kind},
{"Received", received.UTC().Format(time.RFC3339)},
} {
b.WriteString("- **" + line[0] + ":** " + line[1] + "\n")
}
b.WriteString("\n---\n\n")
b.WriteString(in.Body)
return b.String()
}
+418
View File
@@ -0,0 +1,418 @@
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)
}
}
+1
View File
@@ -108,6 +108,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
{"POST", "/v1/licences/heartbeat"},
{"POST", "/v1/licences/ci"},
{"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"},
{"POST", "/v1/feedback"},
{"GET", "/.well-known/licence-keys.json"},
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/managed-services"},
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/contracts"},
+8 -3
View File
@@ -53,9 +53,10 @@ type Server struct {
// ones (contractdocs.Default). Tests pass their own.
Contracts *contractdocs.Catalogue
blocks blockCache // MemberBlocked answers for user tokens (team.go)
ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go)
connLimiter keyRateLimiter // codes entered per tenant and person (connections.go)
blocks blockCache // MemberBlocked answers for user tokens (team.go)
ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go)
connLimiter keyRateLimiter // codes entered per tenant and person (connections.go)
feedbackLimiter keyRateLimiter // feedback reports per person (feedback.go)
}
func (s *Server) now() time.Time {
@@ -237,6 +238,10 @@ func NewRouter(s *Server) http.Handler {
mux.HandleFunc("GET /v1/licences", s.listLicences)
mux.HandleFunc("POST /v1/licences/{id}/revoke", s.revokeLicence)
// Crash and /bug reports from the CLIs (werkpilot#86; group "feedback"):
// any member, with their own token.
mux.HandleFunc("POST /v1/feedback", s.postFeedback)
// keycloak claims refresh — the URL the protocol mapper would call at
// token issuance to grab the up-to-date entitlement bundle. Today the
// dev realm projects user attributes (set by SyncClaims) — this is
+47
View File
@@ -2635,6 +2635,53 @@ paths:
"429": { description: "More than 60 calls for this key in the last hour." }
"503": { description: Licence signer not configured. }
/v1/feedback:
post:
summary: File a crash report or bug report from a CLI (werkpilot#86).
description: |
Sent with the person's own token (device flow); any member of the
tenant may send one, and the tenant is the token's. Each report
becomes an issue in an internal Gitea repo (FEEDBACK_GITEA_REPO),
titled `[<tenant slug>] <kind>: <title>`, whose body is a provenance
block (tenant slug and id, the user's subject and e-mail, product,
version, device, kind, time received in UTC), a `---` rule, then
`body` verbatim. Only the issue number is returned. Route group
`feedback`; a user token from a client holding `licences` (the
CLIs) passes without it. At most 10 reports per person and hour. Fields are
trimmed; in title, product, version and device, line breaks and
other control characters become spaces. Over-long fields are
refused, not cut.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [product, kind, title, body]
properties:
product: { type: string, minLength: 1, maxLength: 100, example: werkpilot }
kind: { type: string, enum: [crash, bug] }
title: { type: string, minLength: 1, maxLength: 200 }
body: { type: string, description: "Markdown, at most 200000 bytes." }
version: { type: string, maxLength: 100, example: "0.3.1" }
device: { type: string, maxLength: 100, description: "hostname" }
responses:
"201":
description: Filed.
content:
application/json:
schema:
type: object
required: [id]
properties:
id: { type: integer, description: "The issue number in the feedback repo." }
"400": { $ref: "#/components/responses/BadRequest" }
"403": { description: "Not a user token (user_token_required), or the client holds neither feedback nor licences (FORBIDDEN_CLIENT)." }
"413": { description: "body exceeds 200000 bytes (too_large)." }
"429": { description: "More than 10 reports from this person in the last hour (rate_limited)." }
"502": { description: "Gitea did not create the issue (feedback_failed)." }
"503": { description: "FEEDBACK_GITEA_TOKEN not set (feedback_disabled)." }
/.well-known/licence-keys.json:
get:
summary: Licence verification keys (JWKS, OKP/Ed25519). PUBLIC_EXPLICIT.