about summary refs log tree commit diff
path: root/scripts/gn4-token.py
blob: 44f0dea8ef23158e6e8281f3cf3d5eceb23cabe7 (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
#!/usr/bin/env python3
"""Administer this server's short API tokens (`gn4ai_...`).

The registry is a single SQLite database (`tokens.sqlite`, `GN4_API_TOKENS_DB`),
owned by the server; this script does not open it. It talks to the server's own
routes instead, so there is exactly one implementation of the format, the
checksum and the revocation rules:

    create  mint a token and print it ONCE      POST   /tokens
    list    every token, never the secret       GET    /tokens
    revoke  revoke one by its id                DELETE /tokens/{id}
    who     describe a credential               GET    /tokens/who

Those routes only answer a caller on this machine (the server checks the TCP
peer address, not a header), so this script is a local admin tool by
construction -- there is no `--host` far-away variant worth having.

    scripts/gn4-token.py create --id zachs-1 --subject zachs --ttl-days 30
    scripts/gn4-token.py list
    scripts/gn4-token.py who  gn4ai_...           # or pass it as --token-file
    scripts/gn4-token.py revoke zachs-1

The base URL defaults to $GN4_API, else http://127.0.0.1:$GENENETWORK4_PORT
(3000 if unset) -- i.e. this machine, which is the only place the routes answer.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import urllib.error
import urllib.request

DEFAULT_PORT = 3000


def base_url() -> str:
    explicit = os.environ.get("GN4_API")
    if explicit:
        return explicit.rstrip("/")
    port = os.environ.get("GENENETWORK4_PORT", str(DEFAULT_PORT))
    return f"http://127.0.0.1:{port}"


def request(method: str, path: str, body: dict | None = None, token: str | None = None):
    data = None if body is None else json.dumps(body).encode()
    headers = {"content-type": "application/json"} if data else {}
    if token:
        headers["authorization"] = f"Bearer {token}"
    call = urllib.request.Request(base_url() + path, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(call, timeout=30) as response:
            return json.loads(response.read().decode())
    except urllib.error.HTTPError as error:
        detail = error.read().decode(errors="replace")
        try:
            parsed = json.loads(detail)
            message = parsed.get("detail") or parsed.get("message") or detail
            code = parsed.get("code", "")
        except json.JSONDecodeError:
            message, code = detail, ""
        if error.code == 403 and code == "not_local":
            raise SystemExit(
                f"{base_url()} refused this caller: token administration only answers "
                "requests from this machine (127.0.x.x or ::1, not through a proxy)."
            ) from error
        raise SystemExit(f"{method} {path}: HTTP {error.code}: {message}") from error
    except urllib.error.URLError as error:
        raise SystemExit(
            f"cannot reach {base_url()} ({error.reason}); is the server running, "
            "and is this machine allowed to administer tokens?"
        ) from error


def secret_from(args) -> str:
    if args.token:
        return args.token.strip()
    if args.token_file:
        with open(args.token_file) as handle:
            return handle.read().strip()
    raise SystemExit("give the token as an argument, --token, or --token-file")


def command_create(args) -> int:
    reply = request(
        "POST",
        "/tokens",
        {
            "id": args.id,
            "subject": args.subject,
            "scope": args.scope,
            **({"ttl_days": args.ttl_days} if args.ttl_days is not None else {}),
            **({"note": args.note} if args.note else {}),
        },
    )["data"]
    print(f"id        {reply['id']}")
    print(f"subject   {reply['subject']}  scope {reply['scope']}  status {reply['status']}")
    if reply.get("expires_at"):
        print(f"expires   {reply['expires_at']}")
    print()
    print("This is the only time the token can be shown -- it is stored as a hash:")
    print()
    print(f"  {reply['token']}")
    print()
    print("Use it as `Authorization: Bearer <token>`. Never in a query string.")
    return 0


def command_list(args) -> int:
    tokens = request("GET", "/tokens")["data"]
    if not tokens:
        print("no tokens")
        return 0
    width = max(len(token["id"]) for token in tokens)
    for token in tokens:
        expires = token.get("expires_at")
        used = token.get("last_used_at")
        print(
            f"{token['id']:<{width}}  {token['subject']:<16}  {token['scope']:<8}"
            f"  {token['status']:<8}  {token['prefix']}…"
            f"  {'expires ' + str(expires) if expires else 'no expiry'}"
            f"  {'used ' + str(used) if used else 'never used'}"
        )
    return 0


def command_revoke(args) -> int:
    reply = request("DELETE", f"/tokens/{args.id}")["data"]
    print(f"revoked {reply['id']} ({reply['subject']}); effective on the next request")
    return 0


def command_who(args) -> int:
    reply = request("GET", "/tokens/who", token=secret_from(args))["data"]
    print(json.dumps(reply, indent=2))
    return 0


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    commands = parser.add_subparsers(dest="command", required=True)

    create = commands.add_parser("create", help="mint a token, printing it once")
    create.add_argument("--id", required=True, help="human handle, unique: zachs-1")
    create.add_argument("--subject", required=True, help="who it acts as (gn-auth user id)")
    create.add_argument("--scope", default="public", help="registry-declared scope (default: public)")
    create.add_argument("--ttl-days", type=int, default=None, help="lifetime in days (default 30)")
    create.add_argument("--note", default=None, help="free text, e.g. what it is for")
    create.set_defaults(run=command_create)

    listing = commands.add_parser("list", help="every token, never the secret")
    listing.set_defaults(run=command_list)

    revoke = commands.add_parser("revoke", help="revoke a token by its id")
    revoke.add_argument("id")
    revoke.set_defaults(run=command_revoke)

    who = commands.add_parser("who", help="describe a credential (either scheme)")
    who.add_argument("token", nargs="?", help="the credential itself")
    who.add_argument("--token", dest="token_option", default=None, help=argparse.SUPPRESS)
    who.add_argument("--token-file", default=None, help="read the credential from a file")
    who.set_defaults(run=command_who, token=None)

    args = parser.parse_args()
    if args.command == "who":
        args.token = args.token or args.token_option
    return args.run(args)


if __name__ == "__main__":
    sys.exit(main())