import base64, json, os, time, urllib.request, urllib.error, urllib.parse
CID = os.environ["MI_CLIENT_ID"]
def call(url, headers):
    try:
        r = urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=20)
        return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        try: return e.code, json.load(e)
        except Exception: return e.code, {}
    except Exception as e:
        return 0, {"error": type(e).__name__}
def token():
    q = urllib.parse.urlencode({"api-version": "2018-02-01", "resource": "https://graph.microsoft.com", "client_id": CID})
    return call("http://169.254.169.254/metadata/identity/oauth2/token?" + q, {"Metadata": "true"})
for i in range(20):
    code, body = token()
    if code == 200: break
    print("waiting for identity endpoint, HTTP", code, flush=True); time.sleep(10)
first = body["access_token"]
p = first.split(".")[1]; c = json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
print("first token HTTP", code, "idtyp", c.get("idtyp"), "roles", c.get("roles"), "lifetime_seconds", c["exp"] - c["iat"], flush=True)
for n in range(1, 31):
    rc, rb = call("https://graph.microsoft.com/v1.0/users?$top=5&$select=id", {"Authorization": "Bearer " + first})
    tc, tb = token()
    new = ("same token" if tb.get("access_token") == first else "different token") if tc == 200 else str(tb.get("error"))[:60]
    print(time.strftime("%H:%M:%S", time.gmtime()), "old token read: HTTP", rc, "users", len(rb.get("value", [])), "| new token request: HTTP", tc, new, flush=True)
    time.sleep(30)
print("done", flush=True)
