diff --git a/derp/derpserver/derpserver.go b/derp/derpserver/derpserver.go index 8ce67d501..62fe5fa06 100644 --- a/derp/derpserver/derpserver.go +++ b/derp/derpserver/derpserver.go @@ -259,6 +259,11 @@ type Server struct { // maps from netip.AddrPort to a client's public key keyOfAddr map[netip.AddrPort]key.NodePublic rateConfig RateConfig // per-client DERP frame rate limiting config + // rateExemptAddrs is the set of client public IPs (from + // rateConfig.ExemptAddrs, unmapped) whose rate limit is overridden to 0. + // It is only consulted when a client's limiter is (re)configured, never + // on the per-frame path. + rateExemptAddrs set.Set[netip.Addr] } // clientSet represents 1 or more *sclients. @@ -675,6 +680,12 @@ type RateConfig struct { // will be increased to [minRateLimitTokenBucketSize] before application. Only // relevant if PerClientRateLimitBytesPerSec is nonzero. PerClientRateBurstBytes uint64 `json:",omitzero"` + // ExemptAddrs are client public IPv4 or IPv6 addresses that are exempt + // from rate limiting. Clients connecting from these addresses have their + // rate limit overridden to 0 (unlimited). IPv4-mapped IPv6 addresses are + // treated as their IPv4 equivalent. Only relevant if + // PerClientRateLimitBytesPerSec is nonzero. + ExemptAddrs []netip.Addr `json:",omitempty"` } // LoadRateConfig reads and JSON-unmarshals a [RateConfig] from the file at path. @@ -690,6 +701,11 @@ func LoadRateConfig(path string) (RateConfig, error) { if err := json.Unmarshal(b, &rc); err != nil { return RateConfig{}, fmt.Errorf("error parsing rate config: %w", err) } + for i, ip := range rc.ExemptAddrs { + if !ip.IsValid() { + return RateConfig{}, fmt.Errorf("error parsing rate config: invalid ExemptAddrs[%d]", i) + } + } return rc, nil } @@ -701,33 +717,62 @@ func (s *Server) LoadAndApplyRateConfig(path string) error { return err } applied := s.UpdateRateLimits(rc) - s.logf("rate config applied: client-rate=%d bytes/sec, client-burst=%d bytes", - applied.PerClientRateLimitBytesPerSec, applied.PerClientRateBurstBytes) + s.logf("rate config applied: client-rate=%d bytes/sec, client-burst=%d bytes, exempt-addrs=%v", + applied.PerClientRateLimitBytesPerSec, applied.PerClientRateBurstBytes, applied.ExemptAddrs) return nil } // UpdateRateLimits sets the receive rate limits, updating all existing client // connections. It returns the applied config, which may differ from rc. If the -// per-client rate limits is 0, rate limiting is disabled. Mesh peers are always -// exempt from rate limiting. +// per-client rate limits is 0, rate limiting is disabled. Mesh peers and +// clients connecting from one of rc.ExemptAddrs are always exempt from rate +// limiting. func (s *Server) UpdateRateLimits(rc RateConfig) (applied RateConfig) { s.mu.Lock() defer s.mu.Unlock() + var exempt set.Set[netip.Addr] if rc.PerClientRateLimitBytesPerSec == 0 { // all rate limiting is disabled rc = RateConfig{} } else { rc.PerClientRateBurstBytes = max(rc.PerClientRateBurstBytes, minRateLimitTokenBucketSize) + var addrs []netip.Addr + for _, ip := range rc.ExemptAddrs { + if !ip.IsValid() { + continue + } + ip = ip.Unmap() + if exempt.Contains(ip) { + continue + } + exempt.Make() + exempt.Add(ip) + addrs = append(addrs, ip) + } + rc.ExemptAddrs = addrs } s.rateConfig = rc + s.rateExemptAddrs = exempt for _, cs := range s.clients.All() { - cs.ForeachClient(func(c *sclient) { - c.setRateLimit(rc.PerClientRateLimitBytesPerSec, rc.PerClientRateBurstBytes) - }) + cs.ForeachClient(s.applyRateLimitLocked) } return rc } +// applyRateLimitLocked configures c's receive rate limiter from the server's +// current rate config. Clients whose remote IP is in [Server.rateExemptAddrs] +// have their limit overridden to 0, which leaves [sclient.recvLim] nil so that +// [sclient.rateLimit] does no extra per-frame work for them. +// +// s.mu must be held. +func (s *Server) applyRateLimitLocked(c *sclient) { + bytesPerSec := s.rateConfig.PerClientRateLimitBytesPerSec + if bytesPerSec != 0 && s.rateExemptAddrs.Contains(c.remoteIPPort.Addr().Unmap()) { + bytesPerSec = 0 + } + c.setRateLimit(bytesPerSec, s.rateConfig.PerClientRateBurstBytes) +} + // HasMeshKey reports whether the server is configured with a mesh key. func (s *Server) HasMeshKey() bool { return !s.meshKey.IsZero() } @@ -905,7 +950,7 @@ func (s *Server) registerClient(c *sclient) { s.mu.Lock() defer s.mu.Unlock() - c.setRateLimit(s.rateConfig.PerClientRateLimitBytesPerSec, s.rateConfig.PerClientRateBurstBytes) + s.applyRateLimitLocked(c) cs, ok := s.clients.Load(c.key) if !ok { @@ -1561,8 +1606,9 @@ func (c *sclient) handleFrameSendPacket(_ derp.FrameType, fl uint32) error { return c.sendPkt(dst, p) } -// setRateLimit updates the receive rate limiter. When bytesPerSec is 0, or the -// client is a mesh peer, the limiter is set to nil so that [sclient.rateLimit] is a no-op. +// setRateLimit updates the receive rate limiter. When bytesPerSec is 0 (rate +// limiting disabled or the client's address is exempt), or the client is a mesh +// peer, the limiter is set to nil so that [sclient.rateLimit] is a no-op. func (c *sclient) setRateLimit(bytesPerSec, burst uint64) { if c.canMesh || bytesPerSec == 0 { c.recvLim.Store(nil) @@ -1601,8 +1647,8 @@ func rateLimitWait(ctx context.Context, lim *xrate.Limiter, n int, now time.Time // within the buffered reader to fill back in with data from // the TCP socket. Pacing reads acts as a form of natural // backpressure via TCP flow control. -// When rate limiting is disabled or the client is a mesh peer, recvLim is nil -// and this is a no-op. +// When rate limiting is disabled, the client is a mesh peer, or the client's +// address is exempt, recvLim is nil and this is a no-op. func (c *sclient) rateLimit(n int) error { if lim := c.recvLim.Load(); lim != nil { newTimer := func(d time.Duration) (<-chan time.Time, func() bool) { @@ -2161,8 +2207,9 @@ type sclient struct { peerGoneLim *rate.Limiter // recvLim is the receive rate limiter. When rate limiting is enabled for a - // non-mesh client, it points to a [xrate.Limiter]. When rate limiting - // is disabled or the client is a mesh peer, it is nil and [sclient.rateLimit] + // non-mesh, non-exempt client, it points to a [xrate.Limiter]. When rate + // limiting is disabled, the client is a mesh peer, or the client's remote + // IP is in [RateConfig.ExemptAddrs], it is nil and [sclient.rateLimit] // is a no-op. Updated atomically by [sclient.setRateLimit] so that // [sclient.rateLimit] can load it without holding [Server.mu]. // diff --git a/derp/derpserver/derpserver_test.go b/derp/derpserver/derpserver_test.go index 0c1dfce93..2a584f3c5 100644 --- a/derp/derpserver/derpserver_test.go +++ b/derp/derpserver/derpserver_test.go @@ -1680,6 +1680,34 @@ func TestPerClientRateLimit(t *testing.T) { }) } +// BenchmarkRateLimit measures the per-frame cost of [sclient.rateLimit], which +// is called on every received DERP frame. +func BenchmarkRateLimit(b *testing.B) { + const frameSize = 1000 + b.Run("no_limiter", func(b *testing.B) { + // Rate limiting disabled, mesh peer, or exempt address. + c := &sclient{ctx: context.Background()} + b.ReportAllocs() + for b.Loop() { + if err := c.rateLimit(frameSize); err != nil { + b.Fatal(err) + } + } + }) + b.Run("limiter_no_wait", func(b *testing.B) { + s := New(key.NewNode(), logger.Discard) + defer s.Close() + c := &sclient{ctx: context.Background(), s: s} + c.recvLim.Store(rate.NewLimiter(rate.Inf, minRateLimitTokenBucketSize)) + b.ReportAllocs() + for b.Loop() { + if err := c.rateLimit(frameSize); err != nil { + b.Fatal(err) + } + } + }) +} + // zeroTimer returns a timer that fires immediately. func zeroTimer(_ time.Duration) (<-chan time.Time, func() bool) { t := time.NewTimer(0) @@ -1884,6 +1912,90 @@ func TestUpdateRateLimits(t *testing.T) { } } +func TestRateLimitExemptAddrs(t *testing.T) { + const ( + testRate = minRateLimitTokenBucketSize + 1 + testBurst = minRateLimitTokenBucketSize + 2 + ) + wantLimited := func(t *testing.T, name string, c *sclient, limited bool) { + t.Helper() + lim := c.recvLim.Load() + if limited && lim == nil { + t.Errorf("%s: expected non-nil limiter", name) + } + if !limited && lim != nil { + t.Errorf("%s: expected nil limiter (exempt), got limit=%v", name, lim.Limit()) + } + } + + s := New(key.NewNode(), t.Logf) + defer s.Close() + + // Clients registered before any rate config is applied. + v4 := addDebugTestClient(s, key.NewNode().Public(), "203.0.113.1:1234", derp.ClientInfo{}) + v6 := addDebugTestClient(s, key.NewNode().Public(), "[2001:db8::1]:1234", derp.ClientInfo{}) + mapped := addDebugTestClient(s, key.NewNode().Public(), "[::ffff:203.0.113.2]:1234", derp.ClientInfo{}) + other := addDebugTestClient(s, key.NewNode().Public(), "203.0.113.99:1234", derp.ClientInfo{}) + + rc := RateConfig{ + PerClientRateLimitBytesPerSec: testRate, + PerClientRateBurstBytes: testBurst, + ExemptAddrs: []netip.Addr{ + netip.MustParseAddr("203.0.113.1"), + netip.MustParseAddr("2001:db8::1"), + netip.MustParseAddr("203.0.113.2"), + netip.MustParseAddr("::ffff:203.0.113.1"), // dup of 203.0.113.1 once unmapped + {}, // invalid; ignored + }, + } + applied := s.UpdateRateLimits(rc) + wantApplied := []netip.Addr{ + netip.MustParseAddr("203.0.113.1"), + netip.MustParseAddr("2001:db8::1"), + netip.MustParseAddr("203.0.113.2"), + } + if !reflect.DeepEqual(applied.ExemptAddrs, wantApplied) { + t.Errorf("applied.ExemptAddrs = %v; want %v", applied.ExemptAddrs, wantApplied) + } + + wantLimited(t, "v4", v4, false) + wantLimited(t, "v6", v6, false) + wantLimited(t, "v4-mapped", mapped, false) + wantLimited(t, "other", other, true) + verifyLimiter(t, other.recvLim.Load(), applied) + + // Exempt rateLimit calls are a no-op. + v4.ctx = context.Background() + if err := v4.rateLimit(minRateLimitTokenBucketSize * 10); err != nil { + t.Fatalf("exempt rateLimit: %v", err) + } + + // Clients registered after the config is applied honor the exemption. + lateExempt := addDebugTestClient(s, key.NewNode().Public(), "[2001:db8::1]:5678", derp.ClientInfo{}) + lateOther := addDebugTestClient(s, key.NewNode().Public(), "[2001:db8::2]:5678", derp.ClientInfo{}) + wantLimited(t, "lateExempt", lateExempt, false) + wantLimited(t, "lateOther", lateOther, true) + + // Removing an address from the exempt list applies the limit to it. + rc.ExemptAddrs = []netip.Addr{netip.MustParseAddr("2001:db8::1")} + s.UpdateRateLimits(rc) + wantLimited(t, "v4", v4, true) + wantLimited(t, "v6", v6, false) + wantLimited(t, "v4-mapped", mapped, true) + wantLimited(t, "lateExempt", lateExempt, false) + + // Disabling rate limiting clears the exempt list and all limiters. + if got := s.UpdateRateLimits(RateConfig{ExemptAddrs: rc.ExemptAddrs}); !reflect.DeepEqual(got, RateConfig{}) { + t.Errorf("applied = %+v; want zero", got) + } + if s.rateExemptAddrs.Len() != 0 { + t.Errorf("rateExemptAddrs = %v; want empty", s.rateExemptAddrs) + } + for name, c := range map[string]*sclient{"v4": v4, "v6": v6, "other": other, "lateOther": lateOther} { + wantLimited(t, name, c, false) + } +} + func TestLoadRateConfig(t *testing.T) { for _, tt := range []struct { name string @@ -1898,6 +2010,10 @@ func TestLoadRateConfig(t *testing.T) { PerClientRateLimitBytesPerSec: 1, }}, {"zeros", `{"PerClientRateLimitBytesPerSec": 0, "PerClientRateBurstBytes": 0}`, RateConfig{}}, + {"exempt_addrs", `{"PerClientRateLimitBytesPerSec": 1, "ExemptAddrs": ["192.0.2.1", "2001:db8::1"]}`, RateConfig{ + PerClientRateLimitBytesPerSec: 1, + ExemptAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.1"), netip.MustParseAddr("2001:db8::1")}, + }}, {"empty_json", `{}`, RateConfig{}}, } { t.Run(tt.name, func(t *testing.T) { @@ -1923,6 +2039,9 @@ func TestLoadRateConfig(t *testing.T) { {"empty_path", "", ""}, {"missing_file", filepath.Join(t.TempDir(), "nonexistent.json"), ""}, {"invalid_json", "", "not json"}, + {"invalid_exempt_addr", "", `{"ExemptAddrs": ["not-an-ip"]}`}, + {"empty_exempt_addr", "", `{"ExemptAddrs": [""]}`}, + {"exempt_prefix_not_addr", "", `{"ExemptAddrs": ["192.0.2.0/24"]}`}, } { t.Run(tt.name, func(t *testing.T) { path := tt.path