about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-10-28 10:21:57 +0000
committerPjotr <wrk@bosa.lan>2026-10-28 10:21:57 +0000
commit45ff466ca4f1ad8ea651f4bbad7f31d46d21651e (patch)
treeb424072a82ab660251efeede7380c2dd7f091623
parentc33b1d534114f1e566a0b3a24bf8c161627aa060 (diff)
downloadgn-machines-45ff466ca4f1ad8ea651f4bbad7f31d46d21651e.tar.gz
cgit: Rate limit per forwarded client and serve /plain/ without Anubis.
Every limit was keyed on $binary_remote_addr, but the deployment
terminates TLS on the host and forwards from 127.0.0.1 without
X-Forwarded-For, so the four limits collapsed into one bucket shared by
the whole internet: 5 r/s, 20 connections and 60 r/min for
/log|/commit|/diff for everybody.  Ordinary browsing got 429s (9 of 12
requests at one request every two seconds), and `git clone' failed on
its first request.

Recover the client address instead: new trusted-proxies and
real-ip-header fields feed set_real_ip_from/real_ip_header/
real_ip_recursive, emitted by the new cgit-http-directives (the OS
passes it as nginx extra-content; %cgit-rate-limit-http-directives is
kept as the default-config value).  The trusted-proxies default of
127.0.0.1 matches the host proxy, and set to '() when an instance is
exposed directly so a client cannot pick its own bucket.

Also for anonymous reads:

* the expensive zone goes from 5r/m burst 3 to 60r/m burst 20 -- one
  request per second per client still stops history walks but leaves
  log -> commit -> diff chains alone;
* /plain/ (raw file content: curl, wget, scripts) can skip the Anubis
  challenge (plain-anubis-bypass?), which a tool cannot solve, and can
  be restricted to user-agent prefixes (plain-user-agents) so it cannot
  be used from a browser;
* internal-listen makes the Anubis-mode internal cgit address
  configurable, since a --network container shares the host netns and
  port 8081 may be taken.

The container uses nginx-realip (guix-bioinformatics, gn packages web):
the stock nginx is built without the real_ip module and refuses the
directives with `unknown directive "set_real_ip_from"'.
-rw-r--r--genenetwork/containers/cgit-container.scm155
-rw-r--r--genenetwork/services/cgit.scm222
2 files changed, 324 insertions, 53 deletions
diff --git a/genenetwork/containers/cgit-container.scm b/genenetwork/containers/cgit-container.scm
index 117585a..b108fa7 100644
--- a/genenetwork/containers/cgit-container.scm
+++ b/genenetwork/containers/cgit-container.scm
@@ -145,7 +145,7 @@
 ;;; ```
 ;;;
 ;;; Tests: `genenetwork/services/test/run_container_tests.sh` runs the
-;;; build + boot + full HTTP test cycle (`cgit_http_tests.py`, 18 checks including the
+;;; build + boot + full HTTP test cycle (`cgit_http_tests.py`, 25 checks including the
 ;;; Anubis tests, plus a tool and ssh check).
 ;;;
 ;;; ## Configuration parameters
@@ -173,6 +173,91 @@
 ;;; | `extra-options` | list of `(KEY . VALUE)` pairs | appended verbatim to the generated cgitrc; `VALUE #f` or omitted means `KEY=1` |
 ;;; | `fcgiwrap-processes` | integer, `4` | fcgiwrap worker count serving cgit |
 ;;; | `anubis?` | boolean, `#f` | proxy the tree/diff URIs through the Anubis AI-bot firewall; git smart-HTTP endpoints and static assets stay direct |
