#!/usr/bin/env python3 """Turn a KAB refresh token into a fresh access token, in ~/.kab_token. Paste the browser's refresh_token at the prompt. It isn't echoed, and it isn't stored: it's a stronger credential than the access token, so it stays out of files and shell history. Run this just before a script that needs a token. Usage: python3 scripts/kab_token.py """ import getpass import json import os import sys import time import urllib.error import urllib.parse import urllib.request from pathlib import Path TOKEN_URL = "https://id.kab-dev.kyndemo.live/realms/kab/protocol/openid-connect/token" CLIENT = "kab-ui" def main() -> int: refresh = getpass.getpass("KAB refresh_token: ").strip() body = urllib.parse.urlencode({"grant_type": "refresh_token", "client_id": CLIENT, "refresh_token": refresh}).encode() try: with urllib.request.urlopen(urllib.request.Request(TOKEN_URL, data=body), timeout=30) as response: reply = json.load(response) except urllib.error.HTTPError as error: print(f"Refused: HTTP {error.code}: {json.loads(error.read() or b'{}').get('error_description', 'no reason given')}") return 1 path = Path.home() / ".kab_token" descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(descriptor, "w") as out: out.write(reply["access_token"]) print(f"Wrote {path}. It lasts {reply.get('expires_in')} s, until {time.strftime('%H:%M:%S', time.localtime(time.time() + reply.get('expires_in', 0)))}.") return 0 if __name__ == "__main__": sys.exit(main())