Skill Tracer
Skills › HyperFrames › media-use › gemini-auth.py

gemini-auth.py

52 lines · skills/media-use/audio/scripts/lib/gemini-auth.py at a595755

1"""Obtain Gemini OAuth headers without persisting credentials or tokens."""
2
3import json
4import os
5import sys
6
7# Keep the credential subprocess protocol UTF-8 on every platform.
8for _stream in (sys.stdout, sys.stderr):
9 if hasattr(_stream, "reconfigure"):
10 _stream.reconfigure(encoding="utf-8", errors=_stream.errors)
13def authenticate():
14 try:
15 from google.auth.transport.requests import Request
16 from google.oauth2 import service_account
17 except ImportError:
18 return {"error": "Service-account auth needs Python packages: pip install google-auth requests"}
20 try:
21 path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
22 if path:
23 with open(path, encoding="utf-8") as source:
24 info = json.load(source)
25 else:
26 info = json.loads(os.environ["GCS_CREDS"])
27 if info.get("type") != "service_account":
28 return {"error": "Gemini requires service-account JSON, not user ADC credentials"}
29 # Only exchange credentials with Google's OAuth server.
30 info["token_uri"] = "https://oauth2.googleapis.com/token"
31 credentials = service_account.Credentials.from_service_account_info(
32 info,
33 scopes=[
34 "https://www.googleapis.com/auth/generative-language.retriever",
35 ],
36 )
37 credentials.refresh(Request())
38 project = (
39 os.environ.get("GOOGLE_CLOUD_PROJECT")
40 or os.environ.get("GCLOUD_PROJECT_ID")
41 or info.get("project_id")
42 )
43 return {"token": credentials.token, "project": project}
44 except Exception:
45 # Library exceptions can contain credential data. Never forward them.
46 return {"error": "Gemini service-account authentication failed; check credentials, permissions, and network access"}
49if __name__ == "__main__":
50 result = authenticate()
51 print(json.dumps(result))
52 sys.exit(1 if "error" in result else 0)