+;;; | `trusted-proxies` | list of strings, `("127.0.0.1")` | reverse proxies whose client-address header is believed (`set_real_ip_from`); see *Deploying behind a reverse proxy* below.  Set to `'()` when the instance is exposed directly |
+;;; | `real-ip-header` | string, `"X-Forwarded-For"` | header the trusted proxies set |
+;;; | `plain-anubis-bypass?` | boolean, `#f` | serve `/plain/` (raw file content) straight from the internal cgit server, skipping the Anubis proof-of-work challenge, which tools cannot solve |
+;;; | `plain-user-agents` | `#f` or list of strings, `#f` | user-agent prefixes allowed to use `/plain/`; anything else gets 403.  Advisory only |
+;;; | `internal-listen` | string, `"127.0.0.1:8081"` | address:port of the internal cgit server (`anubis? #t` only), reachable from localhost alone.  Change it when 8081 is taken on the host, since `--network` shares the host network namespace |
+;;;
+;;; ## Deploying behind a reverse proxy
+;;;
+;;; PUBLIC deployments terminate TLS on the host and proxy to the
+;;; container's listener.  That proxy **must** pass the client address,
+;;; otherwise every request arrives from the proxy's own address (in
+;;; this container: `127.0.0.1`) and all four rate limiters -- keyed on
+;;; `$binary_remote_addr` -- collapse into ONE budget shared by the
+;;; whole internet: 5 requests/second, 20 connections, and 60
+;;; requests/minute for `/log/`, `/commit/` and `/diff/` for everybody.
+;;; That is not hypothetical: it produced a steady stream of
+;;; `429 Too Many Requests` for ordinary users (9 of 12 requests
+;;; rejected at a rate of one request every two seconds, and
+;;; `git clone` failing on its first request).
+;;;
+;;; The host server block therefore needs:
+;;;
+;;; ```nginx
+;;; server {
+;;;     server_name git.genenetwork.org;
+;;;     location / {
+;;;         proxy_pass         http://127.0.0.1:8011/;
+;;;         proxy_redirect     off;
+;;;         proxy_set_header   Host              $host;
+;;;         proxy_set_header   X-Real-IP         $remote_addr;
+;;;         proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
+;;;     }
+;;; }
+;;; ```
+;;;
+;;; The container side is already wired: `cgit-http-directives` emits
+;;; `set_real_ip_from 127.0.0.1;`, `real_ip_header X-Forwarded-For;` and
+;;; `real_ip_recursive on;` from the `trusted-proxies` /
+;;; `real-ip-header` fields, so `$binary_remote_addr` is the real
+;;; client again and each client gets its own budget.  Those directives
+;;; need the nginx real_ip module, which Guix's stock nginx does NOT
+;;; build, so the container uses `nginx-realip' (guix-bioinformatics,
+;;; gn/packages/web.scm: stock nginx plus --with-http_realip_module).
+;;; Keep `trusted-proxies` as narrow as the deployment allows (a client
+;;; that can reach the listener directly could otherwise pick its own
+;;; bucket); behind Anubis the internal server trusts the same address,
+;;; so the forwarded chain survives the extra hop.
+;;;
+;;; Also note the host-side user-agent map (`$block_ua` -> `444`): it
+;;; closes the connection for the UAs it matches, which is why plain
+;;; `curl` sees no response at all while `wget` and `git` get through.
+;;;
+;;; ### Anonymous reads: clone and /plain/
+;;;
+;;; Two kinds of anonymous reads must not meet the challenge:
+;;;
+;;; * **git clone/fetch** -- the smart HTTP endpoints (`info/refs`,
+;;;   `git-upload-pack`, `HEAD`, `git-receive-pack`) have their own
+;;;   location in the PUBLIC server and talk to `git-http-backend`
+;;;   directly, in both modes.  Clones are ordinary HTTP requests, so
+;;;   they only get the general per-client rate limit; a clone issues a
+;;;   handful, so 5 r/s with burst 30 is ample.
+;;; * **`/plain/`** -- raw file content (`curl`, `wget`, scripts).  With
+;;;   `plain-anubis-bypass? #t` this URL shape is proxied straight to the
+;;;   internal cgit server, so no challenge (a tool cannot solve one) and
+;;;   `plain-user-agents '("curl" "Wget")` makes everything else 403,
+;;;   so a browser cannot be used to scrub the same files.  The filter
+;;;   reads `$http_user_agent`, i.e. whatever the client claims -- it
+;;;   keeps out casual traffic, not a determined scraper (that is what
+;;;   the rate limits and Anubis are for).
+;;;
+;;; The host proxy sits in front of all of this, so its UA map must not
+;;; kill the agents we allow.  `$block_ua -> 444` currently matches plain
+;;; `curl` (which is why curl gets no response at all while `wget` and
+;;; `git` pass): either drop `curl` from that map, or exempt the paths
+;;; here:
+;;;
+;;; ```nginx
+;;; # in the host block, replacing `if ($block_ua) { return 444; }'
+;;; map "$block_ua:$uri" $block_this {
+;;;     default            $block_ua;
+;;;     "~^1:/.*/plain/"   0;   # raw downloads are for curl/wget
+;;; }
+;;; if ($block_this) { return 444; }
+;;; ```
 ;;;
 ;;; With `anubis? #t` the public nginx listens on `port` (80) and
 ;;; proxies Anubis-verified browser traffic to the cgit front-end on
