about summary refs log tree commit diff
path: root/test/python/test_dev_token.py
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-10-05 07:34:26 +0000
committerPjotr <wrk@bosa.lan>2026-10-05 07:34:26 +0000
commit649ff6395bdca06530ceabd3e216c66851dc60d6 (patch)
tree2bbe7008a8258b11ada120315fedff208d230206 /test/python/test_dev_token.py
parent693e7ee89f8618c1abbf8af5c0db23b071700803 (diff)
downloadgenenetwork4-649ff6395bdca06530ceabd3e216c66851dc60d6.tar.gz
Rename /dev/token to /get-test-token; require a token everywhere
Rename: POST /dev/token -> POST /get-test-token (src/routes/dev.rs,
TestToken replacing DevToken), matching tests/get_test_token.rs and
test/python/test_get_test_token.py (renamed from
tests/dev_token.rs/test_dev_token.py). Config::dev_token_enabled() and
the GN_AUTH_DEV_* config keys keep their names -- they're about the
dev-token feature generically, not tied to this one route's path.

Every endpoint now requires a valid token, not just the
dataset_probeset*/traits* family: species(_by_name/_datasets),
groups(_by_name/_strains/_traits*/_datasets) and dataset_by_name all
gain an AuthToken parameter. /, /version, /openapi.json and
/get-test-token itself are the only exceptions -- a health check, a
version check, the spec describing all this, and the endpoint that
hands out a token in the first place (which would be circular if it
needed one).

Rather than repeating security(("bearer_token" = [])) on every
#[utoipa::path], ApiDoc now declares it once as the document's default
security(...), and the three exceptions besides /get-test-token (/,
/version) override it with their own empty security() -- standard
OpenAPI semantics (an operation's own security, even empty, overrides
the document default; an absent one inherits it). error::Unauthorized,
a new #[derive(utoipa::IntoResponses)] type wrapping ApiError, is the
shared 401 every gated handler now references bare in its own
responses(...) list instead of writing out the same
(status = 401, description = "...", body = ApiError) tuple by hand.
Verified the resolved security per operation in a live /openapi.json.

tests/common::auth_token() (Rust) and the new
test/python/auth_helpers.auth_token() (Python, deduplicating what four
files previously each defined locally) now try this server's own
POST /get-test-token first, falling back to GN4_TEST_AUTH_TOKEN --
every previously-ungated test file gains a token check and switches to
get_with_token; the whole suite, both languages, now runs with zero
manually-provisioned tokens given GENENETWORK4_DEV_MODE=true
GENENETWORK4_BIND=127.0.0.1 for the test run. ServerTestCase gains
EXTRA_ENV so each Python test class can start its own server with dev
mode on. Verified both configured (auto-fetch) and unconfigured
(GN4_TEST_AUTH_TOKEN fallback, and full skip when neither is set, e.g.
the Guix build sandbox) paths.

README.md, docs/gn-auth.md and RELEASE_NOTES.md updated throughout for
the rename and the new blanket token requirement.

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.py103
1 files changed, 0 insertions, 103 deletions
diff --git a/test/python/test_dev_token.py b/test/python/test_dev_token.py
deleted file mode 100644
index 8b31395..0000000
--- a/test/python/test_dev_token.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""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()