"""Local token service implementing the request shape of RFC 8693 token exchange. mode=naive: signs whatever scope is requested. mode=governed: scope subset, shorter expiry, depth limit.""" import base64, hashlib, hmac, json, time, os, urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer KEY = os.urandom(32) # HS256 key for the demo; a real issuer signs with an asymmetric key MAX_DEPTH = 2 CHILD_TTL = 120 TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange" def b64(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def unb64(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def sign(claims): h = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) p = b64(json.dumps(claims).encode()) sig = b64(hmac.new(KEY, f"{h}.{p}".encode(), hashlib.sha256).digest()) return f"{h}.{p}.{sig}" def verify(tok, now=None): h, p, s = tok.split(".") good = b64(hmac.new(KEY, f"{h}.{p}".encode(), hashlib.sha256).digest()) if not hmac.compare_digest(s, good): raise ValueError("bad signature") c = json.loads(unb64(p)) if c["exp"] <= (now or time.time()): raise ValueError("expired") return c def issue_root(sub, scope, ttl=600): now = time.time() return sign({"iss": "sts.demo.test", "sub": sub, "scope": scope, "iat": now, "exp": now + ttl, "depth": 0}) def make_server(mode, log, port=0): class H(BaseHTTPRequestHandler): def log_message(self, *a): pass def reply(self, code, body): data = json.dumps(body).encode() self.send_response(code); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) def do_POST(self): f = {k: v[0] for k, v in urllib.parse.parse_qs( self.rfile.read(int(self.headers["Content-Length"])).decode()).items()} if f.get("grant_type") != TOKEN_EXCHANGE: return self.reply(400, {"error": "unsupported_grant_type"}) req_scope = f.get("scope", "").split() req_sub = f["requested_subject"] # identity the new token is for now = time.time() if mode == "naive": tok = sign({"iss": "sts.demo.test", "sub": req_sub, "scope": " ".join(req_scope), "iat": now, "exp": now + 3600, "depth": 0}) return self.reply(200, {"access_token": tok, "scope": " ".join(req_scope)}) try: parent = verify(f["subject_token"]) except Exception as e: log({"event": "exchange_denied", "reason": f"subject_token: {e}"}) return self.reply(400, {"error": "invalid_request"}) extra = set(req_scope) - set(parent["scope"].split()) if extra: log({"event": "exchange_denied", "actor": parent["sub"], "requested_subject": req_sub, "reason": "scope not subset of parent", "extra_scope": sorted(extra)}) return self.reply(400, {"error": "invalid_scope"}) if parent["depth"] + 1 > MAX_DEPTH: log({"event": "exchange_denied", "actor": parent["sub"], "reason": "delegation depth"}) return self.reply(400, {"error": "invalid_request", "error_description": "depth"}) exp = min(parent["exp"], now + CHILD_TTL) tok = sign({"iss": "sts.demo.test", "sub": req_sub, "scope": " ".join(req_scope), "iat": now, "exp": exp, "depth": parent["depth"] + 1, "act": {"sub": parent["sub"]}}) log({"event": "exchange_ok", "actor": parent["sub"], "sub": req_sub, "scope": req_scope}) return self.reply(200, {"access_token": tok, "scope": " ".join(req_scope), "expires_in": int(exp - now)}) srv = ThreadingHTTPServer(("127.0.0.1", port), H) return srv def exchange(url, subject_token, requested_subject, scope): import urllib.request, urllib.error body = urllib.parse.urlencode({"grant_type": TOKEN_EXCHANGE, "subject_token": subject_token, "subject_token_type": "urn:ietf:params:oauth:token-type:jwt", "requested_subject": requested_subject, "scope": scope}).encode() try: with urllib.request.urlopen(urllib.request.Request(url, body)) as r: return json.load(r) except urllib.error.HTTPError as e: return json.load(e)