|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Dev-only utility to mint a JWT for the knowledge API. |
| 3 | +
|
| 4 | +Reads ``APP_SECRET`` / ``JWT_AUDIENCE`` / ``JWT_ISSUER`` from the environment |
| 5 | +(source ``development/workspaces/services/services.sh knowledge`` first) and |
| 6 | +prints a signed HS256 JWT to stdout. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + python utils/make-jwt.py |
| 10 | + python utils/make-jwt.py --days 30 --subject mcp-server |
| 11 | +
|
| 12 | +Set ``KNOWLEDGE_API_URL`` (default ``http://localhost:8187``) then test with: |
| 13 | + curl -H "Authorization: Bearer $(python utils/make-jwt.py)" \\ |
| 14 | + -H "Content-Type: application/json" \\ |
| 15 | + -d '{"question":"What is KDK?"}' \\ |
| 16 | + $KNOWLEDGE_API_URL/ask |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import argparse |
| 22 | +import os |
| 23 | +import sys |
| 24 | +import time |
| 25 | + |
| 26 | +import jwt |
| 27 | + |
| 28 | + |
| 29 | +def main() -> int: |
| 30 | + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 31 | + parser.add_argument( |
| 32 | + "--days", type=int, default=7, |
| 33 | + help="Token lifetime in days (default 7)", |
| 34 | + ) |
| 35 | + parser.add_argument( |
| 36 | + "--subject", default="dev", |
| 37 | + help="JWT 'sub' claim (default: dev)", |
| 38 | + ) |
| 39 | + args = parser.parse_args() |
| 40 | + |
| 41 | + secret = os.environ.get("APP_SECRET", "") |
| 42 | + audience = os.environ.get("JWT_AUDIENCE", "kalisio") |
| 43 | + issuer = os.environ.get("JWT_ISSUER", "kalisio") |
| 44 | + algorithm = os.environ.get("JWT_ALGORITHM", "HS256") |
| 45 | + |
| 46 | + if not secret: |
| 47 | + print( |
| 48 | + "error: APP_SECRET is empty. Source services.sh first:\n" |
| 49 | + " source development/workspaces/services/services.sh knowledge", |
| 50 | + file=sys.stderr, |
| 51 | + ) |
| 52 | + return 1 |
| 53 | + |
| 54 | + if args.days > 30: |
| 55 | + print( |
| 56 | + f"warning: minting a {args.days}-day token — dev tokens " |
| 57 | + "should not outlive a single workstation session.", |
| 58 | + file=sys.stderr, |
| 59 | + ) |
| 60 | + |
| 61 | + now = int(time.time()) |
| 62 | + payload = { |
| 63 | + "sub": args.subject, |
| 64 | + "aud": audience, |
| 65 | + "iss": issuer, |
| 66 | + "iat": now, |
| 67 | + "exp": now + args.days * 86400, |
| 68 | + } |
| 69 | + token = jwt.encode(payload, secret, algorithm=algorithm) |
| 70 | + print(token) |
| 71 | + return 0 |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + sys.exit(main()) |
0 commit comments