about summary refs log tree commit diff
path: root/test/python
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-10-08 14:57:35 +0000
committerPjotr <wrk@bosa.lan>2026-10-08 14:57:35 +0000
commit69aac61b0c5b2d8a4f909de6a6d6af8d6ee293a3 (patch)
tree8c3734e6a3ca0baca7872d6e87cbe3167fb128b6 /test/python
parent679136801effc34ff4b50e54abfc40592ee1d64d (diff)
downloadgenenetwork4-69aac61b0c5b2d8a4f909de6a6d6af8d6ee293a3.tar.gz
* src/routes/dev.rs: POST /get-test-token answers local callers only, not tied to dev mode.
The endpoint no longer depends on GENENETWORK4_DEV_MODE or on the bind
address. It decides per request whether to answer.

* src/routes/dev.rs (get_test_token): answers a caller only when the TCP
peer (axum ConnectInfo) is in 127.0.x.x (or ::1, or an IPv4-mapped
127.x) and the request carries no X-Forwarded-For, Forwarded or
X-Real-IP header (a reverse proxy on the same host would otherwise make
every client look local). Anything else, including an unknown peer, is a
403. Local is never established from a header.
* src/main.rs: serve with into_make_service_with_connect_info, which
provides the peer address.
* src/config.rs: remove dev_mode, GENENETWORK4_DEV_MODE and
dev_token_enabled(). Add GENENETWORK4_TEST_TOKEN (on by default); when it
is not a clearly affirmative value (true/1/yes/on) the route is not
registered: a 404, absent from /openapi.json. It fails closed, so a
typo ("flase") turns the endpoint off.
* src/lib.rs: register the route unless that switch is off.

* tests: tests/get_test_token.rs rewritten (remote, unknown and proxied
peers refused; 127.x and ::1 answered; always documented by default);
tests/get_test_token_off.rs for the switch (own process: it sets an
environment variable); common::post_from supplies a peer address to the
in-process requests. Python: test_get_test_token.py rewritten, TOKEN_ENV
is now empty (no setting needed).
* README.md, docs/gn-auth.md, docs/SKILL.md, RELEASE_NOTES.md: document
the check, the switch, and "Behind nginx or in a container" (a bridge
container sees the gateway as the peer; a host-network container behind
nginx sees 127.0.0.1, so block the path in nginx, set X-Forwarded-For,
or switch the endpoint off).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Diffstat (limited to 'test/python')
-rw-r--r--test/python/auth_helpers.py23
-rw-r--r--test/python/server_test_case.py2
-rw-r--r--test/python/test_get_test_token.py91
3 files changed, 64 insertions, 52 deletions
diff --git a/test/python/auth_helpers.py b/test/python/auth_helpers.py
index 091c823..c16a7dd 100644
--- a/test/python/auth_helpers.py
+++ b/test/python/auth_helpers.py
@@ -16,10 +16,11 @@ from server_test_case import HOST, PORT
 
 AUTH_SERVER_URL = os.environ.get("AUTH_SERVER_URL", "http://127.0.0.1:8081/")
 
-# Every endpoint needs a token now (see docs/gn-auth.md) -- a test class
-# that calls auth_token() needs its server started with this so it can
-# self-issue one.
-TOKEN_ENV = {"GENENETWORK4_DEV_MODE": "true", "GENENETWORK4_BIND": "127.0.0.1"}
+# Every endpoint needs a token (see docs/gn-auth.md), and a test server
+# issues one to a local caller with no configuration at all (POST
+# /get-test-token is not tied to a mode). Kept as an empty environment so
+# the test classes that set `EXTRA_ENV = TOKEN_ENV` need no change.
+TOKEN_ENV = {}
 
 
 def auth_server_reachable():
@@ -36,14 +37,12 @@ def auth_server_reachable():
 
 
 def auth_token():
-    """A bearer token to use against the already-running test server
-    (started with TOKEN_ENV). Tries POST /get-test-token first -- this
-    just works once the server was started with TOKEN_ENV, no
-    externally managed token needed -- falling back to the
-    GN4_TEST_AUTH_TOKEN env var (see docs/gn-auth.md) for a gn-auth
-    setup that doesn't want dev mode on even for tests. Returns None,
-    rather than raising, if neither produces a token; callers should
-    skipTest() in that case.
+    """A bearer token to use against the already-running test server.
+    Tries POST /get-test-token first -- the test client is local, so
+    this just works with a reachable gn-auth, no externally managed
+    token needed -- falling back to the GN4_TEST_AUTH_TOKEN env var (see
+    docs/gn-auth.md). Returns None, rather than raising, if neither
+    produces a token; callers should skipTest() in that case.
     """
     conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10)
     try:
diff --git a/test/python/server_test_case.py b/test/python/server_test_case.py
index c400661..7561792 100644
--- a/test/python/server_test_case.py
+++ b/test/python/server_test_case.py
@@ -138,7 +138,7 @@ class ServerTestCase(unittest.TestCase):
     """Spawns the genenetwork4 binary for the duration of the test class.
 
     Subclasses that need the server started with extra/overridden
-    environment variables (e.g. GENENETWORK4_DEV_MODE) can set EXTRA_ENV.
+    environment variables (e.g. GN3_URL) can set EXTRA_ENV.
     """
 
     EXTRA_ENV = {}
diff --git a/test/python/test_get_test_token.py b/test/python/test_get_test_token.py
index 6cd07c0..43bde8b 100644
--- a/test/python/test_get_test_token.py
+++ b/test/python/test_get_test_token.py
@@ -1,10 +1,11 @@
-"""Mirrors tests/get_test_token.rs. POST /get-test-token only exists
-when GENENETWORK4_DEV_MODE is on and GENENETWORK4_BIND resolves to
-loopback (see Config::dev_token_enabled, src/routes/dev.rs). Each test
-class below spawns its own server subprocess with its own environment
-(ServerTestCase.EXTRA_ENV), so -- unlike the Rust test, which has to
-keep its env mutations in one sequential test function -- these can be
-separate test classes safely.
+"""Mirrors tests/get_test_token.rs. POST /get-test-token is not tied to a
+mode or a bind address: it is registered and documented by default
+(GENENETWORK4_TEST_TOKEN switches it off), and answers only a caller on
+this machine (a local TCP peer, no proxy
+header; see src/routes/dev.rs). This client is local, so it is answered;
+a request claiming to come through a proxy is refused. (A request from
+another machine cannot be made from here; the Rust test and the unit
+tests cover it.)
 """
 
 import http.client
@@ -30,52 +31,36 @@ def auth_server_reachable():
         conn.close()
 
 
-def post_test_token():
+def post_test_token(headers=None):
     conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10)
     try:
-        conn.request("POST", "/get-test-token")
+        conn.request("POST", "/get-test-token", headers=headers or {})
         response = conn.getresponse()
         return response, response.read()
     finally:
         conn.close()
 
 
-class GetTestTokenDisabledByDefaultTest(ServerTestCase):
-    """No EXTRA_ENV -- the out-of-the-box default (dev_mode off)."""
-
-    def test_get_test_token_returns_404_by_default(self):
-        response, _body = post_test_token()
-        self.assertEqual(response.status, 404)
-
-    def test_get_test_token_not_in_openapi_json_by_default(self):
-        # /openapi.json itself is one of the few endpoints that stays
-        # ungated (see lib.rs) -- no token needed here.
+class GetTestTokenTest(ServerTestCase):
+    def test_get_test_token_is_documented_without_any_configuration(self):
         conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10)
         try:
             conn.request("GET", "/openapi.json")
             body = conn.getresponse().read()
         finally:
             conn.close()
-        spec = json.loads(body)
-        self.assertNotIn("/get-test-token", spec["paths"])
-
-
-class GetTestTokenDevModeButWrongBindTest(ServerTestCase):
-    """dev_mode on, but not bound to loopback: still disabled."""
-
-    EXTRA_ENV = {"GENENETWORK4_DEV_MODE": "true", "GENENETWORK4_BIND": "0.0.0.0"}
-
-    def test_get_test_token_returns_404(self):
-        response, _body = post_test_token()
-        self.assertEqual(response.status, 404)
-
-
-class GetTestTokenEnabledTest(ServerTestCase):
-    """Both set: this is the only configuration where it works."""
-
-    EXTRA_ENV = {"GENENETWORK4_DEV_MODE": "true", "GENENETWORK4_BIND": "127.0.0.1"}
-
-    def test_get_test_token_returns_a_usable_token(self):
+        operation = json.loads(body)["paths"]["/get-test-token"]["post"]
+        self.assertIn("403", operation["responses"])
+
+    def test_get_test_token_refuses_a_request_that_came_through_a_proxy(self):
+        for header in ("X-Forwarded-For", "Forwarded", "X-Real-IP"):
+            response, body = post_test_token({header: "203.0.113.9"})
+            self.assertEqual(response.status, 403, header)
+            error = json.loads(body)
+            self.assertEqual(error["code"], "forbidden")
+            self.assertEqual(error["operation_id"], "get_test_token")
+
+    def test_get_test_token_returns_a_usable_token_to_a_local_caller(self):
         if not auth_server_reachable():
             self.skipTest(f"no gn-auth reachable at {AUTH_SERVER_URL}")
 
@@ -101,5 +86,33 @@ class GetTestTokenEnabledTest(ServerTestCase):
         self.assertEqual(response.status, 200)
 
 
+class GetTestTokenSwitchedOffTest(ServerTestCase):
+    """GENENETWORK4_TEST_TOKEN not clearly on: the route is not registered."""
+
+    EXTRA_ENV = {"GENENETWORK4_TEST_TOKEN": "false"}
+
+    def test_get_test_token_is_a_404_and_not_documented(self):
+        response, _body = post_test_token()
+        self.assertEqual(response.status, 404)
+
+        conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10)
+        try:
+            conn.request("GET", "/openapi.json")
+            body = conn.getresponse().read()
+        finally:
+            conn.close()
+        self.assertNotIn("/get-test-token", json.loads(body)["paths"])
+
+
+class GetTestTokenTypoFailsClosedTest(ServerTestCase):
+    """A misspelt "off" must not leave the endpoint running."""
+
+    EXTRA_ENV = {"GENENETWORK4_TEST_TOKEN": "flase"}
+
+    def test_get_test_token_is_a_404(self):
+        response, _body = post_test_token()
+        self.assertEqual(response.status, 404)
+
+
 if __name__ == "__main__":
     unittest.main()