#!/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 `. 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())