abuse reports: signed reports, gossip and sync, a local hide rule, visitor tips

A report is signed by a node operator (device key and certificate) and
gossiped on one global topic. Each node decides whose reports count: the
operator's own report hides a listing on that node, one trusted report of
illegal content hides it, and --hide-after trusted scam reports hide it
(--trust-reporter names others). Hidden listings stay stored and reachable.
Visitors can tip the node's operator off with a proof-of-work request that
hides nothing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 21:18:43 +01:00
co-authored by Claude Sonnet 5.5
parent 253eb6e75c
commit 6d55222ac5
17 changed files with 1854 additions and 13 deletions
+9 -1
View File
@@ -120,6 +120,14 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress))
mux.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress))
}
// Abuse reports: anyone can read what this node makes of a listing's
// reports and tip the operator off (proof-of-work, no account); the
// operator reads the tips and signs reports.
mux.HandleFunc("GET /api/v1/reports", s.getReports)
mux.HandleFunc("POST /api/v1/signals", s.postSignal)
mux.HandleFunc("GET /api/v1/signals", s.admin(s.listSignals))
mux.HandleFunc("DELETE /api/v1/signals/{author}/{id}", s.admin(s.dismissSignals))
mux.HandleFunc("POST /api/v1/reports", s.admin(s.postReport))
mux.Handle("GET /", s.ui())
return secure(mux)
}
@@ -175,7 +183,7 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
func (s *server) search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
query := store.Query{Kind: q.Get("kind"), Category: q.Get("category")}
query := store.Query{Kind: q.Get("kind"), Category: q.Get("category"), IncludeHidden: q.Get("hidden") == "1"}
if g := q.Get("geohash"); g != "" {
for _, p := range strings.Split(g, ",") {
+4 -1
View File
@@ -40,7 +40,10 @@ func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
if err != nil {
t.Fatal(err)
}
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
s, err := store.Open(":memory:", store.Options{
Difficulty: difficulty, MessageDifficulty: msgDifficulty,
Trust: store.Trust{Self: dev.Cert.Author}, // the operator's own reports hide on this node
})
if err != nil {
t.Fatal(err)
}
+227
View File
@@ -0,0 +1,227 @@
package api
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// --- public ------------------------------------------------------------------
// getReports tells what this node makes of the reports about a listing: the
// counts, and whether its own rules hide it. Reports decide nothing for other
// nodes, so this is one node's view.
func (s *server) getReports(w http.ResponseWriter, r *http.Request) {
author, id := r.URL.Query().Get("author"), r.URL.Query().Get("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "author must be 64 and id 32 hex characters")
return
}
sum, err := s.Store.Summary(r.Context(), author, id)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
noStore(w)
writeJSON(w, http.StatusOK, sum)
}
// signalRequest is what a visitor's browser sends to tip the operator off. It
// is not signed (a visitor has no key), only backed by proof-of-work: the
// SHA-256 of its canonical encoding has leading zero bits, as with messages.
// Field order matters only for the canonical form: pow sorts before v, and the
// browser mines the same bytes.
type signalRequest struct {
Category string `json:"category"`
CreatedAt int64 `json:"created_at"`
Listing struct {
Author string `json:"author"`
ID string `json:"id"`
} `json:"listing"`
Note string `json:"note"`
PoW uint64 `json:"pow"`
Version int `json:"v"`
}
// postSignal records a visitor's tip. Tips stay on this node: they hide
// nothing and are not gossiped; the operator reads them and may sign a report.
func (s *server) postSignal(w http.ResponseWriter, r *http.Request) {
if !s.limiter.allow(clientIP(r)) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many requests from this address; try again in a minute")
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 2048))
if err != nil {
fail(w, http.StatusRequestEntityTooLarge, "request too large")
return
}
var q signalRequest
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&q); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON body")
return
}
canon, err := jcs.Marshal(&q)
if err != nil || !bytes.Equal(canon, body) {
fail(w, http.StatusBadRequest, "the request must be in canonical JSON form")
return
}
probe := report.Report{Version: report.Version, Listing: report.Ref{Author: q.Listing.Author, ID: q.Listing.ID}, Category: q.Category, Note: q.Note}
switch {
case q.Version != report.Version:
fail(w, http.StatusBadRequest, "unsupported version")
return
case !report.ValidCategory(q.Category) || q.Category == report.Withdrawn:
fail(w, http.StatusBadRequest, "unknown category")
return
case len(q.Listing.Author) != 64 || !isLowerHex(q.Listing.Author) || len(q.Listing.ID) != 32 || !isLowerHex(q.Listing.ID):
fail(w, http.StatusBadRequest, "listing must name a 64-hex author and a 32-hex id")
return
case len(q.Note) > report.MaxNote || !validTipNote(probe.Note):
fail(w, http.StatusBadRequest, "the note is too long or has control characters")
return
}
now := s.Clock()
if d := time.Unix(q.CreatedAt, 0).Sub(now); d > report.MaxClockSkew || d < -report.MaxClockSkew {
fail(w, http.StatusBadRequest, "created_at is too far from this node's clock")
return
}
work := pow.LeadingZeroBits(canon)
if work < s.MessageDifficulty {
fail(w, http.StatusBadRequest, "not enough proof-of-work")
return
}
if _, err := s.Store.Region(r.Context(), q.Listing.Author, q.Listing.ID); errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "this node does not know that listing")
return
} else if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
sum := sha256.Sum256(canon)
err = s.Store.AddSignal(r.Context(), store.Signal{
Hash: hex.EncodeToString(sum[:]), Author: q.Listing.Author, ListingID: q.Listing.ID,
Category: q.Category, Note: q.Note, Work: work,
})
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusAccepted)
}
func validTipNote(s string) bool {
for _, c := range s {
if c < 0x20 || c == 0x7f {
return false
}
}
return true
}
// --- the operator (admin token) ---------------------------------------------
type signalView struct {
store.Signal
Title string `json:"title,omitempty"`
}
// listSignals is the operator's queue of visitor tips, strongest first.
func (s *server) listSignals(w http.ResponseWriter, r *http.Request) {
tips, err := s.Store.Signals(r.Context())
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]signalView, 0, len(tips))
for _, g := range tips {
v := signalView{Signal: g}
if l, err := s.Store.Get(r.Context(), g.Author, g.ListingID); err == nil {
v.Title = l.Title
}
out = append(out, v)
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
// dismissSignals throws away the tips about one listing.
func (s *server) dismissSignals(w http.ResponseWriter, r *http.Request) {
author, id := r.PathValue("author"), r.PathValue("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "malformed listing")
return
}
if _, err := s.Store.DeleteSignals(r.Context(), author, id); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusNoContent)
}
type reportBody struct {
Listing struct {
Author string `json:"author"`
ID string `json:"id"`
} `json:"listing"`
Category string `json:"category"`
Note string `json:"note"`
}
// postReport signs a report as this node's operator and gossips it. The
// operator's own report hides the listing on this node at once; others
// count it only if they trust this operator. Category "withdrawn" takes an
// earlier report back. The tips about the listing are cleared.
func (s *server) postReport(w http.ResponseWriter, r *http.Request) {
var b reportBody
if !decodeBody(w, r, &b) {
return
}
now := s.Clock()
rep := &report.Report{
Listing: report.Ref{Author: b.Listing.Author, ID: b.Listing.ID},
Category: b.Category,
Note: b.Note,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(report.MaxLifetime).Unix(),
}
if err := rep.Seal(s.Device, s.Difficulty); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if err := s.Node.PublishReport(r.Context(), rep); err != nil {
switch {
case errors.Is(err, store.ErrInvalid):
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
case errors.Is(err, store.ErrRevoked):
fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
return
}
if _, err := s.Store.DeleteSignals(r.Context(), b.Listing.Author, b.Listing.ID); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
sum, err := s.Store.Summary(r.Context(), b.Listing.Author, b.Listing.ID)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, sum)
}
+182
View File
@@ -0,0 +1,182 @@
package api
import (
"encoding/json"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/pow"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
func (f *fixture) found(t *testing.T, query string) int {
t.Helper()
code, body := f.do(t, "GET", "/api/v1/listings"+query, "", false)
var ls []json.RawMessage
if code != 200 || json.Unmarshal(body, &ls) != nil {
t.Fatalf("search: %d %s", code, body)
}
return len(ls)
}
func (f *fixture) summary(t *testing.T, l *listing.Listing) store.ReportSummary {
t.Helper()
code, body := f.do(t, "GET", "/api/v1/reports?author="+l.Author+"&id="+l.ID, "", false)
var s store.ReportSummary
if code != 200 || json.Unmarshal(body, &s) != nil {
t.Fatalf("summary: %d %s", code, body)
}
return s
}
func reportJSON(l *listing.Listing, category, note string) string {
b, _ := json.Marshal(map[string]any{
"listing": map[string]string{"author": l.Author, "id": l.ID}, "category": category, "note": note,
})
return string(b)
}
func TestTheOperatorReportsAListingAndItDisappearsFromSearchButNotFromItsLink(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
if f.found(t, "") != 1 {
t.Fatal("the listing is not found before the report")
}
if code, _ := f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Scam, "Vorkasse"), false); code != 401 {
t.Fatalf("reporting without the token: %d", code)
}
if code, body := f.do(t, "POST", "/api/v1/reports", reportJSON(l, "spam", ""), true); code != 400 {
t.Fatalf("an unknown category: %d %s", code, body)
}
code, body := f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Scam, "Vorkasse"), true)
var sum store.ReportSummary
if code != 200 || json.Unmarshal(body, &sum) != nil || !sum.Hidden || sum.Own != report.Scam {
t.Fatalf("report: %d %s", code, body)
}
if f.found(t, "") != 0 {
t.Fatal("a hidden listing still shows up in search")
}
if f.found(t, "?hidden=1") != 1 {
t.Fatal("hidden=1 must still list it")
}
if code, _ := f.do(t, "GET", "/api/v1/listings/"+l.Author+"/"+l.ID, "", false); code != 200 {
t.Fatalf("a hidden listing must stay reachable by its link: %d", code)
}
if s := f.summary(t, l); !s.Hidden || s.Trusted[report.Scam] != 1 {
t.Fatalf("summary: %+v", s)
}
// Taking the report back makes it visible again.
time.Sleep(1100 * time.Millisecond) // a newer report needs a later second
if code, body := f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Withdrawn, ""), true); code != 200 {
t.Fatalf("withdraw: %d %s", code, body)
}
if f.found(t, "") != 1 || f.summary(t, l).Hidden {
t.Fatal("a withdrawn report still hides the listing")
}
}
func TestReportSummaryNeedsAWellFormedListing(t *testing.T) {
f := newFixture(t, token)
if code, _ := f.do(t, "GET", "/api/v1/reports?author=zz&id=1", "", false); code != 400 {
t.Fatalf("bad parameters: %d", code)
}
}
// tip is what a visitor's browser sends. With enough = false it has too little
// proof-of-work to count.
func tip(t *testing.T, l *listing.Listing, category, note string, enough bool) string {
t.Helper()
q := signalRequest{Category: category, CreatedAt: time.Now().Unix(), Note: note, Version: 1}
q.Listing.Author, q.Listing.ID = l.Author, l.ID
for ; ; q.PoW++ {
b, err := jcs.Marshal(&q)
if err != nil {
t.Fatal(err)
}
if (pow.LeadingZeroBits(b) >= msgDifficulty) == enough {
return string(b)
}
}
}
// postTo sends a request body without a token and returns the status.
func (f *fixture) postTo(t *testing.T, path, body string) int {
t.Helper()
code, _ := f.do(t, "POST", path, body, false)
return code
}
func TestVisitorsCanTipOffTheOperatorWithoutHidingAnything(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
post := func(body string) int { return f.postTo(t, "/api/v1/signals", body) }
good := tip(t, l, report.Scam, "Will Vorkasse nach Spanien", true)
if code := post(good); code != 202 {
t.Fatalf("a tip: %d", code)
}
if code := post(good); code != 202 {
t.Fatalf("the same tip again: %d", code)
}
if f.found(t, "") != 1 || f.summary(t, l).Hidden {
t.Fatal("a tip must never hide a listing")
}
if s := f.summary(t, l); s.Signals != 1 {
t.Fatalf("a tip sent twice counts %d times, want once", s.Signals)
}
// Only the operator reads them.
if code, _ := f.do(t, "GET", "/api/v1/signals", "", false); code != 401 {
t.Fatalf("reading tips without the token: %d", code)
}
var tips []struct {
store.Signal
Title string `json:"title"`
}
code, body := f.do(t, "GET", "/api/v1/signals", "", true)
if code != 200 || json.Unmarshal(body, &tips) != nil || len(tips) != 1 ||
tips[0].Category != report.Scam || tips[0].Title != l.Title || tips[0].Note != "Will Vorkasse nach Spanien" {
t.Fatalf("tips: %d %s", code, body)
}
for name, c := range map[string]struct {
body string
want int
}{
"too little work": {tip(t, l, report.Scam, "x", false), 400},
"unknown category": {tip(t, l, "spam", "x", true), 400},
"withdrawn": {tip(t, l, report.Withdrawn, "x", true), 400},
"a note with controls": {tip(t, l, report.Scam, "a\x01b", true), 400},
"a note too long": {tip(t, l, report.Scam, strings.Repeat("a", report.MaxNote+1), true), 400},
"not canonical": {" " + good, 400},
"not JSON": {"hallo", 400},
} {
if got := post(c.body); got != c.want {
t.Errorf("%s: %d, want %d", name, got, c.want)
}
}
stranger := *l
stranger.ID = strings.Repeat("0", 32)
if code := post(tip(t, &stranger, report.Scam, "x", true)); code != 404 {
t.Fatalf("a listing this node does not know: %d", code)
}
// The operator dismisses them, or turns them into a report (which clears them).
if code, _ := f.do(t, "DELETE", "/api/v1/signals/"+l.Author+"/"+l.ID, "", true); code != 204 {
t.Fatalf("dismiss: %d", code)
}
if f.summary(t, l).Signals != 0 {
t.Fatal("a dismissed tip is still counted")
}
post(tip(t, l, report.Illegal, "anders", true))
f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Illegal, "bestätigt"), true)
if s := f.summary(t, l); s.Signals != 0 || !s.Hidden {
t.Fatalf("after reporting: %+v", s)
}
}