about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-10-28 10:22:07 +0000
committerPjotr <wrk@bosa.lan>2026-10-28 10:22:07 +0000
commit065a587bc0c8ca2531e0cbb76fecb75b4910ec77 (patch)
tree89fe4c5653247b32523b0920dba43633fb8f7053
parent45ff466ca4f1ad8ea651f4bbad7f31d46d21651e (diff)
downloadgn-machines-065a587bc0c8ca2531e0cbb76fecb75b4910ec77.tar.gz
cgit: Test per-client budgets and /plain/ handling.
The rate-limit tests could not catch the shared-bucket bug: they always
spoke from one address, so "per client IP" and "per proxy IP" looked
identical.  Give each test its own X-Forwarded-For bucket (the listener
trusts 127.0.0.1, see trusted-proxies) and add the regression:

* t19/t20 keep covering the expensive and general limits, now with the
  60r/m burst 20 and a bucket nobody else spends;
* t21 exhausting one forwarded client's expensive budget must leave the
  next one alone;
* t22 the same for the general (server-level) budget;
* t23/t24 /plain/ serves curl and wget and answers 403 to anything else;
* t25 /plain/ is not challenged by Anubis.

t10 identifies as curl now, because /plain/ is an allowlist.
-rw-r--r--genenetwork/services/test/cgit_http_tests.py129
1 files changed, 93 insertions, 36 deletions
diff --git a/genenetwork/services/test/cgit_http_tests.py b/genenetwork/services/test/cgit_http_tests.py
index b87d323..fae359a 100644
--- a/genenetwork/services/test/cgit_http_tests.py
+++ b/genenetwork/services/test/cgit_http_tests.py
@@ -6,6 +6,13 @@ headless browser is needed.  They assume the container is running with
 its nginx on http://127.0.0.1 (port 80) and the demo repository (seeded
 at first boot) in /srv/git.
 
