Repository navigation
Expand file tree
/
Copy pathlab_token
More file actions
executable file
·101 lines (81 loc) · 3.69 KB
/
Copy pathlab_token
File metadata and controls
executable file
·101 lines (81 loc) · 3.69 KB
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
#!/usr/bin/env python3
"""Print a Neops access token for the lab's calls to the workflow engine.
The engine authorizes a request from a Neops RS256 access token, which the CMS
issues through its GraphQL `login` mutation. This prints the bare token, so a
shell or a make recipe can hand it to `run_workflow`, `wait_ready` and the
`lab_bootstrap` container through `NEOPS_ENGINE_TOKEN`:
export NEOPS_ENGINE_TOKEN=$(./lab_token)
export NEOPS_ENGINE_TOKEN=$(./lab_token --username operator)
Lab passwords equal usernames, so `--password` is only needed for an account
outside that convention. Access tokens last 15 minutes
(NEOPS_JWT_ACCESS_LIFETIME_MINUTES); mint a fresh one for a long run.
Exit codes
----------
0 a token was printed
1 the login failed, or the CMS was unreachable
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from urllib import error, request
LOGIN_MUTATION = """
mutation($username: String!, $password: String!) {
login(username: $username, password: $password) { accessToken }
}
"""
# The CMS rate-limits local logins per client IP
# (NEOPS_LOCAL_LOGIN_RATE_LIMIT, default 5/m), and every lab call leaves this
# host from the same address.
RATE_LIMIT_HINT = (
"the CMS rate-limited this login (NEOPS_LOCAL_LOGIN_RATE_LIMIT, default 5/m per IP). "
"Wait a minute, or mint one token and pass it to every caller through NEOPS_ENGINE_TOKEN."
)
def login_payload(username: str, password: str) -> dict:
"""Build the GraphQL request body for the CMS `login` mutation."""
return {"query": LOGIN_MUTATION, "variables": {"username": username, "password": password}}
def fetch_token(cms_url: str, username: str, password: str) -> str:
"""Run the login mutation and return the bare access token."""
req = request.Request(
cms_url.rstrip("/") + "/graphql",
data=json.dumps(login_payload(username, password)).encode(),
headers={"Content-Type": "application/json"},
)
try:
with request.urlopen(req, timeout=15) as resp:
payload = json.load(resp)
except error.HTTPError as exc:
body = exc.read().decode(errors="replace")
raise SystemExit(f"CMS login failed ({exc.code} {exc.reason}): {body[:300]}") from exc
except error.URLError as exc:
raise SystemExit(f"could not reach the CMS at {cms_url}: {exc.reason}") from exc
messages = [str(err.get("message", "")) for err in payload.get("errors") or []]
if any("Too many requests" in message for message in messages):
raise SystemExit(f"CMS login failed: {RATE_LIMIT_HINT}")
if messages:
raise SystemExit(f"CMS login failed: {'; '.join(messages)}")
token = ((payload.get("data") or {}).get("login") or {}).get("accessToken")
if not token:
raise SystemExit(f"CMS login returned no accessToken: {json.dumps(payload)[:300]}")
return str(token)
def build_arg_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="lab_token",
description="Print a Neops access token for the lab's calls to the workflow engine.",
)
p.add_argument("--username", default="neops", help="CMS username (default: neops)")
p.add_argument("--password", default=None, help="CMS password (default: the username)")
p.add_argument(
"--cms-url",
default=os.environ.get("CMS_URL", "http://localhost:8001"),
help="CMS base URL (default: $CMS_URL, else http://localhost:8001)",
)
return p
def main() -> int:
args = build_arg_parser().parse_args()
password = args.username if args.password is None else args.password
print(fetch_token(args.cms_url, args.username, password))
return 0
if __name__ == "__main__":
sys.exit(main())