#!/usr/bin/env python3 # SECURITY: Local-only. No network access and no child processes. # All I/O is local file operations only: # READS: data[/]/active_grants.json, data[/]/.signing_key # WRITES: none # must be one of dev|st|sit|qa|sandbox|preprod|prod (anything else is rejected). # Imports used: argparse, json, os, sys, hmac, hashlib, datetime, pathlib, typing # Standard library only; no networking or process-spawning modules are imported. """ Validate Grant Token Check if a permission grant token is valid and not expired. Usage: python validate_token.py TOKEN Example: python validate_token.py grant_a1b2c3d4e5f6 """ import argparse import hashlib import hmac import json import os import sys from datetime import datetime, timezone from pathlib import Path from typing import Any, Optional _DATA_ROOT = Path(__file__).resolve().parent.parent / "data" # The only environments a data// directory is used for. _ENVIRONMENTS = ("dev", "st", "sit", "qa", "sandbox", "preprod", "prod") def _resolve_data_dir(env: str = "") -> Path: """Return data/, or data// for one of the documented environments.""" requested = env or os.environ.get("NETWORK_AI_ENV", "") if not requested: return _DATA_ROOT for name in _ENVIRONMENTS: if requested == name: return _DATA_ROOT / name # built from the fixed list, not the input raise ValueError( f"Unknown environment {requested!r}; expected one of: {', '.join(_ENVIRONMENTS)}" ) GRANTS_FILE = _resolve_data_dir() / "active_grants.json" def _load_signing_key() -> "Optional[bytes]": """ Load the local HMAC-SHA256 signing key used by check_permission.py. Returns None if the key file does not exist or cannot be read. """ key_file = GRANTS_FILE.parent / ".signing_key" if not key_file.exists(): return None try: return bytes.fromhex(key_file.read_text().strip()) except (ValueError, OSError): return None def _verify_grant_sig(grant: "dict[str, Any]") -> "Optional[bool]": """ Verify the HMAC-SHA256 signature stored in a grant record. Returns: True — signature present and valid False — signature present but invalid (tampered) None — no signature, or the signing key is unavailable (cannot verify) """ stored_sig = grant.get("_sig") if not stored_sig: return None if not isinstance(stored_sig, str): return False key = _load_signing_key() if key is None: return None fields = [grant.get("token", ""), grant.get("agent_id", ""), grant.get("resource_type", ""), grant.get("scope") or "", grant.get("expires_at", ""), grant.get("granted_at", "")] if not all(isinstance(f, str) for f in fields): return False # malformed record: cannot match what check_permission.py signed payload = "|".join(fields) expected = hmac.new(key, payload.encode("utf-8"), hashlib.sha256).hexdigest() return hmac.compare_digest(expected, stored_sig) def validate_token(token: str) -> dict[str, Any]: """Validate a grant token and return its details.""" if not GRANTS_FILE.exists(): return { "valid": False, "reason": "No grants file found" } try: grants = json.loads(GRANTS_FILE.read_text()) except json.JSONDecodeError: return { "valid": False, "reason": "Invalid grants file" } if token not in grants: return { "valid": False, "reason": "Token not found" } grant = grants[token] # Guard against tampered grant records (checks HMAC-SHA256 signature) sig_result = _verify_grant_sig(grant) if sig_result is False: return { "valid": False, "reason": "Token signature invalid — grant record may have been tampered with", } # Fail closed: a grant that cannot be verified (no signature, or no signing key) is never valid. if sig_result is None: return { "valid": False, "reason": "Token is unsigned or its signature cannot be verified (signing key unavailable)", } # Check expiration. A grant without a parseable expiry is rejected: a # corrupted or edited expires_at must never extend a token's lifetime. expiry = _parse_expiry(grant.get("expires_at")) if expiry is None: return { "valid": False, "reason": "Token has no valid expiry timestamp", } if datetime.now(timezone.utc) >= expiry: return { "valid": False, "reason": "Token has expired", "expired_at": grant.get("expires_at"), } return { "valid": True, "grant": grant, "sig_verified": sig_result is True, } def _parse_expiry(value: Any) -> "Optional[datetime]": """Parse an ISO-8601 expiry as an aware UTC datetime; None if unusable.""" if not isinstance(value, str) or not value.strip(): return None try: parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) except ValueError: return None if parsed.tzinfo is None: parsed = parsed.replace(tzinfo=timezone.utc) return parsed def main(): parser = argparse.ArgumentParser(description="Validate a permission grant token") parser.add_argument("token", help="Grant token to validate") parser.add_argument("--json", action="store_true", help="Output as JSON") parser.add_argument( "--env", default="", help="Target environment (dev|st|sit|qa|sandbox|preprod|prod). Overrides NETWORK_AI_ENV." ) args = parser.parse_args() # Re-resolve data paths if --env was provided explicitly global GRANTS_FILE if args.env: GRANTS_FILE = _resolve_data_dir(args.env) / "active_grants.json" result = validate_token(args.token) if args.json: print(json.dumps(result, indent=2)) else: if result["valid"]: grant = result["grant"] print("✅ Token is VALID") print(f" Agent: {grant.get('agent_id')}") print(f" Resource: {grant.get('resource_type')}") print(f" Scope: {grant.get('scope', 'N/A')}") print(f" Expires: {grant.get('expires_at')}") print(f" Restrictions: {', '.join(grant.get('restrictions', []))}") else: print("❌ Token is INVALID") print(f" Reason: {result.get('reason')}") sys.exit(0 if result["valid"] else 1) if __name__ == "__main__": main()