niko_trust/internal/server/ratelimit_test.go
Niko Marmeladkov 9d66003689
Initial commit: signed-object trust relay, verifier, and docs
- server: relay storing signed objects (PUT/GET), per-IP rate limiting,
  per-subject quota (1000), one-response-per-request, pagination,
  /v1/healthz /v1/readyz /v1/metrics
- verify: signature-verifying trust evaluator; every object is checked via
  env.Verify(), approvals via VerifyApprovalResponse, revocations via
  VerifyRevocationOf; k-of-n approval quorum
- docs: TRUST-MODEL.md and API.md describing issuer-anchored signatures and
  the endpoint/status-code contract
- tests: server, verify, and ratelimit packages
2026-08-12 22:36:49 +03:00

60 lines
1.4 KiB
Go

package server
import (
"net/http"
"testing"
"time"
)
func TestAllowUnderLimit(t *testing.T) {
l := newIPLimiter(3, time.Minute)
for i := 0; i < 3; i++ {
if !l.allow("1.2.3.4") {
t.Fatalf("request %d: expected allow", i)
}
}
if l.allow("1.2.3.4") {
t.Fatal("expected deny once limit reached")
}
}
func TestDistinctIPsIndependent(t *testing.T) {
l := newIPLimiter(1, time.Minute)
if !l.allow("10.0.0.1") {
t.Fatal("ip1 first request should be allowed")
}
if l.allow("10.0.0.1") {
t.Fatal("ip1 second request should be denied")
}
if !l.allow("10.0.0.2") {
t.Fatal("ip2 should have its own budget")
}
}
func TestWindowReset(t *testing.T) {
l := newIPLimiter(2, 20*time.Millisecond)
if !l.allow("9.9.9.9") || !l.allow("9.9.9.9") {
t.Fatal("first two requests should be allowed")
}
if l.allow("9.9.9.9") {
t.Fatal("third request within window should be denied")
}
time.Sleep(30 * time.Millisecond)
if !l.allow("9.9.9.9") {
t.Fatal("request after window expiry should be allowed again")
}
}
func TestClientIP(t *testing.T) {
withPort, _ := http.NewRequest(http.MethodGet, "/", nil)
withPort.RemoteAddr = "192.168.1.5:54321"
if got := clientIP(withPort); got != "192.168.1.5" {
t.Fatalf("expected 192.168.1.5, got %q", got)
}
noPort, _ := http.NewRequest(http.MethodGet, "/", nil)
noPort.RemoteAddr = "10.0.0.1"
if got := clientIP(noPort); got != "10.0.0.1" {
t.Fatalf("expected 10.0.0.1, got %q", got)
}
}