talentprism-cli 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,311 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import stat
5
+ import time
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Any
10
+ from urllib.parse import urlparse
11
+
12
+ from .config_store import (
13
+ DEFAULT_CONFIG_PATH,
14
+ DEFAULT_PROFILE,
15
+ config_lock,
16
+ config_path as _config_path,
17
+ load_config,
18
+ write_config,
19
+ )
20
+ from .errors import TalentPrismError
21
+
22
+
23
+ __all__ = ["DEFAULT_BASE_URL", "DEFAULT_CONFIG_PATH", "DEFAULT_PROFILE", "TalentPrismConfig", "resolve_config"]
24
+
25
+ DEFAULT_BASE_URL = "https://talentprism.ai"
26
+ DEFAULT_TIMEOUT_SECONDS = 30.0
27
+ DEFAULT_GET_RETRIES = 2
28
+ LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1", "0.0.0.0"}
29
+ SECRET_KEYS = ("api_key", "access_token", "refresh_token")
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class TalentPrismConfig:
34
+ api_key: str
35
+ base_url: str = DEFAULT_BASE_URL
36
+ profile: str = DEFAULT_PROFILE
37
+ api_key_source: str = "default"
38
+ base_url_source: str = "default"
39
+ # "api_key" (flag, env or profile key), "login" (tokens from `tp login`) or "none".
40
+ auth_kind: str = "api_key"
41
+ access_token: str = ""
42
+ refresh_token: str = ""
43
+ token_expires_at: float | None = None
44
+ oauth_client_id: str = ""
45
+ config_path: str = ""
46
+ allow_insecure_http: bool = False
47
+ # Transport settings, read from TALENTPRISM_TIMEOUT / _RETRIES / _AGENT_SOURCE in the env given to resolve_config.
48
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
49
+ get_retries: int = DEFAULT_GET_RETRIES
50
+ agent_source: str = ""
51
+
52
+ @property
53
+ def masked_api_key(self) -> str:
54
+ return mask_secret(self.api_key)
55
+
56
+ @property
57
+ def credential_kind(self) -> str:
58
+ return self.auth_kind if (self.api_key or self.access_token or self.refresh_token) else "none"
59
+
60
+
61
+ def transport_settings(env: Any) -> dict[str, Any]:
62
+ """The env-driven transport fields of TalentPrismConfig, so the env given to ``run()`` is the one honoured."""
63
+ try:
64
+ timeout = float(env.get("TALENTPRISM_TIMEOUT") or DEFAULT_TIMEOUT_SECONDS)
65
+ except ValueError:
66
+ timeout = DEFAULT_TIMEOUT_SECONDS
67
+ try:
68
+ retries = max(0, int(env.get("TALENTPRISM_RETRIES") or DEFAULT_GET_RETRIES))
69
+ except ValueError:
70
+ retries = DEFAULT_GET_RETRIES
71
+ return {
72
+ "timeout_seconds": timeout,
73
+ "get_retries": retries,
74
+ "agent_source": str(env.get("TALENTPRISM_AGENT_SOURCE") or "").strip(),
75
+ }
76
+
77
+
78
+ def mask_secret(value: str) -> str:
79
+ if len(value) <= 12:
80
+ return "****"
81
+ return f"{value[:4]}...{value[-4:]}"
82
+
83
+
84
+ def resolve_config(
85
+ *,
86
+ api_key: str | None = None,
87
+ base_url: str | None = None,
88
+ profile: str | None = None,
89
+ config_path: str | Path | None = None,
90
+ env: dict[str, str] | None = None,
91
+ enforce_safe_permissions: bool = False,
92
+ require_api_key: bool = True,
93
+ ) -> TalentPrismConfig:
94
+ env = os.environ if env is None else env
95
+ config_file = _config_path(config_path)
96
+ file_config = _load_config(config_file, enforce_safe_permissions=enforce_safe_permissions)
97
+ profile_name = select_profile(file_config, profile, env)
98
+ profiles = file_config.get("profiles", {})
99
+ profile_config = profiles.get(profile_name, {})
100
+ if profiles and profile_name not in profiles:
101
+ raise TalentPrismError(
102
+ code="config_profile_missing",
103
+ type="invalid_input",
104
+ message=f"Profile '{profile_name}' does not exist in the TalentPrism config file.",
105
+ details={"profile": profile_name, "config_path": str(config_file)},
106
+ remediation="Run `tp config set-profile <name>` with an existing profile or add the profile to the config file.",
107
+ )
108
+
109
+ resolved_base_url, base_url_source = resolve_base_url(base_url, env, profile_config)
110
+ resolved_base_url = resolved_base_url.rstrip("/")
111
+
112
+ # Precedence: --api-key flag > TALENTPRISM_API_KEY env > profile login tokens > profile api_key.
113
+ resolved_api_key = api_key or env.get("TALENTPRISM_API_KEY") or ""
114
+ tokens = _profile_tokens(profile_config, resolved_base_url) if not resolved_api_key else {}
115
+ if resolved_api_key:
116
+ auth_kind, source = "api_key", "flag" if api_key else "env"
117
+ elif tokens:
118
+ auth_kind, source = "login", "profile"
119
+ elif profile_config.get("api_key"):
120
+ resolved_api_key, auth_kind, source = profile_config["api_key"], "api_key", "profile"
121
+ else:
122
+ auth_kind, source = "none", "profile"
123
+ if auth_kind == "none" and require_api_key:
124
+ raise ValueError("TALENTPRISM_API_KEY is required")
125
+ if auth_kind != "none":
126
+ validate_base_url_scheme(resolved_base_url, env)
127
+ return TalentPrismConfig(
128
+ api_key=resolved_api_key,
129
+ base_url=resolved_base_url,
130
+ profile=profile_name,
131
+ api_key_source=source,
132
+ base_url_source=base_url_source,
133
+ auth_kind=auth_kind,
134
+ access_token=tokens.get("access_token", ""),
135
+ refresh_token=tokens.get("refresh_token", ""),
136
+ token_expires_at=parse_expiry(tokens.get("token_expires_at")),
137
+ oauth_client_id=profile_config.get("oauth_client_id", ""),
138
+ config_path=str(config_file),
139
+ allow_insecure_http=env.get("TALENTPRISM_ALLOW_INSECURE_HTTP") == "1",
140
+ **transport_settings(env),
141
+ )
142
+
143
+
144
+ def select_profile(file_config: dict, profile: str | None, env: Any) -> str:
145
+ return profile or env.get("TALENTPRISM_PROFILE") or file_config.get("default_profile") or DEFAULT_PROFILE
146
+
147
+
148
+ def resolve_base_url(flag: str | None, env: Any, profile_config: dict) -> tuple[str, str]:
149
+ if flag:
150
+ return flag, "flag"
151
+ if env.get("TALENTPRISM_BASE_URL"):
152
+ return env["TALENTPRISM_BASE_URL"], "env"
153
+ if profile_config.get("base_url"):
154
+ return profile_config["base_url"], "profile"
155
+ return DEFAULT_BASE_URL, "default"
156
+
157
+
158
+ def _profile_tokens(profile_config: dict, base_url: str) -> dict[str, str]:
159
+ """Login tokens usable against `base_url`; tokens are never sent to a server that did not issue them."""
160
+ if not (profile_config.get("access_token") or profile_config.get("refresh_token")):
161
+ return {}
162
+ issuer = profile_config.get("oauth_base_url")
163
+ if issuer and issuer.rstrip("/") != base_url:
164
+ return {}
165
+ return {key: profile_config.get(key, "") for key in ("access_token", "refresh_token", "token_expires_at")}
166
+
167
+
168
+ def parse_expiry(raw: str | None) -> float | None:
169
+ try:
170
+ return float(raw) if raw else None
171
+ except ValueError:
172
+ return None
173
+
174
+
175
+ def config_status(
176
+ *,
177
+ api_key: str | None = None,
178
+ base_url: str | None = None,
179
+ profile: str | None = None,
180
+ config_path: str | Path | None = None,
181
+ env: dict[str, str] | None = None,
182
+ ) -> dict[str, Any]:
183
+ config = resolve_config(
184
+ api_key=api_key,
185
+ base_url=base_url,
186
+ profile=profile,
187
+ config_path=config_path,
188
+ env=env,
189
+ enforce_safe_permissions=True,
190
+ require_api_key=False,
191
+ )
192
+ has_key = config.auth_kind == "api_key" and bool(config.api_key)
193
+ auth: dict[str, Any] = {"method": None, "source": None}
194
+ if has_key:
195
+ auth = {"method": "api_key", "source": config.api_key_source, "masked": config.masked_api_key}
196
+ elif config.auth_kind == "login":
197
+ expires = config.token_expires_at
198
+ auth = {
199
+ "method": "login",
200
+ "source": "profile",
201
+ "masked": mask_secret(config.access_token) if config.access_token else None,
202
+ "expires_at": datetime.fromtimestamp(expires, timezone.utc).isoformat() if expires else None,
203
+ "expired": bool(expires is None or expires <= time.time()),
204
+ "refreshable": bool(config.refresh_token),
205
+ }
206
+ return {
207
+ "profile": config.profile,
208
+ "base_url": config.base_url,
209
+ "base_url_source": config.base_url_source,
210
+ "auth": auth,
211
+ "api_key": {
212
+ "configured": has_key,
213
+ "masked": config.masked_api_key if has_key else None,
214
+ "source": config.api_key_source if has_key else None,
215
+ },
216
+ }
217
+
218
+
219
+ def set_profile_values(
220
+ config_path: str | Path | None,
221
+ profile_name: str,
222
+ *,
223
+ api_key: str | None = None,
224
+ base_url: str | None = None,
225
+ ) -> dict[str, Any]:
226
+ if not api_key and not base_url:
227
+ raise TalentPrismError(
228
+ code="config_set_missing_values",
229
+ type="invalid_input",
230
+ message="Nothing to set: pass --api-key and/or --base-url.",
231
+ remediation="Re-run `tp config set <name>` with --api-key or --base-url.",
232
+ )
233
+ path = _config_path(config_path)
234
+ updated = []
235
+ with config_lock(path):
236
+ config = _load_config(path, enforce_safe_permissions=False)
237
+ profile = config.setdefault("profiles", {}).setdefault(profile_name, {})
238
+ if api_key:
239
+ profile["api_key"] = api_key
240
+ updated.append("api_key")
241
+ if base_url:
242
+ profile["base_url"] = base_url.rstrip("/")
243
+ updated.append("base_url")
244
+ if not config.get("default_profile"):
245
+ config["default_profile"] = profile_name
246
+ write_config(path, config)
247
+ return {"profile": profile_name, "config_path": str(path), "updated": updated}
248
+
249
+
250
+ def set_active_profile(config_path: str | Path | None, profile_name: str) -> dict[str, Any]:
251
+ path = _config_path(config_path)
252
+ with config_lock(path):
253
+ config = _load_config(path, enforce_safe_permissions=False)
254
+ if profile_name not in config.get("profiles", {}):
255
+ raise TalentPrismError(
256
+ code="config_profile_missing",
257
+ type="invalid_input",
258
+ message=f"Profile '{profile_name}' does not exist in the TalentPrism config file.",
259
+ details={"profile": profile_name, "config_path": str(path)},
260
+ remediation="Add the profile to the config file before selecting it.",
261
+ )
262
+ config["default_profile"] = profile_name
263
+ write_config(path, config)
264
+ return {"profile": profile_name, "config_path": str(path)}
265
+
266
+
267
+ def _load_config(path: Path, *, enforce_safe_permissions: bool) -> dict:
268
+ config = load_config(path)
269
+ if enforce_safe_permissions and _config_contains_secret(config):
270
+ _validate_secret_safe_permissions(path)
271
+ return config
272
+
273
+
274
+ def validate_base_url_scheme(base_url: str, env: Any) -> None:
275
+ """Refuse to send credentials, OAuth codes or tokens over plain http to a non-loopback host."""
276
+ parsed = urlparse(base_url)
277
+ if parsed.scheme != "http":
278
+ return
279
+ host = (parsed.hostname or "").lower()
280
+ if host in LOOPBACK_HOSTS or host.endswith(".localhost"):
281
+ return
282
+ if env.get("TALENTPRISM_ALLOW_INSECURE_HTTP") == "1":
283
+ return
284
+ raise TalentPrismError(
285
+ code="insecure_base_url",
286
+ type="invalid_input",
287
+ message="Refusing to send credentials over plain HTTP to a non-local host.",
288
+ details={"base_url": base_url},
289
+ remediation=(
290
+ "Use an https:// base URL. For trusted private networks (e.g. Docker service hostnames), "
291
+ "set TALENTPRISM_ALLOW_INSECURE_HTTP=1 to accept the risk."
292
+ ),
293
+ )
294
+
295
+
296
+ def _config_contains_secret(config: dict[str, Any]) -> bool:
297
+ return any(bool(profile.get(key)) for profile in config.get("profiles", {}).values() for key in SECRET_KEYS)
298
+
299
+
300
+ def _validate_secret_safe_permissions(path: Path) -> None:
301
+ if os.name == "nt":
302
+ return
303
+ mode = stat.S_IMODE(path.stat().st_mode)
304
+ if mode & 0o077:
305
+ raise TalentPrismError(
306
+ code="config_permissions_unsafe",
307
+ type="invalid_input",
308
+ message="TalentPrism config file contains credentials but is readable by other users.",
309
+ details={"config_path": str(path), "mode": oct(mode)},
310
+ remediation="Run `chmod 600 <config_path>` or rerun `tp config set-profile <name>` to repair permissions.",
311
+ )
@@ -0,0 +1,144 @@
1
+ """Reading and atomically writing the on-disk config file (~/.talentprism/config.toml).
2
+
3
+ The file is a small TOML subset: string values at the top level and in `[profiles.<name>]`
4
+ tables. Reads use stdlib tomllib; writes are hand-rolled so the format stays stable and every
5
+ value is escaped. Writes go to a private temp file (0600 from creation) and are renamed into
6
+ place, so a crash never leaves a half-written or world-readable file.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import secrets
14
+ import tomllib
15
+ from contextlib import contextmanager
16
+ from pathlib import Path
17
+ from typing import Any, Iterator
18
+
19
+ from .errors import TalentPrismError
20
+
21
+
22
+ DEFAULT_PROFILE = "default"
23
+ DEFAULT_CONFIG_PATH = Path.home() / ".talentprism" / "config.toml"
24
+ _BARE_KEY = re.compile(r"^[A-Za-z0-9_-]+$")
25
+ _ESCAPES = {"\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t"}
26
+
27
+
28
+ def config_path(path: str | Path | None) -> Path:
29
+ return Path(path).expanduser() if path else DEFAULT_CONFIG_PATH
30
+
31
+
32
+ def load_config(path: Path) -> dict:
33
+ if not path.exists():
34
+ return {}
35
+ try:
36
+ parsed = tomllib.loads(path.read_text(encoding="utf-8"))
37
+ except tomllib.TOMLDecodeError as exc:
38
+ raise _malformed_config(path, _error_line(exc)) from exc
39
+ except UnicodeDecodeError as exc:
40
+ raise _malformed_config(path, None) from exc
41
+ config: dict = {"profiles": {}}
42
+ for key, value in parsed.items():
43
+ if key == "profiles":
44
+ if not isinstance(value, dict):
45
+ raise _malformed_config(path, None)
46
+ for name, values in value.items():
47
+ if not isinstance(values, dict) or not all(isinstance(v, str) for v in values.values()):
48
+ raise _malformed_config(path, None)
49
+ config["profiles"][name] = dict(values)
50
+ elif isinstance(value, str):
51
+ config[key] = value
52
+ else:
53
+ raise _malformed_config(path, None)
54
+ return config
55
+
56
+
57
+ def write_config(path: Path, config: dict[str, Any]) -> None:
58
+ contents = _render(config)
59
+ _ensure_private_dir(path.parent)
60
+ temp = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
61
+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
62
+ try:
63
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
64
+ handle.write(contents)
65
+ handle.flush()
66
+ os.fsync(handle.fileno())
67
+ os.replace(temp, path)
68
+ except BaseException:
69
+ temp.unlink(missing_ok=True)
70
+ raise
71
+
72
+
73
+ @contextmanager
74
+ def config_lock(path: Path) -> Iterator[None]:
75
+ """Serialise read-modify-write cycles across `tp` processes (POSIX flock; no-op elsewhere)."""
76
+ try:
77
+ import fcntl
78
+ except ImportError: # Windows: best effort, atomic replace still prevents torn files.
79
+ yield
80
+ return
81
+ _ensure_private_dir(path.parent)
82
+ fd = os.open(path.with_name(path.name + ".lock"), os.O_RDWR | os.O_CREAT, 0o600)
83
+ try:
84
+ fcntl.flock(fd, fcntl.LOCK_EX)
85
+ yield
86
+ finally:
87
+ try:
88
+ fcntl.flock(fd, fcntl.LOCK_UN)
89
+ finally:
90
+ os.close(fd)
91
+
92
+
93
+ def _render(config: dict[str, Any]) -> str:
94
+ lines = [f"default_profile = {_quote(config.get('default_profile', DEFAULT_PROFILE))}"]
95
+ # Preserve every key we parsed, not just the ones this CLI knows about,
96
+ # so rewriting the file never drops hand-edited settings.
97
+ for key, value in config.items():
98
+ if key in ("default_profile", "profiles"):
99
+ continue
100
+ lines.append(f"{_key(key)} = {_quote(value)}")
101
+ lines.append("")
102
+ for name, values in config.get("profiles", {}).items():
103
+ lines.append(f"[profiles.{_key(name)}]")
104
+ for key, value in values.items():
105
+ if value is not None:
106
+ lines.append(f"{_key(key)} = {_quote(value)}")
107
+ lines.append("")
108
+ return "\n".join(lines).rstrip() + "\n"
109
+
110
+
111
+ def _quote(value: Any) -> str:
112
+ text = str(value)
113
+ escaped = "".join(
114
+ _ESCAPES.get(char) or (f"\\u{ord(char):04x}" if ord(char) < 0x20 or ord(char) == 0x7F else char)
115
+ for char in text
116
+ )
117
+ return f'"{escaped}"'
118
+
119
+
120
+ def _key(name: str) -> str:
121
+ return name if _BARE_KEY.match(name) else _quote(name)
122
+
123
+
124
+ def _ensure_private_dir(directory: Path) -> None:
125
+ if not directory.exists():
126
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
127
+
128
+
129
+ def _error_line(exc: tomllib.TOMLDecodeError) -> int | None:
130
+ match = re.search(r"line (\d+)", str(exc))
131
+ return int(match.group(1)) if match else None
132
+
133
+
134
+ def _malformed_config(path: Path, line_number: int | None) -> TalentPrismError:
135
+ details: dict[str, Any] = {"config_path": str(path)}
136
+ if line_number is not None:
137
+ details["line"] = line_number
138
+ return TalentPrismError(
139
+ code="config_malformed",
140
+ type="invalid_input",
141
+ message="TalentPrism config file is malformed.",
142
+ details=details,
143
+ remediation="Fix the TOML syntax or move the file aside and recreate the profile.",
144
+ )
@@ -0,0 +1,154 @@
1
+ """Login-token storage and refresh.
2
+
3
+ Refresh tokens rotate: every refresh returns a new one and revokes the old, and replaying an old one
4
+ revokes the whole grant. So a refresh is a critical section: take the config lock, re-read the file
5
+ (another `tp` process may have just rotated), spend the token only if nobody else did, and persist the
6
+ new pair before the caller retries its request.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from contextlib import nullcontext
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from . import oauth
17
+ from .config import TalentPrismConfig, parse_expiry
18
+ from .config_store import config_lock, load_config, write_config
19
+ from .errors import TalentPrismError
20
+
21
+
22
+ REFRESH_SKEW_SECONDS = 60
23
+ TOKEN_KEYS = ("access_token", "refresh_token", "token_expires_at")
24
+
25
+
26
+ def session_expired_error() -> TalentPrismError:
27
+ return TalentPrismError(
28
+ code="session_expired",
29
+ type="auth",
30
+ message="Your TalentPrism login has expired or was revoked.",
31
+ remediation="Run `tp login` to sign in again.",
32
+ )
33
+
34
+
35
+ def apply_token_payload(profile: dict[str, str], payload: dict[str, Any], *, base_url: str, client_id: str) -> None:
36
+ """Merge a token-endpoint response into a profile dict (in place)."""
37
+ profile["access_token"] = str(payload["access_token"])
38
+ if payload.get("refresh_token"):
39
+ profile["refresh_token"] = str(payload["refresh_token"])
40
+ profile["token_expires_at"] = str(int(time.time() + float(payload.get("expires_in") or 0)))
41
+ profile["oauth_base_url"] = base_url.rstrip("/")
42
+ profile["oauth_client_id"] = client_id
43
+
44
+
45
+ def save_login(path: Path, profile_name: str, payload: dict[str, Any], *, base_url: str, client_id: str) -> None:
46
+ with config_lock(path):
47
+ config = load_config(path)
48
+ profile = config.setdefault("profiles", {}).setdefault(profile_name, {})
49
+ apply_token_payload(profile, payload, base_url=base_url, client_id=client_id)
50
+ if base_url.rstrip("/") != profile.get("base_url", "").rstrip("/"):
51
+ profile["base_url"] = base_url.rstrip("/")
52
+ if not config.get("default_profile"):
53
+ config["default_profile"] = profile_name
54
+ write_config(path, config)
55
+
56
+
57
+ def save_client(path: Path, profile_name: str, *, client_id: str, base_url: str) -> None:
58
+ """Remember the registered OAuth client so later logins reuse it instead of registering again."""
59
+ with config_lock(path):
60
+ config = load_config(path)
61
+ profile = config.setdefault("profiles", {}).setdefault(profile_name, {})
62
+ profile["oauth_client_id"] = client_id
63
+ profile["oauth_base_url"] = base_url.rstrip("/")
64
+ if not config.get("default_profile"):
65
+ config["default_profile"] = profile_name
66
+ write_config(path, config)
67
+
68
+
69
+ def clear_login(path: Path, profile_name: str, *, forget_client: bool = False) -> dict[str, str]:
70
+ """Remove stored tokens (api_key and base_url stay). Returns what was removed."""
71
+ with config_lock(path):
72
+ config = load_config(path)
73
+ profile = config.get("profiles", {}).get(profile_name)
74
+ if profile is None:
75
+ return {}
76
+ removed = {key: profile.pop(key) for key in TOKEN_KEYS if key in profile}
77
+ removed["oauth_client_id"] = profile.get("oauth_client_id", "")
78
+ removed["oauth_base_url"] = profile.get("oauth_base_url", "")
79
+ if forget_client:
80
+ profile.pop("oauth_client_id", None)
81
+ profile.pop("oauth_base_url", None)
82
+ write_config(path, config)
83
+ return removed
84
+
85
+
86
+ class TokenManager:
87
+ """Holds the live access/refresh token pair for one APIClient and keeps it fresh."""
88
+
89
+ def __init__(self, config: TalentPrismConfig, request, timeout: float | None = None):
90
+ self._config = config
91
+ self._request = request
92
+ self._timeout = timeout
93
+ self.access_token = config.access_token
94
+ self.refresh_token = config.refresh_token
95
+ self.expires_at = config.token_expires_at
96
+
97
+ def bearer(self) -> str:
98
+ """Access token to send now, refreshing first when it is missing, expired or about to expire."""
99
+ if not self.access_token or self._expiring():
100
+ self.refresh()
101
+ return self.access_token
102
+
103
+ def refresh(self, rejected: str | None = None) -> None:
104
+ """Rotate the tokens. `rejected` is the access token the server just refused, if any."""
105
+ config = self._config
106
+ path = Path(config.config_path) if config.config_path else None
107
+ with config_lock(path) if path else nullcontext():
108
+ full = load_config(path) if path else {}
109
+ profile = full.get("profiles", {}).get(config.profile, {}) if path else {}
110
+ if path:
111
+ self._adopt(profile)
112
+ if not self.refresh_token:
113
+ raise session_expired_error()
114
+ if path and self.access_token and self.access_token != rejected and not self._expiring():
115
+ return # another process already rotated; use its result, do not spend the token again
116
+ client_id = profile.get("oauth_client_id") or config.oauth_client_id
117
+ try:
118
+ payload = oauth.refresh_tokens(
119
+ config.base_url,
120
+ client_id=client_id,
121
+ refresh_token=self.refresh_token,
122
+ request=self._request,
123
+ insecure_ok=config.allow_insecure_http,
124
+ timeout=self._timeout,
125
+ )
126
+ except TalentPrismError as exc:
127
+ code = oauth.oauth_error_code(exc)
128
+ if code in ("invalid_grant", "invalid_client"):
129
+ if path:
130
+ for key in TOKEN_KEYS:
131
+ profile.pop(key, None)
132
+ if code == "invalid_client":
133
+ profile.pop("oauth_client_id", None)
134
+ write_config(path, full)
135
+ self.access_token = self.refresh_token = ""
136
+ raise session_expired_error() from exc
137
+ raise
138
+ values = dict(profile)
139
+ apply_token_payload(values, payload, base_url=config.base_url, client_id=client_id)
140
+ if path:
141
+ profile.update(values)
142
+ full.setdefault("profiles", {})[config.profile] = profile
143
+ write_config(path, full) # persist before the caller retries its request
144
+ self.access_token = values["access_token"]
145
+ self.refresh_token = values["refresh_token"]
146
+ self.expires_at = parse_expiry(values["token_expires_at"])
147
+
148
+ def _adopt(self, profile: dict[str, str]) -> None:
149
+ self.access_token = profile.get("access_token", "")
150
+ self.refresh_token = profile.get("refresh_token", "")
151
+ self.expires_at = parse_expiry(profile.get("token_expires_at"))
152
+
153
+ def _expiring(self) -> bool:
154
+ return self.expires_at is None or self.expires_at - time.time() <= REFRESH_SKEW_SECONDS
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+
7
+ EXIT_CODES = {
8
+ "invalid_input": 2,
9
+ "auth": 3,
10
+ "not_found": 4,
11
+ "validation": 5,
12
+ "transient": 6,
13
+ "schema_mismatch": 7,
14
+ }
15
+
16
+
17
+ @dataclass
18
+ class TalentPrismError(Exception):
19
+ code: str
20
+ type: str
21
+ message: str
22
+ remediation: str
23
+ details: dict[str, Any] = field(default_factory=dict)
24
+
25
+ @property
26
+ def exit_code(self) -> int:
27
+ return EXIT_CODES.get(self.type, 1)
28
+
29
+ def to_payload(self) -> dict[str, Any]:
30
+ return {
31
+ "code": self.code,
32
+ "type": self.type,
33
+ "message": self.message,
34
+ "details": self.details,
35
+ "remediation": self.remediation,
36
+ }
37
+
38
+
39
+ def missing_api_key_error() -> TalentPrismError:
40
+ return TalentPrismError(
41
+ code="missing_api_key",
42
+ type="invalid_input",
43
+ message="No TalentPrism credentials were found.",
44
+ remediation=(
45
+ "Run `tp login` to sign in with your browser. For automation, set TALENTPRISM_API_KEY, "
46
+ "pass --api-key, or add api_key to the active profile."
47
+ ),
48
+ )