@@ -207,25 +292,39 @@
 ;;; the request rate is the one that matters most for them.
 ;;;
 ;;; On top of that, the expensive cgit endpoints (`/diff/`, `/commit/`,
-;;; `/log/`) get a stricter limit of 5 requests/minute per client IP
-;;; (shared zone `cgit-expensive`, burst 3 `nodelay`).  The expensive
-;;; limit applies in both modes: in the plain variant it protects the
-;;; public listener directly, with Anubis it sits in the internal
-;;; server and stops crawlers that *pass* the challenge from hammering
-;;; history walks.  The general limit sits on the public listener only
-;;; -- behind Anubis the internal server sees every request from
-;;; 127.0.0.1, so keying a limit there would lump all clients together.
+;;; `/log/`) get a stricter limit of 60 requests/minute per client IP
+;;; (shared zone `cgit-expensive`, burst 20 `nodelay`) -- one request
+;;; per second sustained, which leaves normal browsing (log -> commit ->
+;;; diff, a few commits in tabs) alone while still stopping history
+;;; walks.  The expensive limit applies in both modes: in the plain
+;;; variant it protects the public listener directly, with Anubis it
+;;; sits in the internal server and stops crawlers that *pass* the
+;;; challenge from hammering history walks.  The general limit sits on
+;;; the public listener only -- behind Anubis the internal server sees
+;;; every request from 127.0.0.1, so keying a limit there would lump
+;;; all clients together.
+;;;
+;;; "Per client IP" holds only when the client IP is actually visible:
+;;; the host proxy in front must send `X-Forwarded-For`, and the
+;;; container must believe it (see *Deploying behind a reverse proxy*
+;;; above and the `trusted-proxies` field).  Without both, one shared
+;;; bucket throttles the whole site.
+;;;
 ;;; Both layers answer 429 Too Many Requests and log at `warn` level
 ;;; (`limit_req_log_level` / `limit_conn_log_level`) for fail2ban; the
 ;;; container's nginx runs at `warn` log level so those lines reach
-;;; /var/log/nginx/error.log.
-;;;
-;;; The zone definitions travel in this container's nginx-configuration
-;;; extra-content (`%cgit-rate-limit-http-directives` from cgit.scm);
-;;; the knobs are `%cgit-perip-rate` / `%cgit-perip-burst` /
-;;; `%cgit-connperip-limit` and `%cgit-expensive-rate` /
+;;; /var/log/nginx/error.log.  Note that the logged address is the
+;;; *recovered* client address -- with the proxy misconfigured they all
+;;; say 127.0.0.1, and a fail2ban rule would then ban the proxy and take
+;;; the site down.
+;;;
+;;; The directives travel in this container's nginx-configuration
+;;; extra-content (`(cgit-http-directives %cgit-web-config)` from
+;;; cgit.scm, which emits the real-IP recovery plus the zone
+;;; definitions); the knobs are `%cgit-perip-rate` / `%cgit-perip-burst`
+;;; / `%cgit-connperip-limit` and `%cgit-expensive-rate` /
 ;;; `%cgit-expensive-burst` in cgit.scm; the regression tests are t19
-;;; and t20 in `genenetwork/services/test/cgit_http_tests.py`.
+;;; to t25 in `genenetwork/services/test/cgit_http_tests.py`.
 ;;;
 ;;; Browser note: Anubis sets `Secure` cookies by default, which browsers
 ;;; drop on plain HTTP.  Behind a TLS-terminating host proxy (the
@@ -365,6 +464,7 @@
   #:use-module (gnu services base)
   #:use-module (gnu services shepherd)
   #:use-module (gnu services sysctl)
+  #:use-module ((gn packages web) #:select (nginx-realip))
   #:use-module (gnu packages version-control))
 (use-package-modules base bash admin compression linux python)
 
@@ -380,6 +480,16 @@
    (root-title "GeneNetwork cgit")
    (root-desc "Git repositories for the GeneNetwork project")
    (repository-directory "/home/git/public")
+   ;; The host proxy (nginx on the deployment host) terminates TLS and
+   ;; forwards to 127.0.0.1:8011; trusting loopback for the client
+   ;; address is what keeps the rate limits per user instead of per
+   ;; proxy.  Set to '() if the container is ever exposed directly.
+   (trusted-proxies (list "127.0.0.1"))
+   ;; Raw file downloads (cgit's /plain/ view) are what scripts fetch:
+   ;; keep the Anubis challenge out of the way for them, and only serve
+   ;; them to the tools people actually use.
+   (plain-anubis-bypass? #t)
+   (plain-user-agents (list "curl" "Wget"))
    ;; Protect the web UI with the Anubis AI-bot firewall.
    (anubis? #t)))
 
@@ -418,16 +528,23 @@
     (list
      ;; The stock nginx front-end.  cgit-nginx-service-type below
      ;; contributes its nginx-server-configuration sites to it; the
-     ;; http-context extra-content carries the rate-limiting zone
-     ;; the cgit locations reference.
+     ;; http-context extra-content carries the real-IP recovery (so the
+     ;; rate limits are per client, not per host proxy) and the
+     ;; rate-limiting zones the cgit locations reference.
      (service nginx-service-type
               (nginx-configuration
+               ;; The stock nginx is built WITHOUT the real_ip module,
+               ;; so set_real_ip_from/real_ip_header are unknown
+               ;; directives and nginx refuses to start.  This variant
+               ;; only adds --with-http_realip_module; the rate limits
+               ;; depend on it (see (cgit-http-directives ...) below).
+               (nginx nginx-realip)
                ;; Let the rate-limit rejections logged at warn level
                ;; (limit_req_log_level/limit_conn_log_level) actually
                ;; reach the log: with the default error level they are
                ;; dropped before fail2ban can see them.
                (log-level 'warn)
-               (extra-content %cgit-rate-limit-http-directives)))
+               (extra-content (cgit-http-directives %cgit-web-config))))
      ;; One shared configuration for the web and nginx services (the
      ;; front-end needs the same record to generate the cgitrc for
      ;; fcgiwrap's CGIT_CONFIG environment).
diff --git a/genenetwork/services/cgit.scm b/genenetwork/services/cgit.scm
index 5cbe076..9289591 100644
--- a/genenetwork/services/cgit.scm
+++ b/genenetwork/services/cgit.scm
@@ -29,10 +29,10 @@
 ;;;   web): cgit-nginx-service-type contributes its sites as plain
 ;;;   nginx-server-configuration records -- the Guix way, no
 ;;;   hand-rolled conf strings.  The OS instantiates
-;;;   nginx-service-type itself, passing the exported
-;;;   %cgit-rate-limit-http-directives as the http-context
-;;;   extra-content (the rate-limit zone the cgit locations
-;;;   reference).
+;;;   nginx-service-type itself, passing the list returned by
+;;;   (cgit-http-directives CONFIG) as the http-context
+;;;   extra-content (the client-address recovery and the rate-limit
+;;;   zones the cgit locations reference).
 ;;; * fcgiwrap runs without the least-authority wrapper (nested
 ;;;   sandboxes inside a system container are fragile); it still runs
 ;;;   as the nginx user on a unix socket.
@@ -45,6 +45,7 @@
   #:export (cgit-web-configuration
             cgit-web-service-type
             cgit-nginx-service-type
+            cgit-http-directives
             %cgit-rate-limit-http-directives
             cgit-demo-repository-service)
   #:use-module (gnu)
@@ -60,6 +61,7 @@
                           fastcgi-pass
                           proxy-header
                           proxy-header->nginx
+                          proxy-pass
                           unix-socket-proxy-pass
                           try-files
                           nginx-include
@@ -70,7 +72,11 @@
                           limit-connection
                           limit-connection-status
                           limit-connection-log-level
-                          limit-connection-zone))
+                          limit-connection-zone
+                          set-real-ip-from
+                          real-ip-header
+                          real-ip-recursive
+                          nginx-map))
   #:use-module ((gnu packages mail) #:select (mailcap))
   #:use-module ((gnu packages version-control)
                 #:select (cgit-pink git))
@@ -141,7 +147,51 @@
   ;; Protect the diff and tree URIs behind the Anubis AI bot firewall
   ;; (see anubis-service-type below).  Off by default.
   (anubis?              cgit-web-configuration-anubis? ; boolean
-                        (default #f)))
+                        (default #f))
+  ;; Addresses (IP or CIDR block) of the reverse proxies in front of
+  ;; this instance, whose client-address header is believed.  This is
+  ;; what keeps the rate limiters keyed on $binary_remote_addr
+  ;; PER-CLIENT: without it every request carrying a proxy in front
+  ;; arrives from the proxy's address, so all clients share -- and
+  ;; exhaust -- one budget (the 429 storm this default fixes).  The
+  ;; proxy must be configured to send the header, e.g. in the host
+  ;; nginx in front of the container:
+  ;;   proxy_set_header X-Real-IP       $remote_addr;
+  ;;   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+  ;; Set to '() when the instance is exposed directly: then no client
+  ;; can choose its own bucket by sending a forged header.
+  (trusted-proxies      cgit-web-configuration-trusted-proxies
+                        ; list of strings
+                        (default (list "127.0.0.1")))
+  ;; Request header carrying the client address, as set by the
+  ;; trusted proxies above.
+  (real-ip-header       cgit-web-configuration-real-ip-header ; string
+                        (default "X-Forwarded-For"))
+  ;; cgit's /plain/ view serves raw file content -- what scripts fetch
+  ;; (curl, wget, `git archive --remote') rather than what a browser
+  ;; navigates to.  With Anubis enabled, let those URLs skip the
+  ;; proof-of-work challenge: a tool cannot solve it, and a raw file
+  ;; download does not need bot protection.  Only meaningful together
+  ;; with anubis? #t; without Anubis the location is served anyway.
+  (plain-anubis-bypass? cgit-web-configuration-plain-anubis-bypass?
+                        ; boolean
+                        (default #f))
+  ;; When set, a list of user-agent PREFIXES (matched
+  ;; case-insensitively) allowed to use /plain/; everything else gets
+  ;; 403.  #f (the default) allows any user agent.  This is a
+  ;; courtesy filter, not access control: a user agent is whatever the
+  ;; client claims to be.
+  (plain-user-agents    cgit-web-configuration-plain-user-agents
+                        ; #f or list of strings
+                        (default #f))
+  ;; ADDRESS:PORT of the INTERNAL cgit server (anubis? #t only).  It
+  ;; is reachable from localhost alone and carries the cgit CGI; the
+  ;; public listener proxies to it -- through Anubis, and directly for
+  ;; the plain-anubis-bypass? endpoints.  Change it when 8081 is taken
+  ;; on the host, since a `guix system container --network' shares the
+  ;; host network namespace.
+  (internal-listen      cgit-web-configuration-internal-listen ; string
+                        (default "127.0.0.1:8081")))
 
 (define (cgit-about-filter cgit)
   ;; about-filter for the README formats cgit's own filters support;
@@ -266,20 +316,45 @@ which runs the fcgiwrap instance)." )))
 ;;;   of %cgit-perip-burst requests is allowed through without delay.
 ;;; * the EXPENSIVE cgit endpoints (/diff/, /commit/, /log/ -- see
 ;;;   below) additionally get their own, much stricter limit_req zone:
-;;;   RATE is expressed in r/m notation; 5r/m means one request every
-;;;   12 seconds per client IP, with a small burst queue.  Exceeding it
-;;;   answers 429 Too Many Requests instead of running the CGI.
+;;;   RATE is expressed in r/m notation; 60r/m means one request per
+;;;   second per client IP, with a small burst queue.  Exceeding it
+;;;   answers 429 Too Many Requests instead of running the CGI.  It is
+;;;   deliberately generous: a human clicking through log -> commit ->
+;;;   diff, or opening several commits in tabs, is normal traffic -- an
+;;;   earlier 5r/m burst 3 rejected that.
 ;;;
 ;;; Both reject with 429 and log at warn level, so fail2ban-style
 ;;; tooling can follow up.
+;;;
+;;; The /plain/ view (raw file content) is special-cased: it is served
+;;; straight from the internal cgit server, bypassing Anubis when
+;;; plain-anubis-bypass? is set, because the proof-of-work challenge
+;;; breaks curl/wget/`git archive' and raw downloads do not need bot
+;;; protection; and it can be restricted to a list of user-agent
+;;; prefixes (plain-user-agents) so browsers are not used to scrub
+;;; files through it.  That filter is advisory -- the user agent is
+;;; whatever the client claims.
+;;;
+;;; "Keyed on the client IP" only holds up if the client IP is really
+;;; there: behind a TLS-terminating reverse proxy every request arrives
+;;; from the proxy's address, so the keys collapse into ONE global
+;;; budget -- 5 r/s for the whole internet, 20 connections for the
+;;; whole internet -- and legitimate users get 429s whenever somebody
+;;; else is busy.  (Observed live: 9 of 12 requests rejected at a rate
+;;; of one request every 2 seconds.)  cgit-http-directives therefore
+;;; emits set_real_ip_from for every address in the configuration's
+;;; trusted-proxies field plus real_ip_header/real_ip_recursive, which
+;;; makes $binary_remote_addr the forwarded client address again; the
+;;; proxy in front has to send that header (see the trusted-proxies
+;;; field).  Keep trusted-proxies as narrow as the deployment allows.
 (define %cgit-perip-zone "perip")
 (define %cgit-perip-rate "5r/s")
 (define %cgit-perip-burst 30)
 (define %cgit-connperip-zone "connperip")
 (define %cgit-connperip-limit 20)
 
-(define %cgit-expensive-rate "5r/m")
-(define %cgit-expensive-burst 3)
+(define %cgit-expensive-rate "60r/m")
+(define %cgit-expensive-burst 20)
 (define %cgit-expensive-zone "cgit-expensive")
 
 (define (cgit-general-limit-directives)
@@ -309,27 +384,104 @@ request and connection limits to every location of a server."
    (cgit-expensive-location "~ ^/[^/]+/commit/" rate burst)
    (cgit-expensive-location "~ ^/[^/]+/log/" rate burst)))
 
+(define (cgit-plain-location config)
+  "The nginx location serving cgit's @code{/plain/} view -- raw file
+content, the shape scripts fetch (curl, wget, @code{git archive
+--remote}).
+
+With Anubis and @code{plain-anubis-bypass?} it is proxied STRAIGHT to
+the internal cgit server, so the proof-of-work challenge never sees it
+(a tool cannot solve one).  Otherwise it goes through the ordinary
+cgit CGI path.
+
+When @code{plain-user-agents} is set, only those user-agent prefixes
+may use it; everything else gets 403.  The check is an nginx
+@code{map} emitted by @code{cgit-http-directives}."
+  (let* ((bypass? (and (cgit-web-configuration-anubis? config)
+                       (cgit-web-configuration-plain-anubis-bypass? config)))
+         (guard (if (cgit-web-configuration-plain-user-agents config)
+                    (list "if ($cgit_plain_ua_ok = 0) { return 403; }")
+                    '())))
+    (nginx-location-configuration
+     (uri "~ ^/[^/]+/plain/")
+     (body
+      (append
+       guard
+       (if bypass?
+           (list
+            (proxy-pass
+             (string-append
+              "http://" (cgit-web-configuration-internal-listen config)))
+            ;; Keep the client address intact for the internal
+            ;; server's real_ip/limit zones: $proxy_add_x_forwarded_for
+            ;; appends the address of THIS hop (127.0.0.1), which
+            ;; real_ip_recursive then skips.
+            (proxy-header->nginx
+             (proxy-header (name "Host") (value "$http_host")))
+            (proxy-header->nginx
+             (proxy-header (name "X-Real-IP") (value "$remote_addr")))
+            (proxy-header->nginx
+             (proxy-header (name "X-Forwarded-For")
+                           (value "$proxy_add_x_forwarded_for")))
+            (proxy-header->nginx
+             (proxy-header (name "X-Forwarded-Proto") (value "$scheme"))))
+           (list (try-files "$uri" "@cgit"))))))))
+
+(define (cgit-http-directives config)
+  "The http-context nginx directives the cgit sites need: client
+address recovery for requests arriving through a trusted proxy, the
+rate-limiting zones keyed on the recovered address, and the reject
+status/log level.  Pass the result as the @code{extra-content} of the
+nginx-configuration that instantiates the stock nginx-service-type."
+  ;; Not match-record: the record field real-ip-header would shadow the
+  ;; nginx serializer of the same name from (genenetwork services
+  ;; nginx).
+  (let ((proxies (cgit-web-configuration-trusted-proxies config))
+        (header (cgit-web-configuration-real-ip-header config)))
+    (append
+     ;; Client address recovery, first: limit_req_zone is expanded at
+     ;; configuration load time and the zones key on
+     ;; $binary_remote_addr, which real_ip rewrites per request.  The
+     ;; directives are still required in the http context, and their
+     ;; presence here is what makes the limits per-client instead of
+     ;; per-proxy.
+     (if (null? proxies)
+         '()
+         (append (map set-real-ip-from proxies)
+                 (list (real-ip-header header)
+                       (real-ip-recursive))))
+     ;; General per-client-IP request rate and concurrent connections.
+     (append
+      (if (cgit-web-configuration-plain-user-agents config)
+          ;; Allowlist for cgit's /plain/ view, consumed by
+          ;; cgit-plain-location.  The default (0) rejects.
+          (list (nginx-map "$http_user_agent" "$cgit_plain_ua_ok" "0"
+                           (map (lambda (agent)
+                                  (cons (string-append "~*^" agent) "1"))
+                                (cgit-web-configuration-plain-user-agents
+                                 config))))
+          '())
+      (list
+      (limit-request-zone "$binary_remote_addr"
+                          %cgit-perip-zone "10m" %cgit-perip-rate)
+      (limit-connection-zone "$binary_remote_addr"
+                             %cgit-connperip-zone "10m")
+      ;; Expensive-endpoint zone (same key, separate, stricter rate).
+      (limit-request-zone "$binary_remote_addr"
+                          %cgit-expensive-zone "10m" %cgit-expensive-rate)
+      ;; Answer 429 and log at warn so fail2ban can pick rejections up.
+      (limit-request-status 429)
+      (limit-connection-status 429)
+      (limit-request-log-level 'warn)
+      (limit-connection-log-level 'warn))))))
+
 (define %cgit-rate-limit-http-directives
-  ;; nginx-configuration 'extra-content' (http context) for the OS
-  ;; instantiating nginx-service-type: the shared rate-limiting zones
-  ;; the cgit servers/locations reference by name.  The general
-  ;; per-IP zone and the stricter expensive-endpoint zone both live
-  ;; here because limit_req_zone/limit_conn_zone are only valid in
-  ;; the http context, and the reject status/log level are global.
-  (list
-   ;; General per-client-IP request rate and concurrent connections.
-   (limit-request-zone "$binary_remote_addr"
-                       %cgit-perip-zone "10m" %cgit-perip-rate)
-   (limit-connection-zone "$binary_remote_addr"
-                          %cgit-connperip-zone "10m")
-   ;; Expensive-endpoint zone (same key, separate, stricter rate).
-   (limit-request-zone "$binary_remote_addr"
-                       %cgit-expensive-zone "10m" %cgit-expensive-rate)
-   ;; Answer 429 and log at warn so fail2ban can pick rejections up.
-   (limit-request-status 429)
-   (limit-connection-status 429)
-   (limit-request-log-level 'warn)
-   (limit-connection-log-level 'warn)))
+  ;; cgit-http-directives for a default <cgit-web-configuration>, i.e.
+  ;; trusting 127.0.0.1 (the host proxy / Anubis) for the client
+  ;; address.  Kept for out-of-tree users of the old name; prefer
+  ;; (cgit-http-directives config) so the trusted-proxies and
+  ;; real-ip-header fields are honoured.
+  (cgit-http-directives (cgit-web-configuration)))
 
 ;; FastCGI parameters and the other nginx directives the locations
 ;; below are built from are typed records and serializer procedures
@@ -429,6 +581,7 @@ that PASS the challenge are stopped too."
             (raw-content (cgit-general-limit-directives))
             (locations
              (list git-http
+                   (cgit-plain-location config)
                    (nginx-location-configuration
                     (uri "/")
                     (body
@@ -446,7 +599,7 @@ that PASS the challenge are stopped too."
            ;; INTERNAL: the plain cgit server, reachable only via
            ;; Anubis and from localhost.
            (nginx-server-configuration
-            (listen (list "127.0.0.1:8081"))
+            (listen (list (cgit-web-configuration-internal-listen config)))
             (server-name (list server-name))
             (root root)
             (locations (append expensive (list cgi fallback)))))
@@ -456,7 +609,8 @@ that PASS the challenge are stopped too."
             (server-name (list server-name))
             (root root)
             (raw-content (cgit-general-limit-directives))
-            (locations (append (list git-http) expensive
+            (locations (append (list git-http (cgit-plain-location config))
+                               expensive
                                (list cgi fallback)))))))))
 
 (define cgit-nginx-activation
@@ -505,7 +659,7 @@ that PASS the challenge are stopped too."
      ;; Contribute the cgit sites to the OS's nginx: plain
      ;; nginx-server-configuration records consumed by the stock
      ;; nginx-service-type (which the OS instantiates, with
-     ;; %cgit-rate-limit-http-directives as http extra-content).
+     ;; (cgit-http-directives config) as http extra-content).
      (service-extension nginx-service-type cgit-nginx-server-blocks)
      (service-extension shepherd-root-service-type
                         cgit-nginx-shepherd-services)