limits: sync streams, listings per author, inbound connections per IP

A peer may hold 4 sync streams and open 1500 a minute; banned peers get none and cannot redial. A node keeps at most 100 unexpired listings per author (--max-per-author); updates, renewals and deletions of held ones still work. At most 16 inbound connections per public IP or IPv6 /64 (--max-conns-per-ip); local and private addresses are exempt.

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-19 00:30:36 +01:00
co-authored by Claude Sonnet 5.5
parent 0b3ead4b23
commit 5ac02360c4
12 changed files with 527 additions and 23 deletions
+4 -2
View File
@@ -149,8 +149,10 @@ starting a design-heavy item; see "Working with the owner".
that many against the 512 MiB pod limit. that many against the 512 MiB pod limit.
- **Peer scoring beyond the guard.** `internal/p2p/guard.go` drops a peer - **Peer scoring beyond the guard.** `internal/p2p/guard.go` drops a peer
relaying over 1200 messages a minute and bans one that sends 20 invalid ones relaying over 1200 messages a minute and bans one that sends 20 invalid ones
for an hour (gossip only). Not covered: throwaway peer IDs, rate limits on for an hour, limits sync streams (4 at once, 1500 a minute), keeps at most
the sync protocol and the HTTP API, sharing bans between nodes. 100 listings per author (`--max-per-author`) and 16 inbound connections per
public IP (`--max-conns-per-ip`). Not covered: a rate limit on the HTTP API,
attackers with many addresses, sharing bans between nodes (deliberately).
- **Joining without the seeds.** A newcomer whose remembered peers are all in - **Joining without the seeds.** A newcomer whose remembered peers are all in
another region cannot find its region when no DHT server is up (sim: 0 of another region cannot find its region when no DHT server is up (sim: 0 of
114 listings). Remember region peers separately, or ask connected peers. 114 listings). Remember region peers separately, or ask connected peers.
+19 -14
View File
@@ -67,6 +67,10 @@ func cmdRun(args []string) error {
"identity key (64 hex) of a node operator whose abuse reports count here; repeatable. Your own reports always hide a listing on your node") "identity key (64 hex) of a node operator whose abuse reports count here; repeatable. Your own reports always hide a listing on your node")
hideAfter := fs.Int("hide-after", store.DefaultHideThreshold, hideAfter := fs.Int("hide-after", store.DefaultHideThreshold,
"how many trusted operators must report a listing as a scam before your node hides it (one report of illegal content is enough)") "how many trusted operators must report a listing as a scam before your node hides it (one report of illegal content is enough)")
maxPerAuthor := fs.Int("max-per-author", store.DefaultMaxPerAuthor,
"most unexpired listings this node keeps for one author; more are neither stored nor passed on (-1: no limit)")
maxConnsPerIP := fs.Int("max-conns-per-ip", p2p.DefaultConnsPerIP,
"inbound connections accepted from one public IP address (IPv6: one /64); local and private addresses are exempt (-1: no limit)")
fs.Parse(args) fs.Parse(args)
for _, k := range trustReporters { for _, k := range trustReporters {
if !validKey(k) { if !validKey(k) {
@@ -136,7 +140,7 @@ func cmdRun(args []string) error {
} }
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{ st, err := store.Open(filepath.Join(*data, dbFile), store.Options{
Difficulty: *difficulty, MessageDifficulty: *msgDifficulty, Difficulty: *difficulty, MessageDifficulty: *msgDifficulty, MaxPerAuthor: *maxPerAuthor,
Trust: store.Trust{Self: dev.Cert.Author, Reporters: trustReporters, Threshold: *hideAfter}, Trust: store.Trust{Self: dev.Cert.Author, Reporters: trustReporters, Threshold: *hideAfter},
}) })
if err != nil { if err != nil {
@@ -150,19 +154,20 @@ func cmdRun(args []string) error {
defer stop() defer stop()
node, err := p2p.New(ctx, p2p.Config{ node, err := p2p.New(ctx, p2p.Config{
Device: dev, Device: dev,
Store: st, Store: st,
ListenAddrs: listen, ListenAddrs: listen,
Bootstrap: bootstrap, Bootstrap: bootstrap,
Regions: regions, Regions: regions,
MDNS: !*noMDNS, MDNS: !*noMDNS,
DHT: !*noDHT, DHT: !*noDHT,
Public: *public, Public: *public,
MaxConns: *maxConns, MaxConns: *maxConns,
Announce: announceAddrs, MaxConnsPerIP: *maxConnsPerIP,
PeerCache: filepath.Join(*data, peersFile), Announce: announceAddrs,
Difficulty: *difficulty, PeerCache: filepath.Join(*data, peersFile),
Logger: log, Difficulty: *difficulty,
Logger: log,
MessageDifficulty: *msgDifficulty, MessageDifficulty: *msgDifficulty,
}) })
+18 -3
View File
@@ -703,9 +703,24 @@ Findings (see "What is left" in SPECS.md for the open ones):
banned for an hour: closed connection, gossip blacklist; `internal/p2p/guard.go`). banned for an hour: closed connection, gossip blacklist; `internal/p2p/guard.go`).
In the sim the attacker was cut off from all 6 nodes it reached and honest In the sim the attacker was cut off from all 6 nodes it reached and honest
listings still arrived 50 of 50. What it does not stop: an attacker with many listings still arrived 50 of 50. What it does not stop: an attacker with many
peer IDs (a ban costs it nothing but a new key), a peer that sends only peer IDs, a peer that sends only valid but unwanted records, or one that
valid but unwanted records, or one that stays under the limits. The ban is stays under the limits. Three more limits close part of that:
per node, not shared, and covers gossip only, not the sync protocol. - **Sync:** a peer may hold 4 sync streams at once and open 1500 a minute
(a full sync of 100,000 listings is about 1200); a banned peer gets none.
- **Per author:** a node keeps at most 100 unexpired listings per author
(`--max-per-author`, -1 for no limit); a 101st new one is neither stored
nor passed on, while updates, renewals and deletions of held ones still
work. Each node decides for itself, so nodes with different values hold
different sets and anti-entropy keeps offering the refused ones.
- **Per address:** at most 16 inbound connections from one public IP, or one
IPv6 /64 (`--max-conns-per-ip`, -1 for no limit); loopback, private and
link-local addresses are exempt, and a banned peer ID is refused when it
redials. A new peer ID from the same machine therefore does not help.
Behind a Kubernetes service the real source address is only visible with
`externalTrafficPolicy: Local` (the base manifest has it; the nodeport
overlay uses `Cluster`, which hides it, so the limit does nothing there).
Bans are per node and not shared (a shared ban would let one node get
honest ones banned); the HTTP API still has no limits.
3. **The DHT is only as good as its servers.** Only publicly reachable nodes 3. **The DHT is only as good as its servers.** Only publicly reachable nodes
serve it. With every seed gone, a newcomer whose remembered peers are all in serve it. With every seed gone, a newcomer whose remembered peers are all in
another region found nobody (0 of 114 listings), and one that remembers no another region found nobody (0 of 114 listings), and one that remembers no
+2
View File
@@ -511,6 +511,8 @@ func (s *server) seal(w http.ResponseWriter, r *http.Request, l *listing.Listing
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": ")) fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
case errors.Is(err, store.ErrRevoked): case errors.Is(err, store.ErrRevoked):
fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'") fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'")
case errors.Is(err, store.ErrQuota):
fail(w, http.StatusConflict, "this node keeps no more listings for you; delete or let some expire first")
case errors.Is(err, context.Canceled): case errors.Is(err, context.Canceled):
fail(w, http.StatusRequestTimeout, "request cancelled") fail(w, http.StatusRequestTimeout, "request cancelled")
default: default:
+49 -3
View File
@@ -38,8 +38,9 @@ type peerGuard struct {
disconnect func(peer.ID) disconnect func(peer.ID)
self peer.ID self peer.ID
mu sync.Mutex mu sync.Mutex
peers map[peer.ID]*peerCount peers map[peer.ID]*peerCount
streams map[peer.ID]int // sync streams open per peer
} }
type peerCount struct { type peerCount struct {
@@ -47,6 +48,9 @@ type peerCount struct {
total int total int
bad int bad int
noted bool // the flood was already logged this window noted bool // the flood was already logged this window
syncs int // sync requests this window
syncNoted bool
} }
func newPeerGuard(self peer.ID, now func() time.Time, log *slog.Logger, disconnect func(peer.ID)) (*peerGuard, error) { func newPeerGuard(self peer.ID, now func() time.Time, log *slog.Logger, disconnect func(peer.ID)) (*peerGuard, error) {
@@ -54,7 +58,8 @@ func newPeerGuard(self peer.ID, now func() time.Time, log *slog.Logger, disconne
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &peerGuard{now: now, log: log, bl: bl, disconnect: disconnect, self: self, peers: map[peer.ID]*peerCount{}}, nil return &peerGuard{now: now, log: log, bl: bl, disconnect: disconnect, self: self,
peers: map[peer.ID]*peerCount{}, streams: map[peer.ID]int{}}, nil
} }
// wrap puts the guard around a topic validator. Messages we published // wrap puts the guard around a topic validator. Messages we published
@@ -128,5 +133,46 @@ func (g *peerGuard) bad(p peer.ID) {
} }
} }
// Limits on what a peer may ask of us over the sync protocol. A full sync of a
// region of 100,000 listings is about 200 inventory pages and a thousand
// fetches, so the rate leaves room for it; the limit on parallel streams is
// what stops one peer from tying up the node.
const (
maxSyncPerWindow = 1500
maxSyncStreams = 4
)
// beginSync is called when p opens a sync stream. It refuses banned peers,
// peers asking too often and peers with too many streams open; otherwise it
// returns the function to call when the stream is done.
func (g *peerGuard) beginSync(p peer.ID) (end func(), ok bool) {
if g.banned(p) {
return nil, false
}
g.mu.Lock()
defer g.mu.Unlock()
c := g.count(p)
c.syncs++
if c.syncs > maxSyncPerWindow {
if !c.syncNoted {
c.syncNoted = true
g.log.Warn("peer asks for too much sync; refusing its requests until the minute is over",
"peer", p, "limit_per_minute", maxSyncPerWindow)
}
return nil, false
}
if g.streams[p] >= maxSyncStreams {
return nil, false
}
g.streams[p]++
return func() {
g.mu.Lock()
defer g.mu.Unlock()
if g.streams[p]--; g.streams[p] <= 0 {
delete(g.streams, p)
}
}, true
}
// banned reports whether p is currently banned. // banned reports whether p is currently banned.
func (g *peerGuard) banned(p peer.ID) bool { return g.bl.Contains(p) } func (g *peerGuard) banned(p peer.ID) bool { return g.bl.Contains(p) }
+58
View File
@@ -127,6 +127,64 @@ func TestOurOwnMessagesAreNeverLimited(t *testing.T) {
} }
} }
func TestAPeerMayOnlyHoldAFewSyncStreamsAtOnce(t *testing.T) {
f := newGuardFixture(t)
var ends []func()
for i := 0; i < maxSyncStreams; i++ {
end, ok := f.g.beginSync("greedy")
if !ok {
t.Fatalf("stream %d refused within the limit", i)
}
ends = append(ends, end)
}
if _, ok := f.g.beginSync("greedy"); ok {
t.Fatal("a stream over the limit was accepted")
}
if _, ok := f.g.beginSync("other"); !ok {
t.Fatal("one peer's streams must not use up another's")
}
ends[0]()
end, ok := f.g.beginSync("greedy")
if !ok {
t.Fatal("a finished stream must free its place")
}
end()
for _, e := range ends[1:] {
e()
}
if len(f.g.streams) != 1 { // only "other" is still open
t.Fatalf("%d peers still have streams recorded", len(f.g.streams))
}
}
func TestSyncRequestsAreRatedAndBannedPeersAreRefused(t *testing.T) {
f := newGuardFixture(t)
for i := 0; i < maxSyncPerWindow; i++ {
end, ok := f.g.beginSync("busy")
if !ok {
t.Fatalf("request %d within the rate refused", i)
}
end()
}
if _, ok := f.g.beginSync("busy"); ok {
t.Fatal("a request over the rate was accepted")
}
f.now = f.now.Add(guardWindow)
if end, ok := f.g.beginSync("busy"); !ok {
t.Fatal("the next minute must start fresh")
} else {
end()
}
f.verdict = pubsub.ValidationReject
for i := 0; i < maxBadPerWindow; i++ {
f.send("mallory")
}
if _, ok := f.g.beginSync("mallory"); ok {
t.Fatal("a banned peer got a sync stream")
}
}
func TestFinishedWindowsAreForgotten(t *testing.T) { func TestFinishedWindowsAreForgotten(t *testing.T) {
f := newGuardFixture(t) f := newGuardFixture(t)
for i := 0; i < 5000; i++ { for i := 0; i < 5000; i++ {
+111
View File
@@ -0,0 +1,111 @@
package p2p
import (
"net"
"sync"
"sync/atomic"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// DefaultConnsPerIP is how many inbound connections one public IP address may
// hold. A household or an office with a few nodes behind one router stays well
// below it; one machine that mints peer IDs to get around a ban does not.
const DefaultConnsPerIP = 16
// ipGate is the node's connection gater. It refuses an inbound connection when
// its source address already holds the limit, and any connection from a peer the
// guard has banned (so a ban cannot be undone by redialing). Local, private and
// link-local addresses are exempt: a LAN, the simulator and a cluster network
// that hides real source addresses behind one internal address would otherwise
// lock out everyone at once.
type ipGate struct {
max int // per address; 0 means no limit
mu sync.Mutex
counts map[string]int
banned atomic.Pointer[func(peer.ID) bool]
}
func newIPGate(max int) *ipGate { return &ipGate{max: max, counts: map[string]int{}} }
// ipKey names the source of a connection: the IPv4 address, or the /64 of an
// IPv6 one (a single machine usually owns a whole /64). It is empty for
// addresses that are exempt or not IP at all.
func ipKey(a ma.Multiaddr) string {
for _, code := range []int{ma.P_IP4, ma.P_IP6} {
v, err := a.ValueForProtocol(code)
if err != nil {
continue
}
ip := net.ParseIP(v)
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() {
return ""
}
if ip4 := ip.To4(); ip4 != nil {
return ip4.String()
}
return ip.Mask(net.CIDRMask(64, 128)).String() + "/64"
}
return ""
}
func (g *ipGate) full(a ma.Multiaddr) bool {
if g.max <= 0 {
return false
}
k := ipKey(a)
if k == "" {
return false
}
g.mu.Lock()
defer g.mu.Unlock()
return g.counts[k] >= g.max
}
// connection gater
func (g *ipGate) InterceptPeerDial(peer.ID) bool { return true }
func (g *ipGate) InterceptAddrDial(peer.ID, ma.Multiaddr) bool { return true }
func (g *ipGate) InterceptAccept(cm network.ConnMultiaddrs) bool {
return !g.full(cm.RemoteMultiaddr())
}
func (g *ipGate) InterceptSecured(dir network.Direction, p peer.ID, _ network.ConnMultiaddrs) bool {
if dir == network.DirInbound {
if f := g.banned.Load(); f != nil && (*f)(p) {
return false
}
}
return true
}
func (g *ipGate) InterceptUpgraded(network.Conn) (bool, control.DisconnectReason) { return true, 0 }
// notifee: count the inbound connections that got established
func (g *ipGate) track(c network.Conn, delta int) {
if g.max <= 0 || c.Stat().Direction != network.DirInbound {
return
}
k := ipKey(c.RemoteMultiaddr())
if k == "" {
return
}
g.mu.Lock()
defer g.mu.Unlock()
if g.counts[k]+delta <= 0 {
delete(g.counts, k)
return
}
g.counts[k] += delta
}
func (g *ipGate) notifee() network.Notifiee {
return &network.NotifyBundle{
ConnectedF: func(_ network.Network, c network.Conn) { g.track(c, 1) },
DisconnectedF: func(_ network.Network, c network.Conn) { g.track(c, -1) },
}
}
+138
View File
@@ -0,0 +1,138 @@
package p2p
import (
"testing"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
type fakeConnAddrs struct{ remote ma.Multiaddr }
func (f fakeConnAddrs) LocalMultiaddr() ma.Multiaddr { return nil }
func (f fakeConnAddrs) RemoteMultiaddr() ma.Multiaddr { return f.remote }
func mustAddr(t *testing.T, s string) ma.Multiaddr {
t.Helper()
a, err := ma.NewMultiaddr(s)
if err != nil {
t.Fatal(err)
}
return a
}
func TestIPKeysGroupASourceAndExemptLocalAddresses(t *testing.T) {
for addr, want := range map[string]string{
"/ip4/203.0.113.7/tcp/4001": "203.0.113.7",
"/ip4/203.0.113.7/udp/9/quic-v1": "203.0.113.7",
"/ip6/2001:db8:1:2:aaaa::1/tcp/4001": "2001:db8:1:2::/64",
"/ip6/2001:db8:1:2:bbbb::9/tcp/4001": "2001:db8:1:2::/64",
"/ip4/127.0.0.1/tcp/4001": "",
"/ip4/192.168.1.20/tcp/4001": "",
"/ip4/10.1.2.3/tcp/4001": "",
"/ip6/::1/tcp/4001": "",
"/ip6/fe80::1/tcp/4001": "",
"/ip6/fd00::5/tcp/4001": "",
"/dns4/example.org/tcp/4001": "",
} {
if got := ipKey(mustAddr(t, addr)); got != want {
t.Errorf("ipKey(%s) = %q, want %q", addr, got, want)
}
}
}
func TestOneAddressCannotHoldMoreConnectionsThanTheLimit(t *testing.T) {
g := newIPGate(2)
a := fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.7/tcp/1000")}
other := fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.8/tcp/1000")}
if !g.InterceptAccept(a) {
t.Fatal("first connection refused")
}
g.counts["203.0.113.7"] = 1
if !g.InterceptAccept(a) {
t.Fatal("second connection refused")
}
g.counts["203.0.113.7"] = 2
if g.InterceptAccept(a) {
t.Fatal("a third connection from one address was accepted")
}
if !g.InterceptAccept(other) {
t.Fatal("another address must not be affected")
}
g.counts["203.0.113.7"] = 1 // one closed
if !g.InterceptAccept(a) {
t.Fatal("a closed connection must free its place")
}
local := fakeConnAddrs{mustAddr(t, "/ip4/127.0.0.1/tcp/1000")}
for i := 0; i < 50; i++ {
if !g.InterceptAccept(local) {
t.Fatal("local addresses are exempt")
}
}
if newIPGate(0).full(a.remote) {
t.Fatal("a limit of zero means no limit")
}
}
// fakeConn answers only what the gate asks of a connection.
type fakeConn struct {
network.Conn
remote ma.Multiaddr
dir network.Direction
}
func (c fakeConn) RemoteMultiaddr() ma.Multiaddr { return c.remote }
func (c fakeConn) Stat() network.ConnStats {
return network.ConnStats{Stats: network.Stats{Direction: c.dir}}
}
func TestEstablishedInboundConnectionsAreCountedUntilTheyClose(t *testing.T) {
g := newIPGate(2)
n := g.notifee()
in := func() fakeConn {
return fakeConn{remote: mustAddr(t, "/ip4/203.0.113.7/tcp/1000"), dir: network.DirInbound}
}
out := fakeConn{remote: mustAddr(t, "/ip4/203.0.113.7/tcp/1000"), dir: network.DirOutbound}
a, b := in(), in()
n.Connected(nil, a)
n.Connected(nil, out) // ones we dialed do not count
if g.full(a.remote) {
t.Fatal("one inbound connection fills a limit of two")
}
n.Connected(nil, b)
if !g.full(a.remote) {
t.Fatal("two inbound connections must fill a limit of two")
}
n.Disconnected(nil, out)
if !g.full(a.remote) {
t.Fatal("closing an outbound connection must not free an inbound place")
}
n.Disconnected(nil, a)
if g.full(a.remote) {
t.Fatal("a closed connection must free its place")
}
n.Disconnected(nil, b)
if len(g.counts) != 0 {
t.Fatalf("%d addresses still counted after everything closed", len(g.counts))
}
}
func TestBannedPeersCannotComeBack(t *testing.T) {
g := newIPGate(2)
cm := fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.7/tcp/1000")}
if !g.InterceptSecured(network.DirInbound, "mallory", cm) {
t.Fatal("nobody is banned before the guard says so")
}
banned := func(p peer.ID) bool { return p == "mallory" }
g.banned.Store(&banned)
if g.InterceptSecured(network.DirInbound, "mallory", cm) {
t.Fatal("a banned peer got back in")
}
if !g.InterceptSecured(network.DirInbound, "alice", cm) {
t.Fatal("an innocent peer was refused")
}
if !g.InterceptSecured(network.DirOutbound, "mallory", cm) {
t.Fatal("we may still dial out; only inbound is gated")
}
}
+14 -1
View File
@@ -116,6 +116,10 @@ type Config struct {
// (which scales with memory) for any other; a negative number keeps // (which scales with memory) for any other; a negative number keeps
// libp2p's default even for a Public node. // libp2p's default even for a Public node.
MaxConns int MaxConns int
// MaxConnsPerIP is how many inbound connections one public IP address (an
// IPv6 /64) may hold; local and private addresses are exempt. Zero means
// DefaultConnsPerIP, a negative number no limit.
MaxConnsPerIP int
// ExtraOptions are added to the libp2p host's options; the simulator uses // ExtraOptions are added to the libp2p host's options; the simulator uses
// them to put latency and connection loss on the transport. // them to put latency and connection loss on the transport.
ExtraOptions []libp2p.Option ExtraOptions []libp2p.Option
@@ -233,6 +237,12 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
} }
opts = append(opts, limits) opts = append(opts, limits)
} }
perIP := cfg.MaxConnsPerIP
if perIP == 0 {
perIP = DefaultConnsPerIP
}
gate := newIPGate(max(perIP, 0))
opts = append(opts, libp2p.ConnectionGater(gate))
opts = append(opts, cfg.ExtraOptions...) opts = append(opts, cfg.ExtraOptions...)
if cfg.Bandwidth != nil { if cfg.Bandwidth != nil {
opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth)) opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth))
@@ -274,6 +284,9 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
n.Close() n.Close()
return nil, err return nil, err
} }
h.Network().Notify(gate.notifee())
banned := n.guard.banned
gate.banned.Store(&banned)
n.ps, err = pubsub.NewGossipSub(nctx, h, n.ps, err = pubsub.NewGossipSub(nctx, h,
pubsub.WithMaxMessageSize(listing.MaxSize+4096), pubsub.WithMaxMessageSize(listing.MaxSize+4096),
pubsub.WithFloodPublish(true), pubsub.WithFloodPublish(true),
@@ -612,7 +625,7 @@ func (n *Node) subscribeRegion(region string) error {
switch out, err := n.cfg.Store.Put(n.ctx, l); { switch out, err := n.cfg.Store.Put(n.ctx, l); {
case err == nil: case err == nil:
n.noteListing(n.ctx, l, out, "gossip", msg.ReceivedFrom) n.noteListing(n.ctx, l, out, "gossip", msg.ReceivedFrom)
case errors.Is(err, store.ErrRevoked): case errors.Is(err, store.ErrRevoked), errors.Is(err, store.ErrQuota):
default: default:
n.log.Warn("store listing", "err", err) n.log.Warn("store listing", "err", err)
} }
+6
View File
@@ -61,6 +61,12 @@ type syncRequest struct {
func (n *Node) handleSync(s network.Stream) { func (n *Node) handleSync(s network.Stream) {
defer s.Close() defer s.Close()
end, ok := n.guard.beginSync(s.Conn().RemotePeer())
if !ok {
_ = s.Reset()
return
}
defer end()
_ = s.SetDeadline(time.Now().Add(syncTimeout)) _ = s.SetDeadline(time.Now().Add(syncTimeout))
var req syncRequest var req syncRequest
+74
View File
@@ -0,0 +1,74 @@
package store
import (
"errors"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
)
func newQuotaEnv(t *testing.T, max int) *env {
t.Helper()
e := &env{now: t0}
e.root, _, _ = identity.NewRoot()
e.dev = newDevice(t, e.root)
s, err := Open(":memory:", Options{Difficulty: difficulty, MaxPerAuthor: max, Clock: func() time.Time { return e.now }})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
e.s = s
return e
}
func TestAnAuthorCannotHoldMoreNewListingsThanTheQuota(t *testing.T) {
e := newQuotaEnv(t, 3)
var held []*listing.Listing
for i := 0; i < 3; i++ {
l := e.listing(t, nil)
e.put(t, l)
held = append(held, l)
}
if _, err := e.s.Put(ctx, e.listing(t, nil)); !errors.Is(err, ErrQuota) {
t.Fatalf("a fourth listing: err = %v, want ErrQuota", err)
}
// Another author is unaffected.
other := e.sibling(t)
other.root, _, _ = identity.NewRoot()
other.dev = newDevice(t, other.root)
other.s.maxPerAuthor = 3
other.put(t, other.listing(t, nil))
// What the node already holds can still be changed, renewed and deleted.
upd := e.listing(t, func(l *listing.Listing) { l.ID, l.Seq, l.Title = held[0].ID, 2, "Neu" })
if o := e.put(t, upd); o != Replaced {
t.Fatalf("update at the quota: %v, want replaced", o)
}
if o := e.put(t, e.tombstone(t, held[1])); o != Replaced {
t.Fatalf("deleting at the quota: %v, want replaced", o)
}
}
func TestExpiredListingsDoNotCountAgainstTheQuota(t *testing.T) {
e := newQuotaEnv(t, 2)
e.put(t, e.listing(t, nil))
e.put(t, e.listing(t, nil))
if _, err := e.s.Put(ctx, e.listing(t, nil)); !errors.Is(err, ErrQuota) {
t.Fatalf("err = %v, want ErrQuota", err)
}
e.now = e.now.Add(8 * 24 * time.Hour) // both have expired
if _, err := e.s.Put(ctx, e.listing(t, nil)); err != nil {
t.Fatalf("after the old ones expired: %v", err)
}
}
func TestTheDefaultQuotaIsHundredAndNegativeMeansNone(t *testing.T) {
if e := newEnv(t); e.s.maxPerAuthor != DefaultMaxPerAuthor || DefaultMaxPerAuthor != 100 {
t.Fatalf("default quota %d", e.s.maxPerAuthor)
}
if e := newQuotaEnv(t, -1); e.s.maxPerAuthor != 0 {
t.Fatal("a negative quota must switch the cap off")
}
}
+34
View File
@@ -26,6 +26,10 @@ var (
ErrNotFound = errors.New("store: not found") ErrNotFound = errors.New("store: not found")
// ErrRevoked is returned for listings signed by a revoked device. // ErrRevoked is returned for listings signed by a revoked device.
ErrRevoked = errors.New("store: device revoked") ErrRevoked = errors.New("store: device revoked")
// ErrQuota is returned for a new listing from an author who already has
// the most this node keeps (Options.MaxPerAuthor). Updates, renewals and
// deletions of listings the node holds are never refused for this.
ErrQuota = errors.New("store: this author has too many listings on this node")
) )
// Outcome tells the caller what Put did, so the p2p layer knows whether a // Outcome tells the caller what Put did, so the p2p layer knows whether a
@@ -57,8 +61,19 @@ type Options struct {
// Trust says whose abuse reports hide listings on this node (see Trust). // Trust says whose abuse reports hide listings on this node (see Trust).
Trust Trust Trust Trust
// MaxPerAuthor caps the unexpired listings (tombstones included) this node
// keeps for one author; 0 means DefaultMaxPerAuthor, negative no cap. A
// listing past the cap is not stored and so not passed on. Each node
// decides for itself, so nodes with different caps hold different sets.
MaxPerAuthor int
} }
// DefaultMaxPerAuthor is generous for a person or a small agency and makes one
// identity a poor way to fill a node: more takes more identities, and each
// listing of each costs its own proof-of-work.
const DefaultMaxPerAuthor = 100
type Store struct { type Store struct {
db *sql.DB db *sql.DB
difficulty int difficulty int
@@ -68,6 +83,7 @@ type Store struct {
ownerQueue int ownerQueue int
mailboxQueue int mailboxQueue int
trust Trust trust Trust
maxPerAuthor int // 0: no cap
} }
const schema = ` const schema = `
@@ -217,6 +233,12 @@ func Open(path string, opt Options) (*Store, error) {
msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages, msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages,
ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue} ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue}
s.trust = opt.Trust s.trust = opt.Trust
switch {
case opt.MaxPerAuthor == 0:
s.maxPerAuthor = DefaultMaxPerAuthor
case opt.MaxPerAuthor > 0:
s.maxPerAuthor = opt.MaxPerAuthor
}
if s.trust.Threshold <= 0 { if s.trust.Threshold <= 0 {
s.trust.Threshold = DefaultHideThreshold s.trust.Threshold = DefaultHideThreshold
} }
@@ -284,6 +306,18 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
outcome := Inserted outcome := Inserted
switch { switch {
case errors.Is(err, sql.ErrNoRows): case errors.Is(err, sql.ErrNoRows):
if s.maxPerAuthor > 0 {
var held int
err = tx.QueryRowContext(ctx,
`SELECT COUNT(*) FROM listings WHERE author = ? AND expires_at > ?`,
l.Author, s.clock().Unix()).Scan(&held)
if err != nil {
return Ignored, err
}
if held >= s.maxPerAuthor {
return Ignored, ErrQuota
}
}
case err != nil: case err != nil:
return Ignored, err return Ignored, err
default: default: