diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-05 06:50:30 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-05 06:50:30 +0000 |
| commit | 693e7ee89f8618c1abbf8af5c0db23b071700803 (patch) | |
| tree | e5db71e3f7e8af7342be1004aac9d5dfd0e1db2a /test/python/test_dev_token.py | |
| parent | adc173c1f3c78da487827122262573e753284260 (diff) | |
| download | genenetwork4-693e7ee89f8618c1abbf8af5c0db23b071700803.tar.gz | |
Add POST /dev/token, a dev-only gn-auth token issuer
Calls gn-auth's own password grant (POST /auth/token) for gn-auth's well-known development user and returns the result, so local testing no longer needs a manual curl/gn-auth round trip of its own. Only ever registered -- not just rejected at request time, genuinely absent from the router and from /openapi.json -- when two new Config fields are both set: dev_mode (GENENETWORK4_DEV_MODE) and a loopback bind (GENENETWORK4_BIND, also new). Both are config, not something genenetwork4 infers from its actual network exposure, by design: dev mode alone, or a loopback bind alone, each leave it disabled, and the check (Config::dev_token_enabled) is a plain function so the condition itself has direct unit test coverage rather than only being exercised indirectly through the route. src/main.rs now binds to config.bind instead of a hardcoded "0.0.0.0", via a proper SocketAddr rather than string formatting -- the latter would mishandle an IPv6 bind address like "::1" (needs brackets). GN_AUTH_DEV_CLIENT_ID/_CLIENT_SECRET/_USERNAME/_PASSWORD default to gn-auth's own published dev fixtures (flask init-dev-clients, gn_auth/wsgi.py), so this works unconfigured against an unmodified dev gn-auth instance -- confirmed live, including using the returned token against a real gated endpoint (/traits/BXD/10001), not just checking the token response's shape. tests/dev_token.rs covers all four combinations of the two settings in one sequential test function (mutating the same two env vars from more than one #[tokio::test] in a file would race, since they run concurrently by default) plus the /openapi.json visibility check. test/python/test_dev_token.py mirrors this using separate test classes instead, which is safe here since each spawns its own server subprocess with its own environment (ServerTestCase gains EXTRA_ENV for this). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
Diffstat (limited to 'test/python/test_dev_token.py')
| -rw-r--r-- | test/python/test_dev_token.py | 103 |
1 files changed, 103 insertions, 0 deletions
diff --git a/test/python/test_dev_token.py b/test/python/test_dev_token.py new file mode 100644 index 0000000..8b31395 --- /dev/null +++ b/test/python/test_dev_token.py @@ -0,0 +1,103 @@ +"""Mirrors tests/dev_token.rs. POST /dev/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. +""" + +import http.client +import json +import os +import unittest +from urllib.parse import urlparse + +from server_test_case import HOST, PORT, ServerTestCase + +AUTH_SERVER_URL = os.environ.get("AUTH_SERVER_URL", "http://127.0.0.1:8081/") + + +def auth_server_reachable(): + url = urlparse(AUTH_SERVER_URL) + conn = http.client.HTTPConnection(url.hostname, url.port or 80, timeout=2) + try: + conn.request("GET", url.path.rstrip("/") + "/auth/public-jwks") + return conn.getresponse().status == 200 + except OSError: + return False + finally: + conn.close() + + +def post_dev_token(): + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("POST", "/dev/token") + response = conn.getresponse() + return response, response.read() + finally: + conn.close() + + +class DevTokenDisabledByDefaultTest(ServerTestCase): + """No EXTRA_ENV -- the out-of-the-box default (dev_mode off).""" + + def test_dev_token_returns_404_by_default(self): + response, _body = post_dev_token() + self.assertEqual(response.status, 404) + + def test_dev_token_not_in_openapi_json_by_default(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("/dev/token", spec["paths"]) + + +class DevTokenDevModeButWrongBindTest(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_dev_token_returns_404(self): + response, _body = post_dev_token() + self.assertEqual(response.status, 404) + + +class DevTokenEnabledTest(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_dev_token_returns_a_usable_token(self): + if not auth_server_reachable(): + self.skipTest(f"no gn-auth reachable at {AUTH_SERVER_URL}") + + response, body = post_dev_token() + self.assertEqual(response.status, 200) + + token = json.loads(body) + self.assertTrue(token["access_token"]) + self.assertEqual(token["token_type"], "Bearer") + + # Exercise the issued token against a real gated endpoint -- it + # should be genuinely usable, not just a well-formed response. + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request( + "GET", + "/traits/BXD/10001", + headers={"Authorization": f"Bearer {token['access_token']}"}, + ) + response = conn.getresponse() + finally: + conn.close() + self.assertEqual(response.status, 200) + + +if __name__ == "__main__": + unittest.main() |
