-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathservice.py
More file actions
353 lines (310 loc) · 12.1 KB
/
Copy pathservice.py
File metadata and controls
353 lines (310 loc) · 12.1 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
352
353
"""Shared LLM auth setup operations for CLI, wizard, and REPL wrappers."""
from __future__ import annotations
import subprocess
from dataclasses import dataclass
from pathlib import Path
from config.llm_auth.auth_method import OAUTH_AUTH_METHOD
from config.llm_auth.credentials import (
delete as delete_provider_auth,
)
from config.llm_auth.credentials import (
save_api_key,
)
from config.llm_auth.credentials import (
status as provider_auth_status,
)
from config.llm_auth.credentials import (
verify as verify_provider_auth,
)
from config.llm_auth.records import (
delete_provider_auth_record,
resolve_provider_auth_record,
save_provider_auth_record,
)
from config.secrets.backend import KeyringUnavailableError
from integrations.llm_cli.codex_oauth import CodexOAuthError, run_codex_oauth_login
from surfaces.cli.llm_auth.persist import AuthSetupError, persist_api_key_secret
from surfaces.cli.llm_auth.providers import (
ProviderAuthProfile,
provider_for_profile,
resolve_auth_profile,
)
from surfaces.cli.wizard.config import PROVIDER_BY_VALUE, ProviderOption, WizardCredentialKind
from surfaces.cli.wizard.env_sync import sync_provider_env
from surfaces.cli.wizard.validation import validate_provider_credentials
@dataclass(frozen=True)
class AuthStatus:
"""Status row for one provider auth path."""
provider: str
label: str
authenticated: bool
source: str
detail: str
verified: bool = False
stale: bool = False
@dataclass(frozen=True)
class AuthSetupResult:
"""Result from configuring a provider auth path."""
provider: str
model: str
source: str
detail: str
env_path: Path | None
def _save_auth_record(
*,
provider: ProviderOption,
profile: ProviderAuthProfile,
source: str,
detail: str,
) -> None:
save_provider_auth_record(
provider=provider.value,
auth_name=profile.name,
kind=profile.kind,
source=source,
detail=detail,
)
def configure_api_key_provider(
*,
profile: ProviderAuthProfile,
api_key: str,
model: str | None = None,
set_provider: bool = True,
validate: bool = True,
env_path: Path | None = None,
) -> AuthSetupResult:
"""Validate and persist an API-key provider credential."""
provider = provider_for_profile(profile)
if provider.credential_kind != WizardCredentialKind.API_KEY or not provider.api_key_env:
raise AuthSetupError(f"{provider.label} does not use an OpenSRE-managed API key.")
normalized_key = api_key.strip()
if not normalized_key:
raise AuthSetupError(f"{provider.api_key_env} cannot be empty.")
selected_model = (model if model is not None else provider.default_model).strip()
if validate:
validation = validate_provider_credentials(
provider=provider,
api_key=normalized_key,
model=selected_model,
)
if not validation.ok:
raise AuthSetupError(validation.detail)
try:
# No hardcoded detail: the store reports which tier actually took the
# write, and claiming the keychain when the credential landed in the
# local fallback would both mislead the user and overwrite the correct
# metadata record that save_api_key just wrote.
saved = save_api_key(provider.value, normalized_key)
except (RuntimeError, ValueError) as exc:
raise AuthSetupError(str(exc)) from exc
written_path = (
sync_provider_env(provider=provider, model=selected_model, env_path=env_path)
if set_provider
else None
)
source = "fallback" if saved.used_fallback else "keyring"
_save_auth_record(provider=provider, profile=profile, source=source, detail=saved.detail)
return AuthSetupResult(
provider=provider.value,
model=selected_model,
source=source,
detail=saved.detail,
env_path=written_path,
)
def _managed_codex_login_detail() -> str:
try:
result = run_codex_oauth_login()
except CodexOAuthError as exc:
raise AuthSetupError(str(exc)) from exc
return result.detail
def _subscription_login_command(profile: ProviderAuthProfile, binary_path: str) -> list[str]:
if profile.provider_value == "codex":
return [binary_path, "login"]
if profile.provider_value == "claude-code":
return [binary_path, "auth", "login"]
raise AuthSetupError(f"No interactive login command is registered for {profile.label}.")
def _run_vendor_login(profile: ProviderAuthProfile, binary_path: str) -> None:
try:
result = subprocess.run(_subscription_login_command(profile, binary_path), check=False)
except OSError as exc:
raise AuthSetupError(f"Could not launch {profile.label} login: {exc}") from exc
if result.returncode != 0:
raise AuthSetupError(f"{profile.label} login exited with code {result.returncode}.")
def configure_cli_subscription_provider(
*,
profile: ProviderAuthProfile,
model: str | None = None,
set_provider: bool = True,
launch_login: bool = True,
env_path: Path | None = None,
) -> AuthSetupResult:
"""Configure a CLI-backed subscription provider such as ChatGPT/Codex or Claude Code."""
provider = provider_for_profile(profile)
if provider.credential_kind != WizardCredentialKind.CLI or provider.adapter_factory is None:
raise AuthSetupError(f"{provider.label} is not a CLI-backed subscription provider.")
adapter = provider.adapter_factory()
probe = adapter.detect()
if not probe.installed:
raise AuthSetupError(f"{probe.detail} Install: {adapter.install_hint}")
login_completed = False
if probe.logged_in is not True:
if profile.provider_value == "codex" and launch_login:
detail = _managed_codex_login_detail()
selected_model = (model if model is not None else provider.default_model).strip()
public_provider = PROVIDER_BY_VALUE["openai"]
written_path = (
sync_provider_env(
provider=public_provider,
model=selected_model,
model_provider=provider,
auth_method=OAUTH_AUTH_METHOD,
env_path=env_path,
)
if set_provider
else None
)
_save_auth_record(
provider=provider,
profile=profile,
source="codex-oauth",
detail=detail,
)
return AuthSetupResult(
provider=provider.value,
model=selected_model,
source="codex-oauth",
detail=detail,
env_path=written_path,
)
if launch_login and probe.bin_path:
_run_vendor_login(profile, probe.bin_path)
login_completed = True
probe = adapter.detect()
if probe.logged_in is not True and not login_completed:
raise AuthSetupError(f"{probe.detail} {adapter.auth_hint}")
selected_model = (model if model is not None else provider.default_model).strip()
written_path = (
sync_provider_env(provider=provider, model=selected_model, env_path=env_path)
if set_provider
else None
)
detail = (
f"{provider.label} login completed via {adapter.auth_hint.replace('Run: ', '')}."
if login_completed and probe.logged_in is not True
else probe.detail or f"{provider.label} is authenticated."
)
_save_auth_record(provider=provider, profile=profile, source="vendor-cli", detail=detail)
return AuthSetupResult(
provider=provider.value,
model=selected_model,
source="vendor-cli",
detail=detail,
env_path=written_path,
)
def provider_status(raw_name: str) -> AuthStatus:
"""Return auth status for an auth profile or provider alias."""
profile = resolve_auth_profile(raw_name)
provider = provider_for_profile(profile)
record = resolve_provider_auth_record(provider.value)
if profile.kind == "api_key":
resolved = provider_auth_status(provider.value)
source = resolved.source
authenticated = resolved.configured and not resolved.stale
detail = resolved.detail
if record.get("detail") and authenticated:
detail = record["detail"]
return AuthStatus(
provider.value,
profile.label,
authenticated,
source,
detail,
verified=resolved.verified,
stale=resolved.stale,
)
record_verified = (record.get("verified") or "").strip().lower()
record_stale = (record.get("stale") or "").strip().lower()
if (
record.get("source") == "codex-oauth"
and record_verified != "false"
and record_stale != "true"
):
return AuthStatus(
provider.value,
profile.label,
True,
"codex-oauth",
record.get("detail") or "OpenAI OAuth tokens are stored for Codex.",
verified=True,
)
if provider.adapter_factory is None:
return AuthStatus(provider.value, profile.label, False, "none", "No adapter registered.")
probe = provider.adapter_factory().detect()
authenticated = probe.installed and probe.logged_in is True
cli_source = "vendor-cli" if authenticated else "none"
detail = probe.detail
if record.get("detail") and authenticated:
detail = record["detail"]
return AuthStatus(
provider.value, profile.label, authenticated, cli_source, detail, verified=authenticated
)
def verify_provider(raw_name: str) -> AuthStatus:
"""Intentionally resolve request-time credentials and refresh metadata."""
profile = resolve_auth_profile(raw_name)
provider = provider_for_profile(profile)
if profile.kind != "api_key":
return provider_status(raw_name)
resolved = verify_provider_auth(provider.value)
return AuthStatus(
provider.value,
profile.label,
resolved.configured and not resolved.stale,
resolved.source,
resolved.detail,
verified=resolved.verified,
stale=resolved.stale,
)
def logout_provider(raw_name: str, *, vendor: bool = False) -> str:
"""Clear OpenSRE-managed auth for a provider.
For API-key providers this deletes the API key from every local tier. For
subscription CLI providers, OpenSRE clears only its metadata unless
``vendor=True`` is requested; the actual session belongs to the vendor CLI.
"""
profile = resolve_auth_profile(raw_name)
provider = provider_for_profile(profile)
delete_provider_auth_record(provider.value)
if profile.kind == "api_key":
try:
delete_provider_auth(provider.value)
except KeyringUnavailableError as exc:
raise AuthSetupError(str(exc)) from exc
return f"Removed {provider.api_key_env} from OpenSRE's local credential storage."
if not vendor:
return (
f"Cleared OpenSRE auth metadata for {profile.label}. "
f"Vendor CLI session remains; logout with: {profile.auth_hint.replace('login', 'logout')}"
)
if provider.adapter_factory is None:
raise AuthSetupError(f"No adapter is registered for {provider.label}.")
probe = provider.adapter_factory().detect()
if not probe.installed or not probe.bin_path:
raise AuthSetupError(f"{provider.label} CLI is not installed.")
command = profile.auth_hint.replace("Run: ", "").replace("login", "logout").split()
try:
result = subprocess.run([probe.bin_path, *command[1:]], check=False)
except OSError as exc:
raise AuthSetupError(f"Could not launch vendor logout: {exc}") from exc
if result.returncode != 0:
raise AuthSetupError(f"Vendor logout exited with code {result.returncode}.")
return f"Logged out of {profile.label} via vendor CLI."
__all__ = [
"AuthSetupError",
"AuthSetupResult",
"AuthStatus",
"configure_api_key_provider",
"configure_cli_subscription_provider",
"logout_provider",
"persist_api_key_secret",
"provider_status",
"verify_provider",
]