#!/usr/bin/env python3
"""
L1 validation of extracted GitLab tokens against gitlab.com API.
Read-only: GET /api/v4/user for each token.
"""
import urllib.request
import ssl
import json

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

TOKENS = [
    ("a71731fa", "glpat-xvSJNqi4v8xrD97cL2Yy"),
    ("b359dd31 (admin)", "glpat-MspGapyQssjZQ1APrGky"),
    ("git (mohamed)", "glpat-sgCEpY3CBBhrAJLFAwcxmG86MQp1OjN2Mm1rCw.01.120ci2qti"),
    ("token (khabir)", "glpat-6UyneVwq4emxXZnpFK7-2G86MQp1Omp4cXZhCw.01.12075cpxn"),
    ("5b460014 (admin@camel-soft.com password field)", "glpat-paHb-IMIGMOBkWdimvocHWM6MQpvOjEKdTozdjJtaw8.01.1709yym89"),
    ("gitlab-token (same)", "glpat-paHb-IMIGMOBkWdimvocHWM6MQpvOjEKdTozdjJtaw8.01.1709yym89"),
    ("marwen-gitlab-token", "glpat-4QqtQ3LRuYkw8lngMcv4GmM6MQpvOjEKdTo3eTBxZA8.01.170sjfbyb"),
]

results = []
for label, token in TOKENS:
    req = urllib.request.Request("https://gitlab.com/api/v4/user")
    req.add_header("PRIVATE-TOKEN", token)
    try:
        with urllib.request.urlopen(req, timeout=25, context=ctx) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            print(f"[VALID] {label}")
            print(f"  id={data.get('id')} username={data.get('username')} name={data.get('name')}")
            print(f"  email={data.get('email')} state={data.get('state')}")
            print(f"  is_admin={data.get('is_admin')} created_at={data.get('created_at')}")
            results.append({"label": label, "status": "VALID", "user": data})
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")[:200]
        print(f"[INVALID] {label}: HTTP {e.code} {body}")
        results.append({"label": label, "status": f"HTTP {e.code}", "body": body})
    except Exception as e:
        print(f"[ERROR] {label}: {e}")
        results.append({"label": label, "status": "ERROR", "error": str(e)})

with open("gitlab_token_validation.json", "w") as f:
    json.dump(results, f, indent=2)
print("\n[*] Saved to gitlab_token_validation.json")