+The rate-limit tests (t19-t22) rely on the listener trusting 127.0.0.1
+for the client address (the `trusted-proxies` field of
+cgit-web-configuration, i.e. set_real_ip_from/real_ip_header in nginx),
+so they can send X-Forwarded-For and claim a client bucket of their own.
+They need the plain front-end: behind Anubis the browsing URIs never
+reach cgit (t17/t18 cover that variant).
+
 Usage:
     BASE_URL=http://127.0.0.1 python3 cgit_http_tests.py
 """
@@ -13,7 +20,6 @@ Usage:
 import os
 import re
 import sys
-import time
 import urllib.error
 import urllib.request
 
@@ -39,9 +45,10 @@ class Response:
         return needle in self.body
 
 
-def request(path, timeout=20):
+def request(path, timeout=20, headers=None):
     url = BASE_URL + path
-    req = urllib.request.Request(url, headers={"User-Agent": "cgit-test/1.0"})
+    req = urllib.request.Request(
+        url, headers={"User-Agent": "cgit-test/1.0", **(headers or {})})
     try:
         with urllib.request.urlopen(req, timeout=timeout) as r:
             return Response(r.status,
@@ -121,7 +128,9 @@ def t09():
 
 @test("t10 plain (blob) view shows the README content")
 def t10():
-    r = request("/demo/plain/README.md")
+    # /plain/ is restricted to the user agents in plain-user-agents
+    # (curl/wget in the container config), so identify as one.
+    r = request("/demo/plain/README.md", headers={"User-Agent": "curl/8.7.1"})
     return (r.status == 200
             and r.has("Hello from the cgit container!"))
 
@@ -234,49 +243,97 @@ def t18():
 
 @test("t19 expensive endpoints rate limited to 429 after burst")
 def t19():
-    # The nginx config limits diff/commit/log to 5 requests/minute per
-    # client IP with burst=3 nodelay (shared zone).  Rapid-firing more
+    # The nginx config limits diff/commit/log to 60 requests/minute per
+    # client IP with burst=20 nodelay (shared zone).  Rapid-firing more
     # requests than 1 + burst within the refill window must produce
-    # HTTP 429, and a cheap endpoint must stay unaffected at the same
-    # time.  Run last: the hammering spends the whole burst budget for
-    # this client IP.
-    codes = []
-    for _ in range(8):
-        try:
-            r = request("/demo/log/")
-            codes.append(r.status)
-        except urllib.error.HTTPError as e:
-            codes.append(e.code)
-        time.sleep(0.2)
-    front = request("/")
-    # earlier tests may have spent part of the burst budget already, so
-    # do not assert on the first hit; what must hold either way is that
-    # rapid firing cannot get 8/8 through and that the last hit is a 429.
-    return (codes[-1] == 429         # burst exhausted -> 429
-            and codes.count(200) <= 4   # 1 + burst=3 pass, no more
-            and front.status in (200, 404))
+    # HTTP 429.  The listener trusts 127.0.0.1 for the client address
+    # (see trusted-proxies in cgit.scm), so the test claims a forwarded
+    # address of its own: it owns that budget instead of spending the
+    # one the earlier tests share, and 429s cannot be somebody else's
+    # traffic.
+    headers = {"X-Forwarded-For": "198.51.100.19"}
+    codes = [request("/demo/log/", headers=headers).status
+             for _ in range(40)]
+    # earlier requests cannot have spent this bucket, so the shape is
+    # sharp: 1 + burst=20 pass, the rest are 429.  Allow for a couple
+    # of tokens refilled while the 40 requests were in flight.
+    return (codes[-1] == 429          # burst exhausted -> 429
+            and codes.count(200) <= 25)
 
 
 @test("t20 every request is rate limited per client IP (429 after burst)")
 def t20():
     # The server-level limit_req zone=perip is 5 requests/second per
     # client IP with burst=30 nodelay, so at most 1 + 30 requests pass
-    # back-to-back and the rest are answered 429.  Sleep first so the
-    # token bucket refills (3 s at 5 r/s is plenty) -- the earlier
-    # tests spend part of the same budget.  Fire well past the burst.
-    # Run last.
-    time.sleep(3)
-    codes = []
-    for _ in range(60):
-        try:
-            r = request("/")
-            codes.append(r.status)
-        except urllib.error.HTTPError as e:
-            codes.append(e.code)
+    # back-to-back and the rest are answered 429.  Own forwarded
+    # address again: the bucket starts full and is nobody else's.
+    headers = {"X-Forwarded-For": "198.51.100.20"}
+    codes = [request("/", headers=headers).status
+             for _ in range(60)]
     return (codes.count(429) >= 1          # over the burst -> 429
             and codes.count(200) <= 31)    # 1 + burst=30 pass, no more
 
 
+@test("t21 forwarded clients get separate expensive-endpoint budgets")
+def t21():
+    # Regression for the shared-bucket 429 storm.  The deployment
+    # proxies every request into the container from 127.0.0.1; before
+    # set_real_ip_from/real_ip_header existed, the limit_req zones
+    # keyed on that proxy address, so the whole internet shared (and
+    # exhausted) one budget.  Two forwarded client addresses must
+    # behave like two clients: exhausting A's expensive budget must
+    # leave B's untouched.  Requires the plain (anubis? #f) variant,
+    # like t19: behind Anubis /demo/log/ never reaches cgit.
+    a = {"X-Forwarded-For": "198.51.100.21"}
+    b = {"X-Forwarded-For": "198.51.100.22"}
+    for _ in range(40):
+        request("/demo/log/", headers=a)
+    rejected_a = request("/demo/log/", headers=a).status
+    allowed_b = request("/demo/log/", headers=b).status
+    return rejected_a == 429 and allowed_b == 200
+
+
+@test("t22 exhausting one client's general budget spares the next")
+def t22():
+    # Same regression for the server-level general zone (perip), which
+    # is what produced the 429s on the repository summary page.
+    a = {"X-Forwarded-For": "198.51.100.23"}
+    b = {"X-Forwarded-For": "198.51.100.24"}
+    for _ in range(60):
+        request("/", headers=a)
+    rejected_a = request("/", headers=a).status
+    allowed_b = request("/", headers=b).status
+    return rejected_a == 429 and allowed_b == 200
+
+
+@test("t23 plain view accepts wget as well as curl")
+def t23():
+    r = request("/demo/plain/README.md", headers={"User-Agent": "Wget/1.21"})
+    return (r.status == 200
+            and r.has("Hello from the cgit container!"))
+
+
+@test("t24 plain view rejects other user agents (403)")
+def t24():
+    # plain-user-agents is an allowlist for raw downloads: a browser (or
+    # a scraper pretending to be one) may not scrub files through it.
+    r = request("/demo/plain/README.md",
+                headers={"User-Agent": "Mozilla/5.0 Firefox/142.0"})
+    return r.status == 403
+
+
+@test("t25 plain view is not challenged by Anubis")
+def t25():
+    # The point of plain-anubis-bypass?: tools fetch raw content and
+    # cannot solve a proof-of-work challenge.  Applies to anubis-enabled
+    # deployments (like t17/t18 it fails against an anubis-less one, by
+    # design).
+    r = request("/demo/plain/README.md", headers={"User-Agent": "Wget/1.21"})
+    return (r.status == 200
+            and r.has("Hello from the cgit container!")
+            and not r.has("Making sure"))
+
+
 def main():
     passed = failed = 0
     for name, fn in TESTS: