about summary refs log tree commit diff
path: root/scripts/gn-auth-stub.py
blob: 13489d0d150e2712d80a207b8cb4b91a6efedf22 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python3
"""A local stand-in for gn-auth, so the test suites can be run fully --
against a real database and a real index -- without a gn-auth instance.

The suites skip (rather than fail) anything that needs a token they
cannot get, which is the right behaviour in the Guix build sandbox but
leaves most endpoints untested there. Set `GN4_TEST_AUTH_TOKEN` and this
stub instead, and they run:

    scripts/gn-auth-stub.py &                  # prints the token
    export GN4_TEST_AUTH_TOKEN=$(curl -s -X POST \\
        http://127.0.0.1:8081/auth/token | python3 -c \\
        'import json,sys; print(json.load(sys.stdin)["access_token"])')

What it answers, and why each is needed:

- `GET /auth/public-jwks` -- the key set the token is verified against.
  The token is signed with `test/data/test_rsa_private.pem`, whose
  public half is `test/data/test_jwks.json`: the same fixture pair
  `tests/search_native_db.rs` spins up in-process.
- `POST /auth/token` -- gn-auth's password grant, so `POST
  /get-test-token` (src/routes/dev.rs) can serve a token, which is how
  `tests/*.rs` and `test/python/test_*.py` obtain one themselves.
- `POST /auth/resource/authorisation` and `POST /auth/data/authorisation`
  -- resource- and trait-level privilege lookups (src/auth.rs). They
  answer "no privileges" by default, i.e. the stranger/anonymous case,
  which is what the non-public endpoints' 403 tests assert. Pass
  `--grant-resource-id` to grant `group:resource:view-resource` on one
  resource id to the fixture token, for the owner-side tests
  (`GN4_TEST_RESOURCE_ID` must name the same id).

Left ungranted, a token from this stub is a *public-data-only* token:
genenetwork4 decides what data may go out from the data's own
public/confidentiality/create_time columns and, for anything not public,
from this authorisation lookup (src/auth.rs's `check`). No privileges
means public datasets read normally and every non-public one is a 403 --
the restriction lives in the lookup, not in the token's `scope`, which
genenetwork4 does not consult for data access. `--expires-in` sets how
long such a token lasts (`30d`, `24h`, plain seconds; default 24h); the
stub's key is fixed and never rotates, so the token stays verifiable for
as long as anything serving `test/data/test_jwks.json` is up.

`iss` has to match genenetwork4's `AUTH_SERVER_URL` exactly (it is
passed to `Validation::set_issuer` verbatim), including the trailing
slash the default `http://127.0.0.1:8081/` carries -- that is what
`--port`/`--issuer` are for, and why `--issuer` falls back to
`AUTH_SERVER_URL` when that is set in the environment.

To issue a token for one more user, run a second instance with
`--mint-only` and the *same* issuer as the long-running one:

    scripts/gn-auth-stub.py --mint-only --subject alice \
        --expires-in 30d --token-file /run/gn4/alice.token

It mints, prints and exits without listening; the token verifies against
the long-running stub, because verification only depends on the key
(committed, therefore shared) and on `iss`.
"""

import argparse
import base64
import json
import os
import subprocess
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
JWKS_FILE = os.path.join(REPO, "test", "data", "test_jwks.json")
KEY_FILE = os.path.join(REPO, "test", "data", "test_rsa_private.pem")

VIEW_RESOURCE_PRIVILEGE = "group:resource:view-resource"


def b64u(raw):
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def duration(text):
    """A duration as seconds: "86400", "30d", "24h", "60m" or "45s"."""
    units = {"s": 1, "m": 60, "h": 3600, "d": 86400}
    unit = text[-1] if text[-1].isalpha() else None
    try:
        return int(float(text[:-1] if unit else text) * units[unit or "s"])
    except (KeyError, ValueError) as error:
        raise argparse.ArgumentTypeError(
            f"not a duration: {text!r} (try 30d, 24h, 60m or plain seconds)"
        ) from error


def sign(issuer, kid, subject, scope, expires_in):
    """An RS256 token matching test_jwks.json, in gn-auth's claim shape."""
    now = int(time.time())
    header = {"alg": "RS256", "typ": "JWT", "kid": kid}
    claims = {
        "sub": subject,
        "scope": scope,
        "iss": issuer,
        "iat": now,
        "exp": now + expires_in,
    }
    signing_input = ".".join(
        b64u(json.dumps(part, separators=(",", ":")).encode())
        for part in (header, claims)
    )
    signature = subprocess.run(
        ["openssl", "dgst", "-sha256", "-sign", KEY_FILE],
        input=signing_input.encode(),
        capture_output=True,
        check=True,
    ).stdout
    return signing_input + "." + b64u(signature)


