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:
@@ -0,0 +1,321 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/report"
|
||||
)
|
||||
|
||||
// DefaultHideThreshold is how many distinct trusted reporters it takes to hide
|
||||
// a listing as a scam.
|
||||
const DefaultHideThreshold = 2
|
||||
|
||||
const (
|
||||
maxReports = 20000 // live reports a node keeps; the oldest go first
|
||||
maxSignals = 2000
|
||||
maxSignalsPerList = 50
|
||||
)
|
||||
|
||||
// Trust says whose abuse reports hide listings on this node. It is a local
|
||||
// choice, like everything about hiding: other nodes decide for themselves, and
|
||||
// a hidden listing stays stored and reachable by its link.
|
||||
//
|
||||
// A listing is hidden when
|
||||
// - the node's own operator (Self) reported it as a scam or as illegal, or
|
||||
// - one trusted reporter flagged it as illegal, or
|
||||
// - Threshold distinct trusted reporters flagged it as a scam or as illegal.
|
||||
//
|
||||
// Reports in the other categories only label a listing.
|
||||
type Trust struct {
|
||||
Self string // this node's identity key; may be empty
|
||||
Reporters []string // other identity keys whose reports count
|
||||
Threshold int // 0 means DefaultHideThreshold
|
||||
}
|
||||
|
||||
func (t Trust) keys() []string {
|
||||
out := append([]string(nil), t.Reporters...)
|
||||
if t.Self != "" {
|
||||
out = append(out, t.Self)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// hiddenSQL is a query returning the (author, id) of every listing the node
|
||||
// hides, with its arguments.
|
||||
func (s *Store) hiddenSQL() (string, []any) {
|
||||
keys, _ := json.Marshal(s.trust.keys())
|
||||
return `
|
||||
SELECT l_author, l_id FROM reports
|
||||
WHERE expires_at > ? AND category IN ('scam', 'illegal')
|
||||
AND reporter IN (SELECT value FROM json_each(?))
|
||||
GROUP BY l_author, l_id
|
||||
HAVING COUNT(*) >= ? OR SUM(category = 'illegal') >= 1 OR SUM(reporter = ?) >= 1`,
|
||||
[]any{s.clock().Unix(), string(keys), s.trust.Threshold, s.trust.Self}
|
||||
}
|
||||
|
||||
// PutReport verifies and stores a signed report. A reporter has one report per
|
||||
// listing: a newer one (which may withdraw it) replaces the older.
|
||||
func (s *Store) PutReport(ctx context.Context, r *report.Report) (Outcome, error) {
|
||||
now := s.clock()
|
||||
if err := r.Check(now, s.difficulty); err != nil {
|
||||
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||
}
|
||||
data, err := r.Bytes()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
hash, err := r.Hash()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var revoked int
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM revocations
|
||||
WHERE author = ? AND (device = ? OR (device = '' AND revoked_at > ?))`,
|
||||
r.Reporter, r.Device, r.Cert.IssuedAt).Scan(&revoked); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if revoked > 0 {
|
||||
return Ignored, ErrRevoked
|
||||
}
|
||||
|
||||
outcome := Inserted
|
||||
var held []byte
|
||||
err = tx.QueryRowContext(ctx,
|
||||
`SELECT data FROM reports WHERE reporter = ? AND l_author = ? AND l_id = ?`,
|
||||
r.Reporter, r.Listing.Author, r.Listing.ID).Scan(&held)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
case err != nil:
|
||||
return Ignored, err
|
||||
default:
|
||||
var old report.Report
|
||||
if err := json.Unmarshal(held, &old); err != nil {
|
||||
return Ignored, fmt.Errorf("store: corrupt report row: %w", err)
|
||||
}
|
||||
if !r.Supersedes(&old) {
|
||||
return Ignored, nil
|
||||
}
|
||||
outcome = Replaced
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT OR REPLACE INTO reports
|
||||
(reporter, l_author, l_id, device, cert_issued_at, category, created_at, expires_at, hash, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
r.Reporter, r.Listing.Author, r.Listing.ID, r.Device, r.Cert.IssuedAt, r.Category,
|
||||
r.CreatedAt, r.ExpiresAt, hash, data); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
// Bounded: when over the cap the oldest reports go.
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM reports WHERE (reporter, l_author, l_id) IN (
|
||||
SELECT reporter, l_author, l_id FROM reports ORDER BY created_at DESC LIMIT -1 OFFSET ?)`,
|
||||
maxReports); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
return outcome, nil
|
||||
}
|
||||
|
||||
// Reports returns up to limit live reports, newest first, for sync.
|
||||
func (s *Store) Reports(ctx context.Context, limit int) ([]*report.Report, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM reports WHERE expires_at > ?
|
||||
ORDER BY created_at DESC, reporter, l_author, l_id LIMIT ?`, s.clock().Unix(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*report.Report
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err := rows.Scan(&data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r report.Report
|
||||
if err := json.Unmarshal(data, &r); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt report row: %w", err)
|
||||
}
|
||||
out = append(out, &r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ReportDigest digests the live reports (reporter, listing and version), so
|
||||
// peers can tell cheaply whether they hold the same ones.
|
||||
func (s *Store) ReportDigest(ctx context.Context) (Digest, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT reporter, l_author, l_id, hash FROM reports WHERE expires_at > ?
|
||||
ORDER BY reporter, l_author, l_id`, s.clock().Unix())
|
||||
if err != nil {
|
||||
return Digest{}, err
|
||||
}
|
||||
return digestOf(rows, 4)
|
||||
}
|
||||
|
||||
// ReportSummary is what this node makes of the reports about one listing.
|
||||
type ReportSummary struct {
|
||||
// Hidden: the node's rules (Trust) hide the listing.
|
||||
Hidden bool `json:"hidden"`
|
||||
// Trusted counts live reports from trusted reporters by category
|
||||
// (withdrawn ones are not counted).
|
||||
Trusted map[string]int `json:"trusted"`
|
||||
// Others counts live reports from reporters this node does not trust:
|
||||
// shown, never counted.
|
||||
Others int `json:"others"`
|
||||
// Signals counts what visitors told this node (see AddSignal).
|
||||
Signals int `json:"signals"`
|
||||
// Own is the node operator's own live report category, if any.
|
||||
Own string `json:"own,omitempty"`
|
||||
}
|
||||
|
||||
// Summary describes the reports about a listing.
|
||||
func (s *Store) Summary(ctx context.Context, author, id string) (ReportSummary, error) {
|
||||
sum := ReportSummary{Trusted: map[string]int{}}
|
||||
trusted := map[string]bool{}
|
||||
for _, k := range s.trust.keys() {
|
||||
trusted[k] = true
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT reporter, category FROM reports
|
||||
WHERE l_author = ? AND l_id = ? AND expires_at > ? AND category != 'withdrawn'`,
|
||||
author, id, s.clock().Unix())
|
||||
if err != nil {
|
||||
return sum, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var reporter, category string
|
||||
if err := rows.Scan(&reporter, &category); err != nil {
|
||||
return sum, err
|
||||
}
|
||||
if reporter == s.trust.Self && reporter != "" {
|
||||
sum.Own = category
|
||||
}
|
||||
if trusted[reporter] {
|
||||
sum.Trusted[category]++
|
||||
} else {
|
||||
sum.Others++
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return sum, err
|
||||
}
|
||||
var hidden int
|
||||
sub, args := s.hiddenSQL()
|
||||
if err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM (`+sub+`) WHERE l_author = ? AND l_id = ?`, append(args, author, id)...).Scan(&hidden); err != nil {
|
||||
return sum, err
|
||||
}
|
||||
sum.Hidden = hidden > 0
|
||||
if err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM signals WHERE l_author = ? AND l_id = ? AND expires_at > ?`,
|
||||
author, id, s.clock().Unix()).Scan(&sum.Signals); err != nil {
|
||||
return sum, err
|
||||
}
|
||||
return sum, nil
|
||||
}
|
||||
|
||||
// --- what visitors tell this node ----------------------------------------------
|
||||
|
||||
// Signal is a tip from a visitor: unsigned, backed only by proof-of-work, and
|
||||
// kept on this node alone. It never hides anything; the operator reads it and
|
||||
// may sign a report of their own.
|
||||
type Signal struct {
|
||||
ID int64 `json:"id"`
|
||||
Author string `json:"author"`
|
||||
ListingID string `json:"listing"`
|
||||
Category string `json:"category"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Work int `json:"work"` // proof-of-work bits behind it
|
||||
// Hash identifies the visitor's request, so repeating it adds nothing.
|
||||
// Set by the caller when adding; not listed.
|
||||
Hash string `json:"-"`
|
||||
}
|
||||
|
||||
// SignalTTL is how long a tip is kept.
|
||||
const SignalTTL = report.MaxLifetime
|
||||
|
||||
// AddSignal stores a visitor's tip. Per listing and overall the number is
|
||||
// bounded; when full the tip with the least work goes.
|
||||
func (s *Store) AddSignal(ctx context.Context, sg Signal) error {
|
||||
if !report.ValidCategory(sg.Category) || sg.Category == report.Withdrawn {
|
||||
return fmt.Errorf("%w: category", ErrInvalid)
|
||||
}
|
||||
now := s.clock().Unix()
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if sg.Hash == "" {
|
||||
return fmt.Errorf("%w: hash", ErrInvalid)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT OR IGNORE INTO signals (hash, l_author, l_id, category, note, created_at, expires_at, work)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
sg.Hash, sg.Author, sg.ListingID, sg.Category, sg.Note, now, now+int64(SignalTTL.Seconds()), sg.Work); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, q := range []struct {
|
||||
where string
|
||||
args []any
|
||||
cap int
|
||||
}{
|
||||
{`l_author = ? AND l_id = ?`, []any{sg.Author, sg.ListingID}, maxSignalsPerList},
|
||||
{`1 = 1`, nil, maxSignals},
|
||||
} {
|
||||
args := append(q.args, q.cap)
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM signals WHERE id IN (
|
||||
SELECT id FROM signals WHERE `+q.where+`
|
||||
ORDER BY work DESC, created_at DESC LIMIT -1 OFFSET ?)`, args...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Signals lists the live tips, strongest first, then newest.
|
||||
func (s *Store) Signals(ctx context.Context) ([]Signal, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, l_author, l_id, category, note, created_at, work FROM signals
|
||||
WHERE expires_at > ? ORDER BY work DESC, created_at DESC LIMIT 500`, s.clock().Unix())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Signal
|
||||
for rows.Next() {
|
||||
var g Signal
|
||||
if err := rows.Scan(&g.ID, &g.Author, &g.ListingID, &g.Category, &g.Note, &g.CreatedAt, &g.Work); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, g)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteSignals dismisses every tip about a listing. It reports how many.
|
||||
func (s *Store) DeleteSignals(ctx context.Context, author, id string) (int64, error) {
|
||||
res, err := s.db.ExecContext(ctx, `DELETE FROM signals WHERE l_author = ? AND l_id = ?`, author, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/report"
|
||||
)
|
||||
|
||||
// reporter is somebody who can sign reports.
|
||||
type reporter struct {
|
||||
root *identity.Identity
|
||||
dev *identity.Device
|
||||
}
|
||||
|
||||
func newReporter(t *testing.T) *reporter {
|
||||
t.Helper()
|
||||
root, _, _ := identity.NewRoot()
|
||||
return &reporter{root: root, dev: newDevice(t, root)}
|
||||
}
|
||||
|
||||
func (r *reporter) key() string { return r.dev.Cert.Author }
|
||||
|
||||
// reportEnv is an env whose store trusts the given reporters; self is the
|
||||
// node's own operator.
|
||||
func reportEnv(t *testing.T, self *reporter, trusted ...*reporter) *env {
|
||||
t.Helper()
|
||||
e := &env{now: t0}
|
||||
e.root, _, _ = identity.NewRoot()
|
||||
e.dev = newDevice(t, e.root)
|
||||
tr := Trust{}
|
||||
if self != nil {
|
||||
tr.Self = self.key()
|
||||
}
|
||||
for _, r := range trusted {
|
||||
tr.Reporters = append(tr.Reporters, r.key())
|
||||
}
|
||||
s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }, Trust: tr})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
e.s = s
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *env) report(t *testing.T, by *reporter, l *listing.Listing, category string, at time.Time) *report.Report {
|
||||
t.Helper()
|
||||
r := &report.Report{
|
||||
Listing: report.Ref{Author: l.Author, ID: l.ID},
|
||||
Category: category,
|
||||
CreatedAt: at.Unix(),
|
||||
ExpiresAt: at.Add(7 * 24 * time.Hour).Unix(),
|
||||
}
|
||||
if err := r.Seal(by.dev, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (e *env) putReport(t *testing.T, r *report.Report) Outcome {
|
||||
t.Helper()
|
||||
o, err := e.s.PutReport(ctx, r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (e *env) visible(t *testing.T) int {
|
||||
t.Helper()
|
||||
ls, err := e.s.Search(ctx, Query{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(ls)
|
||||
}
|
||||
|
||||
func (e *env) everything(t *testing.T) int {
|
||||
t.Helper()
|
||||
ls, err := e.s.Search(ctx, Query{IncludeHidden: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(ls)
|
||||
}
|
||||
|
||||
func TestTheOperatorsOwnReportHidesAtOnce(t *testing.T) {
|
||||
me := newReporter(t)
|
||||
e := reportEnv(t, me)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
e.put(t, e.listing(t, nil))
|
||||
|
||||
e.putReport(t, e.report(t, me, l, report.Scam, e.now))
|
||||
if e.visible(t) != 1 || e.everything(t) != 2 {
|
||||
t.Fatalf("visible %d, all %d: want 1 and 2 (hidden, not deleted)", e.visible(t), e.everything(t))
|
||||
}
|
||||
if _, err := e.s.Get(ctx, l.Author, l.ID); err != nil {
|
||||
t.Fatalf("a hidden listing must stay reachable by its link: %v", err)
|
||||
}
|
||||
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
|
||||
if !sum.Hidden || sum.Own != report.Scam || sum.Trusted[report.Scam] != 1 {
|
||||
t.Fatalf("summary: %+v", sum)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeveralTrustedReportersHideAScam(t *testing.T) {
|
||||
a, b, stranger := newReporter(t), newReporter(t), newReporter(t)
|
||||
e := reportEnv(t, nil, a, b)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
e.putReport(t, e.report(t, a, l, report.Scam, e.now))
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("one trusted scam report is not enough to hide")
|
||||
}
|
||||
e.putReport(t, e.report(t, stranger, l, report.Scam, e.now))
|
||||
e.putReport(t, e.report(t, stranger, l, report.Illegal, e.now.Add(time.Second)))
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("reports from strangers must never hide anything")
|
||||
}
|
||||
e.putReport(t, e.report(t, b, l, report.Scam, e.now))
|
||||
if e.visible(t) != 0 {
|
||||
t.Fatal("two trusted reporters did not hide the listing")
|
||||
}
|
||||
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
|
||||
if sum.Trusted[report.Scam] != 2 || sum.Others != 1 {
|
||||
t.Fatalf("summary: %+v", sum)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOneTrustedReportOfIllegalContentHides(t *testing.T) {
|
||||
a := newReporter(t)
|
||||
e := reportEnv(t, nil, a)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
e.putReport(t, e.report(t, a, l, report.Illegal, e.now))
|
||||
if e.visible(t) != 0 {
|
||||
t.Fatal("a trusted report of illegal content must hide at once")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelsNeverHide(t *testing.T) {
|
||||
a, b := newReporter(t), newReporter(t)
|
||||
e := reportEnv(t, a, b)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
e.putReport(t, e.report(t, a, l, report.Category, e.now))
|
||||
e.putReport(t, e.report(t, b, l, report.Other, e.now))
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("category and other reports must only label a listing")
|
||||
}
|
||||
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
|
||||
if sum.Hidden || sum.Trusted[report.Category] != 1 || sum.Trusted[report.Other] != 1 {
|
||||
t.Fatalf("summary: %+v", sum)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAReporterCanTakeAReportBackAndTheNewerOneWins(t *testing.T) {
|
||||
me := newReporter(t)
|
||||
e := reportEnv(t, me)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
old := e.report(t, me, l, report.Scam, e.now)
|
||||
e.putReport(t, old)
|
||||
if e.visible(t) != 0 {
|
||||
t.Fatal("not hidden")
|
||||
}
|
||||
withdrawn := e.report(t, me, l, report.Withdrawn, e.now.Add(time.Minute))
|
||||
if o := e.putReport(t, withdrawn); o != Replaced {
|
||||
t.Fatalf("withdrawing: %v", o)
|
||||
}
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("a withdrawn report still hides the listing")
|
||||
}
|
||||
// The old one arriving late (sync order is arbitrary) changes nothing.
|
||||
if o := e.putReport(t, old); o != Ignored {
|
||||
t.Fatalf("an older report replaced a newer one: %v", o)
|
||||
}
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("the listing was hidden again by an old report")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportsExpireAndHidingLapsesWithThem(t *testing.T) {
|
||||
me := newReporter(t)
|
||||
e := reportEnv(t, me)
|
||||
l := e.listing(t, func(l *listing.Listing) { l.ExpiresAt = e.now.Add(30 * 24 * time.Hour).Unix() })
|
||||
e.put(t, l)
|
||||
e.putReport(t, e.report(t, me, l, report.Scam, e.now))
|
||||
if e.visible(t) != 0 {
|
||||
t.Fatal("not hidden")
|
||||
}
|
||||
e.now = e.now.Add(8 * 24 * time.Hour)
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("an expired report still hides the listing")
|
||||
}
|
||||
if _, err := e.s.Expire(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reps, _ := e.s.Reports(ctx, 10); len(reps) != 0 {
|
||||
t.Fatal("an expired report was kept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestARevokedReportersReportsGoAway(t *testing.T) {
|
||||
a := newReporter(t)
|
||||
e := reportEnv(t, nil, a)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
e.putReport(t, e.report(t, a, l, report.Illegal, e.now))
|
||||
if e.visible(t) != 0 {
|
||||
t.Fatal("not hidden")
|
||||
}
|
||||
rev, err := identity.Revoke(a.root, a.dev.Cert, e.now, difficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.s.PutRevocation(ctx, rev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("the reports of a revoked device still count")
|
||||
}
|
||||
if _, err := e.s.PutReport(ctx, e.report(t, a, l, report.Illegal, e.now.Add(time.Minute))); !errors.Is(err, ErrRevoked) {
|
||||
t.Fatalf("a revoked device's new report: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidReportsAreRefused(t *testing.T) {
|
||||
a := newReporter(t)
|
||||
e := reportEnv(t, nil, a)
|
||||
l := e.listing(t, nil)
|
||||
r := e.report(t, a, l, report.Scam, e.now)
|
||||
r.Note = "changed after signing"
|
||||
if _, err := e.s.PutReport(ctx, r); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("a tampered report: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportDigestsMatchWhenTheSetsDo(t *testing.T) {
|
||||
a, b := newReporter(t), newReporter(t)
|
||||
x, y := reportEnv(t, nil, a, b), reportEnv(t, nil, a, b)
|
||||
l := x.listing(t, nil)
|
||||
r1, r2 := x.report(t, a, l, report.Scam, x.now), x.report(t, b, l, report.Other, x.now)
|
||||
x.putReport(t, r1)
|
||||
x.putReport(t, r2)
|
||||
y.putReport(t, r2)
|
||||
y.putReport(t, r1)
|
||||
dx, _ := x.s.ReportDigest(ctx)
|
||||
dy, _ := y.s.ReportDigest(ctx)
|
||||
if dx != dy || dx.Count != 2 {
|
||||
t.Fatalf("digests differ: %+v %+v", dx, dy)
|
||||
}
|
||||
y.putReport(t, y.report(t, a, l, report.Withdrawn, y.now.Add(time.Minute)))
|
||||
if dy2, _ := y.s.ReportDigest(ctx); dy2 == dx {
|
||||
t.Fatal("a newer report did not change the digest")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisitorsTipsAreBoundedAndNeverHide(t *testing.T) {
|
||||
e := reportEnv(t, nil)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
for i := 0; i < maxSignalsPerList+10; i++ {
|
||||
err := e.s.AddSignal(ctx, Signal{Hash: fmt.Sprint("h", i), Author: l.Author, ListingID: l.ID, Category: report.Scam, Note: "Betrug", Work: 10 + i%5})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
tips, _ := e.s.Signals(ctx)
|
||||
if len(tips) != maxSignalsPerList {
|
||||
t.Fatalf("%d tips kept, want %d", len(tips), maxSignalsPerList)
|
||||
}
|
||||
if tips[0].Work < tips[len(tips)-1].Work {
|
||||
t.Fatal("tips are not listed strongest first")
|
||||
}
|
||||
if e.visible(t) != 1 {
|
||||
t.Fatal("visitor tips must never hide a listing")
|
||||
}
|
||||
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
|
||||
if sum.Signals != maxSignalsPerList || sum.Hidden {
|
||||
t.Fatalf("summary: %+v", sum)
|
||||
}
|
||||
if err := e.s.AddSignal(ctx, Signal{Hash: "x", Author: l.Author, ListingID: l.ID, Category: "spam"}); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("an unknown category: %v", err)
|
||||
}
|
||||
// Sending the same request twice adds nothing.
|
||||
// (h5x tips were kept: the strongest have the highest i%5, so h59 is among them.)
|
||||
before, _ := e.s.Signals(ctx)
|
||||
if err := e.s.AddSignal(ctx, Signal{Hash: "h59", Author: l.Author, ListingID: l.ID, Category: report.Scam, Work: 99}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _ := e.s.Signals(ctx)
|
||||
if len(after) != len(before) || after[0].Work == 99 {
|
||||
t.Fatalf("a repeated tip was added: %d -> %d, strongest %d", len(before), len(after), after[0].Work)
|
||||
}
|
||||
if n, _ := e.s.DeleteSignals(ctx, l.Author, l.ID); n != int64(maxSignalsPerList) {
|
||||
t.Fatalf("dismissed %d", n)
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,9 @@ type Options struct {
|
||||
// OwnerQueue and MailboxQueue cap the envelopes per listing and per
|
||||
// mailbox; 0 means MaxOwnerQueue and MaxMailboxQueue.
|
||||
OwnerQueue, MailboxQueue int
|
||||
|
||||
// Trust says whose abuse reports hide listings on this node (see Trust).
|
||||
Trust Trust
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
@@ -64,6 +67,7 @@ type Store struct {
|
||||
maxMessages int
|
||||
ownerQueue int
|
||||
mailboxQueue int
|
||||
trust Trust
|
||||
}
|
||||
|
||||
const schema = `
|
||||
@@ -150,6 +154,37 @@ CREATE TABLE IF NOT EXISTS inbox_blocked (
|
||||
blocked_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (author, listing_id, thread)
|
||||
) WITHOUT ROWID;
|
||||
-- Signed abuse reports (internal/report): one per (reporter, listing).
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
reporter TEXT NOT NULL,
|
||||
l_author TEXT NOT NULL,
|
||||
l_id TEXT NOT NULL,
|
||||
device TEXT NOT NULL,
|
||||
cert_issued_at INTEGER NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
data BLOB NOT NULL,
|
||||
PRIMARY KEY (reporter, l_author, l_id)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS reports_listing ON reports (l_author, l_id);
|
||||
CREATE INDEX IF NOT EXISTS reports_expires ON reports (expires_at);
|
||||
-- What visitors told this node about a listing (unsigned, proof-of-work
|
||||
-- only). Never gossiped: they are tips for the operator, who may turn one into
|
||||
-- a signed report.
|
||||
CREATE TABLE IF NOT EXISTS signals (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
hash TEXT NOT NULL UNIQUE, -- of the visitor's request: sending it twice adds nothing
|
||||
l_author TEXT NOT NULL,
|
||||
l_id TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
note TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
work INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS signals_listing ON signals (l_author, l_id);
|
||||
-- The exact address of a listing, only ever read by its owner's node.
|
||||
CREATE TABLE IF NOT EXISTS addresses (
|
||||
author TEXT NOT NULL,
|
||||
@@ -181,6 +216,10 @@ func Open(path string, opt Options) (*Store, error) {
|
||||
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock,
|
||||
msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages,
|
||||
ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue}
|
||||
s.trust = opt.Trust
|
||||
if s.trust.Threshold <= 0 {
|
||||
s.trust.Threshold = DefaultHideThreshold
|
||||
}
|
||||
if s.ownerQueue <= 0 {
|
||||
s.ownerQueue = MaxOwnerQueue
|
||||
}
|
||||
@@ -302,6 +341,9 @@ type Query struct {
|
||||
MinRoomsX2 int
|
||||
Limit int // default 50, max 200
|
||||
Offset int
|
||||
// IncludeHidden also returns listings this node hides because trusted
|
||||
// reporters flagged them (see Trust). They are hidden, never deleted.
|
||||
IncludeHidden bool
|
||||
}
|
||||
|
||||
// Search returns live listings, newest first.
|
||||
@@ -345,6 +387,11 @@ func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error)
|
||||
where = append(where, "rooms_x2 >= ?")
|
||||
args = append(args, q.MinRoomsX2)
|
||||
}
|
||||
if !q.IncludeHidden {
|
||||
sub, subArgs := s.hiddenSQL()
|
||||
where = append(where, "(author, id) NOT IN ("+sub+")")
|
||||
args = append(args, subArgs...)
|
||||
}
|
||||
|
||||
limit := q.Limit
|
||||
if limit <= 0 {
|
||||
@@ -460,6 +507,17 @@ func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outc
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
// Reports signed by a voided device do not count either.
|
||||
if r.AllDevices() {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
`DELETE FROM reports WHERE reporter = ? AND cert_issued_at < ?`, r.Author, r.RevokedAt)
|
||||
} else {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
`DELETE FROM reports WHERE reporter = ? AND device = ?`, r.Author, r.Device)
|
||||
}
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
@@ -525,6 +583,12 @@ func (s *Store) Expire(ctx context.Context) (int64, error) {
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM inbox_seen WHERE expires_at <= ?`, now); err != nil {
|
||||
return n + m + k, err
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM reports WHERE expires_at <= ?`, now); err != nil {
|
||||
return n + m + k, err
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM signals WHERE expires_at <= ?`, now); err != nil {
|
||||
return n + m + k, err
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM inbox_blocked WHERE NOT EXISTS (
|
||||
SELECT 1 FROM listings l WHERE l.author = inbox_blocked.author AND l.id = inbox_blocked.listing_id)`); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user