about summary refs log tree commit diff
path: root/test/python/auth_helpers.py
blob: 8b3e80d18bfe22ebaf27c1ab3d473fbf17b49bec (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
"""Shared helpers for tests that need a gn-auth bearer token. Mirrors
tests/common/mod.rs's auth_token()/auth_server_available() on the Rust
side.

A test class that uses auth_token() must set EXTRA_ENV = TOKEN_ENV (see
server_test_case.py) so its own spawned server can answer
POST /get-test-token (src/routes/dev.rs) with a real one.
"""

import http.client
import json
import os
from urllib.parse import urlparse

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"}


def auth_server_reachable():
    """True only when gn-auth is actually reachable at AUTH_SERVER_URL."""
    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 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.
    """
    conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10)
    try:
        conn.request("POST", "/get-test-token")
        response = conn.getresponse()
        if response.status == 200:
            return json.loads(response.read())["access_token"]
    except OSError:
        pass
    finally:
        conn.close()
    return os.environ.get("GN4_TEST_AUTH_TOKEN")