{{ message }}
Repository navigation
Expand file tree
/
Copy pathtoken_helper.py
More file actions
351 lines (302 loc) · 12.7 KB
/
Copy pathtoken_helper.py
File metadata and controls
351 lines (302 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""Shared writer for the Databricks bearer-token helper script.
Claude Code (via ``apiKeyHelper`` in settings.json), Pi (via a
``!command`` apiKey in models.json), and Gemini CLI (via CoDA's launcher
wrapper) resolve their model-auth token by running this helper *per request / per TTL*. Centralising the writer keeps a single
source of truth for the token-resolution logic and its interpreter wiring, so
the two agents can never drift apart.
The helper prints exactly one line to stdout: the bearer token. Resolution
order (see the emitted script's docstring for the full rationale):
1. SP OAuth token fetched from the loopback broker (host path).
2. Legacy ``omnigents-host`` M2M profile, for upgrades from older containers.
3. The PAT from ``$DATABRICKS_TOKEN`` or ``~/.databrickscfg`` [DEFAULT].
All are resolved fresh on each invocation, so a long-running agent survives
PAT rotation / SP-OAuth expiry without a restart.
"""
import configparser
import json
import os
import sys
from pathlib import Path
from sp_token_broker import fetch_sp_token
# Legacy SP OAuth profile name. New installs persist only a secret-free host
# pointer under this name and fetch bearers from the loopback broker.
SP_PROFILE = "omnigents-host"
def resolve_sp_oauth_token() -> str | None:
"""Resolve a fresh token from the Omnigent host M2M profile."""
broker_url = os.environ.get("CODA_SP_TOKEN_BROKER_URL", "").strip()
if broker_url:
token = fetch_sp_token(broker_url)
if token:
return token
# Do not let a missing legacy profile trigger the SDK's ambient auth
# discovery/network path. On local setup tests (and on a cold PAT-only
# container) there is no profile; return immediately so setup scripts can
# use DATABRICKS_TOKEN instead of hanging for an unavailable SP login.
cfg_path = Path(os.path.expanduser("~/.databrickscfg"))
try:
config = configparser.ConfigParser()
config.read(cfg_path)
if SP_PROFILE not in config:
return None
except Exception:
return None
try:
from databricks.sdk.core import Config
headers = Config(profile=SP_PROFILE).authenticate()
auth = (headers or {}).get("Authorization", "")
token = auth[7:].strip() if auth.startswith("Bearer ") else auth.strip()
if token:
return token
except Exception:
pass
return None
def resolve_databricks_token() -> str | None:
"""Resolve a fresh SP OAuth token, falling back to the current PAT."""
token = resolve_sp_oauth_token()
if token:
return token
token = os.environ.get("DATABRICKS_TOKEN", "").strip()
if token:
return token
try:
config = configparser.ConfigParser()
config.read(os.path.expanduser("~/.databrickscfg"))
return config.get("DEFAULT", "token", fallback="").strip() or None
except Exception:
return None
_HELPER_SRC = r'''#!/usr/bin/env python3
"""Print a Databricks bearer token for Claude Code / Pi / Gemini resolution.
stdout MUST be the token only -- both callers use it verbatim.
"""
import configparser
import os
import shutil
import subprocess
import sys
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, build_opener
SP_PROFILE = "omnigents-host"
_MAX_TOKEN_BYTES = 16 * 1024
# Set on the uv re-run so the child (which has the SDK) doesn't recurse.
_REEXEC_GUARD = "OMNIGENTS_APIKEY_HELPER_REEXEC"
class _NoRedirectHandler(HTTPRedirectHandler):
def redirect_request(self, *_args, **_kwargs):
return None
_NO_REDIRECT_OPENER = build_opener(_NoRedirectHandler())
def urlopen(url, timeout):
return _NO_REDIRECT_OPENER.open(url, timeout=timeout)
def _broker_token():
url = os.environ.get("CODA_SP_TOKEN_BROKER_URL", "").strip()
try:
parsed = urlsplit(url)
valid = (
parsed.scheme == "http"
and parsed.hostname == "127.0.0.1"
and parsed.username is None
and parsed.password is None
and parsed.port is not None
and not parsed.query
and not parsed.fragment
and len(parsed.path.split("/")) == 3
and parsed.path.startswith("/token/")
and len(parsed.path.rsplit("/", 1)[1]) >= 32
)
except ValueError:
valid = False
if not valid:
return None
try:
with urlopen(url, timeout=5) as response:
content_type = (response.headers.get("Content-Type", "") or "").split(";", 1)[0]
body = response.read(_MAX_TOKEN_BYTES + 1)
if content_type.strip().lower() != "text/plain" or len(body) > _MAX_TOKEN_BYTES:
return None
token = body.decode("utf-8").strip()
return token if token and "\r" not in token and "\n" not in token else None
except Exception:
return None
def _sp_oauth_token():
token = _broker_token()
if token:
return token
# Upgrade fallback: mint via an older persisted M2M profile. New installs
# never write client_id/client_secret to terminal-visible HOME.
# The M2M (client_id/secret) profile the
# Omnigent host writes is NOT usable via `databricks auth token` (that CLI
# verb is U2M-only and refuses M2M); Config.authenticate() does the
# client-credentials flow. Verified accepted by /anthropic (C-O1, HTTP 200).
# Absent profile / non-host instance -> returns None, caller falls back.
try:
from databricks.sdk.core import Config
except ImportError:
# The helper is normally registered to run under the app's venv
# interpreter (which has databricks-sdk), so this branch shouldn't
# trigger. If it is ever invoked with a bare python3 that lacks the
# SDK, re-exec once under an interpreter that has it: prefer the
# recorded venv python (CODA_VENV_PYTHON), else fall back to
# `uv run --with databricks-sdk python`.
if os.environ.get(_REEXEC_GUARD) == "1":
return None
env = dict(os.environ, **{_REEXEC_GUARD: "1"})
try:
venv_python = os.environ.get("CODA_VENV_PYTHON")
if venv_python and os.path.exists(venv_python):
cmd = [venv_python, os.path.abspath(__file__)]
else:
uv = shutil.which("uv")
if not uv:
return None
cmd = [uv, "run", "--with", "databricks-sdk", "python",
os.path.abspath(__file__)]
out = subprocess.run(
cmd, env=env, capture_output=True, text=True, check=False,
)
except Exception:
return None
return (out.stdout or "").strip() or None
except Exception:
return None
try:
headers = Config(profile=SP_PROFILE).authenticate()
except Exception:
return None
auth = (headers or {}).get("Authorization", "")
# Strip the "Bearer " prefix so stdout carries the raw token only.
return auth[7:].strip() if auth.startswith("Bearer ") else (auth.strip() or None)
def _pat_token():
tok = os.environ.get("DATABRICKS_TOKEN", "").strip()
if tok:
return tok
cfg_path = os.path.expanduser("~/.databrickscfg")
try:
cp = configparser.ConfigParser()
cp.read(cfg_path)
return (cp["DEFAULT"].get("token") or "").strip() or None
except Exception:
return None
def main():
token = _sp_oauth_token() or _pat_token()
if not token:
print("no token source (no SP token broker, no PAT)", file=sys.stderr)
sys.exit(1)
sys.stdout.write(token)
if __name__ == "__main__":
main()
'''
def write_token_helper(target_dir) -> Path:
"""Write the executable token helper into ``target_dir``; return its path.
Idempotent: overwrites any prior copy so a version bump propagates. The
helper emits only the token on stdout (all diagnostics go to stderr).
"""
target_dir = Path(target_dir)
target_dir.mkdir(parents=True, exist_ok=True)
helper_path = target_dir / "anthropic-token-helper.py"
helper_path.write_text(_HELPER_SRC)
helper_path.chmod(0o700)
return helper_path
def helper_command(helper_path) -> str:
"""The `!command` string Pi uses to resolve its apiKey via the helper.
Runs the helper under the app's venv interpreter (has databricks-sdk) so it
never has to re-exec; falls back to the current interpreter. Pi resolves the
`!`-prefixed value as a shell command fresh per request.
"""
py = os.environ.get("CODA_VENV_PYTHON") or sys.executable or "python3"
return f"!{py} {helper_path}"
def write_databricks_token_wrapper(target_dir, real_cli: str) -> Path:
"""Write a narrow CLI shim for Omnigent's profile-based auth command."""
target_dir = Path(target_dir)
target_dir.mkdir(parents=True, exist_ok=True)
wrapper_path = target_dir / "databricks"
source = f'''#!{sys.executable}
import configparser
import datetime
import json
import os
import sys
from urllib.request import urlopen
REAL_CLI = {json.dumps(real_cli)}
PROFILE = {json.dumps(SP_PROFILE)}
def _profile(args):
for index, arg in enumerate(args):
if arg == "--profile" and index + 1 < len(args):
return args[index + 1]
if arg.startswith("--profile="):
return arg.split("=", 1)[1]
return None
def _broker_token():
url = os.environ.get("CODA_SP_TOKEN_BROKER_URL", "")
if not url:
return None
try:
with urlopen(url, timeout=5) as response:
token = response.read().decode().strip()
return token or None
except Exception:
return None
def _profile_host():
path = os.path.expanduser("~/.databrickscfg")
try:
cfg = configparser.ConfigParser(interpolation=None)
cfg.read(path)
return (cfg.get(PROFILE, "host", fallback="") or "").strip()
except Exception:
return ""
args = sys.argv[1:]
profile = _profile(args) or os.environ.get("DATABRICKS_CONFIG_PROFILE")
if args[:2] == ["auth", "token"] and _profile(args) == PROFILE:
token = _broker_token()
if not token:
os.execv(REAL_CLI, [REAL_CLI, *args])
# Emit the FULL OAuth token shape the databricks-sdk CLI token source
# (DatabricksCliTokenSource) requires: access_token + token_type + expiry.
# ALWAYS emit JSON — NOT gated on `--output json`. The SDK builds the token
# command as `databricks auth token --profile <p>` WITHOUT `--output json`
# (credentials_provider._build_core_cli_command) yet still json.loads()s the
# output, because the real CLI defaults `auth token` to JSON. A shim that
# printed a raw token on the no-flag path made the SDK fail with "cannot
# unmarshal CLI result: Expecting value: line 1 column 1", so
# Config(profile=...).authenticate() — used by omnigent's
# resolve_databricks_workspace for the model-catalog fetch — failed and pi
# fell back to a single-model picker. Match the real CLI: default to JSON.
#
# The broker returns only the raw token (no expiry metadata) and always
# mints a FRESH token per call. Set a short, conservative expiry (now + 5
# min, well inside the ~1h SP-OAuth TTL) so the SDK re-invokes this shim —
# re-hitting the broker for a fresh token — rather than caching one whose
# real lifetime we can't prove. Format matches CliTokenSource._parse_expiry
# ("%Y-%m-%dT%H:%M:%S", trailing Z ok).
expiry = (
datetime.datetime.now(datetime.timezone.utc)
+ datetime.timedelta(minutes=5)
).strftime("%Y-%m-%dT%H:%M:%SZ")
payload = {{
"access_token": token,
"token_type": "Bearer",
"expiry": expiry,
}}
# A bare `auth token` (no --output) also defaults to JSON on the real CLI,
# so emitting JSON unconditionally is faithful. `--output text` is not used
# by the SDK, so we don't special-case it.
print(json.dumps(payload))
raise SystemExit(0)
# Direct terminal commands (e.g. `databricks current-user me`) do not invoke
# the SDK's `auth token` subcommand, so they would otherwise reach the real CLI
# with the secret-free omnigents-host profile and fail looking for an OAuth
# cache. For that one profile, mint a broker token and hand it to the real CLI
# through process-local env vars. The token never enters the shell's exported
# environment or a file, and other profiles/commands are delegated untouched.
if profile == PROFILE:
token = _broker_token()
if token:
env = dict(os.environ)
env["DATABRICKS_TOKEN"] = token
host = _profile_host()
if host:
env["DATABRICKS_HOST"] = host
env.pop("DATABRICKS_CONFIG_PROFILE", None)
os.execve(REAL_CLI, [REAL_CLI, *args], env)
os.execv(REAL_CLI, [REAL_CLI, *args])
'''
wrapper_path.write_text(source)
wrapper_path.chmod(0o700)
return wrapper_path
You can’t perform that action at this time.
