about summary refs log tree commit diff
path: root/test/python/test_get_test_token.py
blob: 2426ebd36d9d6e67398b8f37e85d499144823481 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""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.
"""

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_test_token():
    conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10)
    try:
        conn.request("POST", "/get-test-token")
        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.
        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):
        if not auth_server_reachable():
            self.skipTest(f"no gn-auth reachable at {AUTH_SERVER_URL}")

        response, body = post_test_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()