def handler_for(token, grant_ids, jwks_document):
    class Handler(BaseHTTPRequestHandler):
        def _json(self, payload, status=200):
            body = json.dumps(payload).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def _body(self):
            length = int(self.headers.get("Content-Length") or 0)
            return self.rfile.read(length) if length else b""

        def do_GET(self):
            if self.path.rstrip("/") == "/auth/public-jwks":
                body = jwks_document.encode()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            else:
                self._json({"error": "not found"}, 404)

        def do_POST(self):
            body = self._body()
            path = self.path.rstrip("/")
            if path == "/auth/token":
                self._json(
                    {
                        "access_token": token,
                        "token_type": "Bearer",
                        "scope": "profile group resource",
                    }
                )
            elif path == "/auth/resource/authorisation":
                # The fixture token holds the privilege on the granted
                # resource ids and nothing anywhere else; any other
                # bearer token (e.g. a syntactically valid stranger) gets
                # no roles, exactly as gn-auth treats an anonymous call.
                requested = json.loads(body or b"{}").get("resource-ids") or []
                own_token = self.headers.get("Authorization") == "Bearer " + token
                granted = [i for i in requested if i in grant_ids] if own_token else []
                self._json(
                    {
                        resource_id: {
                            "roles": [
                                {"privileges": [{"privilege_id": VIEW_RESOURCE_PRIVILEGE}]}
                            ]
                        }
                        for resource_id in granted
                    }
                )
            elif path == "/auth/data/authorisation":
                self._json({"authorisation": []})
            else:
                self._json({"error": "not found"}, 404)

        def log_message(self, fmt, *args):
            pass

    return Handler


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument(
        "--port",
        type=int,
        default=8081,
        help="port to listen on (default 8081, genenetwork4's default AUTH_SERVER_URL)",
    )
    parser.add_argument(
        "--issuer",
        default=None,
        help="iss claim to mint (default http://127.0.0.1:<port>/, matching "
        "genenetwork4's default AUTH_SERVER_URL -- it must match that string "
        "exactly, trailing slash included)",
    )
    parser.add_argument(
        "--subject",
        default="gn4-test-stub",
        help="sub claim to mint (default gn4-test-stub)",
    )
    parser.add_argument(
        "--scope",
        default="profile group resource",
        help="scope claim to mint",
    )
    parser.add_argument(
        "--expires-in",
        type=duration,
        default="24h",
        metavar="DURATION",
        help="how long the token stays valid, e.g. 30d, 24h, 60m or seconds "
        "(default 24h). The stub's key is fixed and never rotates, so the "
        "token stays verifiable for as long as any JWKS serving "
        "test_jwks.json is up.",
    )
    parser.add_argument(
        "--mint-only",
        action="store_true",
        help="mint the token, print it (and write --token-file) and exit "
        "without listening. Mints for --subject with the same key and iss as "
        "the long-running stub, so the token verifies against it -- this is "
        "how a token is issued for one more user.",
    )
    parser.add_argument(
        "--grant-resource-id",
        action="append",
        default=[],
        metavar="ID",
        help="resource id the fixture token holds view-resource on (repeatable); "
        "set GN4_TEST_RESOURCE_ID to the same value. Without it every "
        "authorisation answer is 'no privileges'.",
    )
    parser.add_argument(
        "--token-file",
        default=None,
        help="write the minted token here as well as printing it",
    )
    args = parser.parse_args()

    issuer = (
        args.issuer
        or os.environ.get("AUTH_SERVER_URL")
        or f"http://127.0.0.1:{args.port}/"
    )
    jwks_document = open(JWKS_FILE).read()
    kid = json.loads(jwks_document)["jwks"][0]["kid"]
    token = sign(issuer, kid, args.subject, args.scope, args.expires_in)

    if args.mint_only:
        if args.token_file:
            with open(args.token_file, "w") as handle:
                handle.write(token + "\n")
        print(token, flush=True)
        return

    # Bind before writing or printing anything: a second instance started
    # while one is already listening fails here, and must leave the first
    # one's token file alone rather than clobber it with a token nothing
    # is serving.
    server = ThreadingHTTPServer(
        ("127.0.0.1", args.port),
        handler_for(token, set(args.grant_resource_id), jwks_document),
    )

    if args.token_file:
        with open(args.token_file, "w") as handle:
            handle.write(token + "\n")
    print(token, flush=True)

    print(
        f"gn-auth stub on http://127.0.0.1:{args.port}/ (iss {issuer}"
        + (f", granting {', '.join(args.grant_resource_id)}" if args.grant_resource_id else "")
        + ")",
        file=__import__("sys").stderr,
        flush=True,
    )
    server.serve_forever()


if __name__ == "__main__":
    main()