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.
- talentprism_cli/LICENSE.txt +17 -0
- talentprism_cli/README.md +70 -0
- talentprism_cli/__init__.py +1 -0
- talentprism_cli/__main__.py +5 -0
- talentprism_cli/auth.py +222 -0
- talentprism_cli/cli.py +1158 -0
- talentprism_cli/config.py +311 -0
- talentprism_cli/config_store.py +144 -0
- talentprism_cli/credentials.py +154 -0
- talentprism_cli/errors.py +48 -0
- talentprism_cli/format.py +96 -0
- talentprism_cli/loopback.py +143 -0
- talentprism_cli/network_bootstrap.py +113 -0
- talentprism_cli/oauth.py +193 -0
- talentprism_cli/readonly_api.py +327 -0
- talentprism_cli/sequence_writes.py +74 -0
- talentprism_cli/skill.py +165 -0
- talentprism_cli/transport.py +277 -0
- talentprism_cli-0.3.0.dist-info/METADATA +93 -0
- talentprism_cli-0.3.0.dist-info/RECORD +24 -0
- talentprism_cli-0.3.0.dist-info/WHEEL +5 -0
- talentprism_cli-0.3.0.dist-info/entry_points.txt +2 -0
- talentprism_cli-0.3.0.dist-info/licenses/talentprism_cli/LICENSE.txt +17 -0
- talentprism_cli-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def format_output(payload: Any, output: str) -> str:
|
|
10
|
+
if output == "json":
|
|
11
|
+
return json.dumps(payload, separators=(",", ":")) + "\n"
|
|
12
|
+
if output == "csv":
|
|
13
|
+
return _format_csv(payload)
|
|
14
|
+
if output == "yaml":
|
|
15
|
+
return _format_yaml(payload)
|
|
16
|
+
return _format_table(payload)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _flatten(payload: dict[str, Any], prefix: str = "") -> dict[str, Any]:
|
|
20
|
+
flattened: dict[str, Any] = {}
|
|
21
|
+
for key, value in payload.items():
|
|
22
|
+
name = f"{prefix}.{key}" if prefix else key
|
|
23
|
+
if isinstance(value, dict):
|
|
24
|
+
flattened.update(_flatten(value, name))
|
|
25
|
+
else:
|
|
26
|
+
flattened[name] = value
|
|
27
|
+
return flattened
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _flatten_rows(rows: list[Any]) -> list[dict[str, Any]]:
|
|
31
|
+
return [_flatten(row) if isinstance(row, dict) else {"value": row} for row in rows]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _union_headers(rows: list[dict[str, Any]]) -> list[str]:
|
|
35
|
+
headers: list[str] = []
|
|
36
|
+
seen: set[str] = set()
|
|
37
|
+
for row in rows:
|
|
38
|
+
for key in row:
|
|
39
|
+
if key not in seen:
|
|
40
|
+
seen.add(key)
|
|
41
|
+
headers.append(key)
|
|
42
|
+
return headers
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _format_csv(payload: Any) -> str:
|
|
46
|
+
rows = payload if isinstance(payload, list) else [payload]
|
|
47
|
+
flattened_rows = _flatten_rows(rows)
|
|
48
|
+
headers = _union_headers(flattened_rows)
|
|
49
|
+
output = io.StringIO()
|
|
50
|
+
writer = csv.DictWriter(output, fieldnames=headers, restval="", lineterminator="\n")
|
|
51
|
+
writer.writeheader()
|
|
52
|
+
writer.writerows(flattened_rows)
|
|
53
|
+
return output.getvalue()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _format_yaml(payload: Any) -> str:
|
|
57
|
+
try:
|
|
58
|
+
import yaml
|
|
59
|
+
|
|
60
|
+
return yaml.safe_dump(payload, sort_keys=False)
|
|
61
|
+
except ImportError:
|
|
62
|
+
return json.dumps(payload, indent=2) + "\n"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _format_table(payload: Any) -> str:
|
|
66
|
+
if isinstance(payload, list):
|
|
67
|
+
return _format_rows_table(payload)
|
|
68
|
+
if isinstance(payload, dict) and isinstance(payload.get("results"), list):
|
|
69
|
+
summary = {key: value for key, value in payload.items() if key != "results"}
|
|
70
|
+
parts = []
|
|
71
|
+
if summary:
|
|
72
|
+
parts.append(_format_pairs_table(summary))
|
|
73
|
+
parts.append(_format_rows_table(payload["results"]))
|
|
74
|
+
return "\n".join(parts)
|
|
75
|
+
return _format_pairs_table(payload if isinstance(payload, dict) else {"value": payload})
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _format_pairs_table(payload: dict[str, Any]) -> str:
|
|
79
|
+
data = _flatten(payload)
|
|
80
|
+
width = max([len(key) for key in data.keys()] or [0])
|
|
81
|
+
return "\n".join(f"{key.ljust(width)} {value}" for key, value in data.items()) + "\n"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _format_rows_table(rows: list[Any]) -> str:
|
|
85
|
+
if not rows:
|
|
86
|
+
return "(no rows)\n"
|
|
87
|
+
flattened_rows = _flatten_rows(rows)
|
|
88
|
+
headers = _union_headers(flattened_rows)
|
|
89
|
+
widths = {header: len(header) for header in headers}
|
|
90
|
+
for row in flattened_rows:
|
|
91
|
+
for header in headers:
|
|
92
|
+
widths[header] = max(widths[header], len(str(row.get(header, ""))))
|
|
93
|
+
lines = [" ".join(header.ljust(widths[header]) for header in headers)]
|
|
94
|
+
for row in flattened_rows:
|
|
95
|
+
lines.append(" ".join(str(row.get(header, "")).ljust(widths[header]) for header in headers))
|
|
96
|
+
return "\n".join(line.rstrip() for line in lines) + "\n"
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""One-shot loopback HTTP server that receives the OAuth redirect, plus the paste-back fallback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
import socket
|
|
7
|
+
import threading
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
9
|
+
from typing import Any, TextIO
|
|
10
|
+
from urllib.parse import parse_qs, urlparse
|
|
11
|
+
|
|
12
|
+
from .errors import TalentPrismError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
CALLBACK_PATH = "/callback"
|
|
16
|
+
LOGIN_TIMEOUT_SECONDS = 300.0
|
|
17
|
+
_PAGE = (
|
|
18
|
+
"<!doctype html><html><head><meta charset='utf-8'><title>TalentPrism CLI</title></head>"
|
|
19
|
+
"<body style='font-family:sans-serif;max-width:32rem;margin:4rem auto'><h2>{title}</h2>"
|
|
20
|
+
"<p>{body}</p></body></html>"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
25
|
+
def do_GET(self) -> None: # noqa: N802 (http.server API)
|
|
26
|
+
parsed = urlparse(self.path)
|
|
27
|
+
if parsed.path != CALLBACK_PATH:
|
|
28
|
+
self._reply(404, "Not found", "This address is not used by the TalentPrism CLI.")
|
|
29
|
+
return
|
|
30
|
+
params = {key: values[0] for key, values in parse_qs(parsed.query).items()}
|
|
31
|
+
self.server.result = params # type: ignore[attr-defined]
|
|
32
|
+
if params.get("error"):
|
|
33
|
+
self._reply(400, "Sign-in cancelled", "You can close this tab and return to your terminal.")
|
|
34
|
+
else:
|
|
35
|
+
self._reply(200, "You are signed in", "You can close this tab and return to your terminal.")
|
|
36
|
+
|
|
37
|
+
def _reply(self, status: int, title: str, body: str) -> None:
|
|
38
|
+
payload = _PAGE.format(title=title, body=body).encode("utf-8")
|
|
39
|
+
self.send_response(status)
|
|
40
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
41
|
+
self.send_header("Content-Length", str(len(payload)))
|
|
42
|
+
self.send_header("Cache-Control", "no-store")
|
|
43
|
+
self.end_headers()
|
|
44
|
+
self.wfile.write(payload)
|
|
45
|
+
|
|
46
|
+
def log_message(self, format: str, *args: Any) -> None: # keep the query string (code) out of any log
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CallbackServer:
|
|
51
|
+
"""Binds 127.0.0.1 only, on an ephemeral port, and serves from a background thread.
|
|
52
|
+
|
|
53
|
+
Serving in the background matters: opening a browser can block (some launchers wait for the
|
|
54
|
+
browser process), and the redirect must still be answered while that call is in flight.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self) -> None:
|
|
58
|
+
self._server = HTTPServer(("127.0.0.1", 0), _Handler)
|
|
59
|
+
self._server.result = None # type: ignore[attr-defined]
|
|
60
|
+
self._server.timeout = 0.2
|
|
61
|
+
self._stop = threading.Event()
|
|
62
|
+
self._thread = threading.Thread(target=self._serve, daemon=True)
|
|
63
|
+
self.port: int = self._server.server_address[1]
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def redirect_uri(self) -> str:
|
|
67
|
+
return f"http://127.0.0.1:{self.port}{CALLBACK_PATH}"
|
|
68
|
+
|
|
69
|
+
def start(self) -> None:
|
|
70
|
+
self._thread.start()
|
|
71
|
+
|
|
72
|
+
def _serve(self) -> None:
|
|
73
|
+
while not self._stop.is_set() and self._server.result is None: # type: ignore[attr-defined]
|
|
74
|
+
self._server.handle_request()
|
|
75
|
+
|
|
76
|
+
def wait(self, timeout: float = LOGIN_TIMEOUT_SECONDS) -> dict[str, str]:
|
|
77
|
+
self._thread.join(timeout)
|
|
78
|
+
result = self._server.result # type: ignore[attr-defined]
|
|
79
|
+
if result is None:
|
|
80
|
+
raise TalentPrismError(
|
|
81
|
+
code="login_timeout",
|
|
82
|
+
type="auth",
|
|
83
|
+
message="Timed out waiting for the browser sign-in to finish.",
|
|
84
|
+
remediation="Run `tp login` again, or `tp login --no-browser` to paste the redirected URL.",
|
|
85
|
+
)
|
|
86
|
+
return result
|
|
87
|
+
|
|
88
|
+
def close(self) -> None:
|
|
89
|
+
self._stop.set()
|
|
90
|
+
if self._thread.is_alive():
|
|
91
|
+
self._thread.join(2)
|
|
92
|
+
self._server.server_close()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def free_port_redirect_uri() -> str:
|
|
96
|
+
"""Redirect URI for --no-browser, where nothing listens and the user pastes the final URL back."""
|
|
97
|
+
with socket.socket() as sock:
|
|
98
|
+
sock.bind(("127.0.0.1", 0))
|
|
99
|
+
return f"http://127.0.0.1:{sock.getsockname()[1]}{CALLBACK_PATH}"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def read_pasted_redirect(stdin: TextIO) -> tuple[dict[str, str], bool]:
|
|
103
|
+
"""Parse a pasted redirect URL or bare code into (callback params, is_bare_code)."""
|
|
104
|
+
line = stdin.readline().strip()
|
|
105
|
+
if not line:
|
|
106
|
+
raise TalentPrismError(
|
|
107
|
+
code="login_cancelled",
|
|
108
|
+
type="auth",
|
|
109
|
+
message="No redirected URL or code was pasted.",
|
|
110
|
+
remediation="Run `tp login --no-browser` again and paste the full URL from the browser address bar.",
|
|
111
|
+
)
|
|
112
|
+
if "://" in line or "?" in line:
|
|
113
|
+
return {key: values[0] for key, values in parse_qs(urlparse(line).query).items()}, False
|
|
114
|
+
return {"code": line}, True # a bare code carries no state; PKCE still binds it to this login
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def check_callback(params: dict[str, str], expected_state: str, *, bare_code: bool = False) -> str:
|
|
118
|
+
"""Validate callback params and return the authorization code."""
|
|
119
|
+
if params.get("error"):
|
|
120
|
+
raise TalentPrismError(
|
|
121
|
+
code="login_denied",
|
|
122
|
+
type="auth",
|
|
123
|
+
message="Sign-in was not approved.",
|
|
124
|
+
details={"error": params["error"], "error_description": params.get("error_description", "")},
|
|
125
|
+
remediation="Run `tp login` again and approve access for the CLI.",
|
|
126
|
+
)
|
|
127
|
+
# A bare pasted code has no state to compare; every other path must present a matching one.
|
|
128
|
+
if not bare_code and not hmac.compare_digest(params.get("state", "").encode(), expected_state.encode()):
|
|
129
|
+
raise TalentPrismError(
|
|
130
|
+
code="login_state_mismatch",
|
|
131
|
+
type="auth",
|
|
132
|
+
message="The sign-in response did not match this login attempt.",
|
|
133
|
+
remediation="Run `tp login` again. If this keeps happening, do not approve unexpected prompts.",
|
|
134
|
+
)
|
|
135
|
+
code = params.get("code", "")
|
|
136
|
+
if not code:
|
|
137
|
+
raise TalentPrismError(
|
|
138
|
+
code="login_failed",
|
|
139
|
+
type="auth",
|
|
140
|
+
message="The sign-in response did not include an authorization code.",
|
|
141
|
+
remediation="Run `tp login` again.",
|
|
142
|
+
)
|
|
143
|
+
return code
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import socket
|
|
5
|
+
from ipaddress import ip_address
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Mapping
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def bootstrap_network_from_env(env: Mapping[str, str] | None = None) -> None:
|
|
12
|
+
env = env or os.environ
|
|
13
|
+
host, port = _target_host_and_port(env)
|
|
14
|
+
cache_path = _cache_path(env)
|
|
15
|
+
force_fallback = env.get("TALENTPRISM_FORCE_HOST_FALLBACK") == "1"
|
|
16
|
+
|
|
17
|
+
if not force_fallback:
|
|
18
|
+
try:
|
|
19
|
+
_write_cache(cache_path, _resolve_ips(host, port))
|
|
20
|
+
return
|
|
21
|
+
except socket.gaierror:
|
|
22
|
+
cached_ips = _read_cache(cache_path)
|
|
23
|
+
if not cached_ips:
|
|
24
|
+
raise
|
|
25
|
+
_install_dns_override(host, cached_ips)
|
|
26
|
+
return
|
|
27
|
+
|
|
28
|
+
cached_ips = _read_cache(cache_path)
|
|
29
|
+
if not cached_ips:
|
|
30
|
+
raise RuntimeError(f"No cached IPs available in {cache_path}")
|
|
31
|
+
_install_dns_override(host, cached_ips)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _target_host_and_port(env: Mapping[str, str]) -> tuple[str, int]:
|
|
35
|
+
base_url = env.get("TALENTPRISM_BASE_URL", "https://talentprism.ai")
|
|
36
|
+
parsed = urlparse(base_url)
|
|
37
|
+
host = parsed.hostname or "talentprism.ai"
|
|
38
|
+
if parsed.port:
|
|
39
|
+
port = parsed.port
|
|
40
|
+
elif parsed.scheme == "http":
|
|
41
|
+
port = 80
|
|
42
|
+
else:
|
|
43
|
+
port = 443
|
|
44
|
+
return host, port
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _cache_path(env: Mapping[str, str]) -> Path:
|
|
48
|
+
raw = env.get("TALENTPRISM_HOST_CACHE_PATH")
|
|
49
|
+
if not raw:
|
|
50
|
+
raise RuntimeError("TALENTPRISM_HOST_CACHE_PATH is required")
|
|
51
|
+
return Path(raw)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _resolve_ips(host: str, port: int) -> list[str]:
|
|
55
|
+
ips: list[str] = []
|
|
56
|
+
seen: set[str] = set()
|
|
57
|
+
for family, socktype, proto, _canonname, sockaddr in socket.getaddrinfo(host, port, type=socket.SOCK_STREAM):
|
|
58
|
+
if family not in {socket.AF_INET, socket.AF_INET6}:
|
|
59
|
+
continue
|
|
60
|
+
ip = sockaddr[0]
|
|
61
|
+
if ip in seen:
|
|
62
|
+
continue
|
|
63
|
+
seen.add(ip)
|
|
64
|
+
ips.append(ip)
|
|
65
|
+
if not ips:
|
|
66
|
+
raise socket.gaierror(f"No addresses returned for {host}")
|
|
67
|
+
return ips
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _write_cache(path: Path, ips: list[str]) -> None:
|
|
71
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
path.write_text("\n".join(ips) + "\n", encoding="utf-8")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _read_cache(path: Path) -> list[str]:
|
|
76
|
+
if not path.exists():
|
|
77
|
+
return []
|
|
78
|
+
ips: list[str] = []
|
|
79
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
80
|
+
candidate = line.strip()
|
|
81
|
+
if not candidate:
|
|
82
|
+
continue
|
|
83
|
+
try:
|
|
84
|
+
ip_address(candidate)
|
|
85
|
+
except ValueError:
|
|
86
|
+
continue
|
|
87
|
+
ips.append(candidate)
|
|
88
|
+
return ips
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _install_dns_override(host: str, ips: list[str]) -> None:
|
|
92
|
+
original_getaddrinfo = socket.getaddrinfo
|
|
93
|
+
|
|
94
|
+
def patched_getaddrinfo(target, port, family=0, type=0, proto=0, flags=0):
|
|
95
|
+
if target == host:
|
|
96
|
+
results = []
|
|
97
|
+
for ip in ips:
|
|
98
|
+
parsed_ip = ip_address(ip)
|
|
99
|
+
ip_family = socket.AF_INET6 if parsed_ip.version == 6 else socket.AF_INET
|
|
100
|
+
if family not in (0, ip_family):
|
|
101
|
+
continue
|
|
102
|
+
socktype = type or socket.SOCK_STREAM
|
|
103
|
+
ip_proto = proto or socket.IPPROTO_TCP
|
|
104
|
+
if ip_family == socket.AF_INET6:
|
|
105
|
+
sockaddr = (ip, port, 0, 0)
|
|
106
|
+
else:
|
|
107
|
+
sockaddr = (ip, port)
|
|
108
|
+
results.append((ip_family, socktype, ip_proto, "", sockaddr))
|
|
109
|
+
if results:
|
|
110
|
+
return results
|
|
111
|
+
return original_getaddrinfo(target, port, family, type, proto, flags)
|
|
112
|
+
|
|
113
|
+
socket.getaddrinfo = patched_getaddrinfo
|
talentprism_cli/oauth.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""OAuth 2.0 client calls for `tp login`: PKCE helpers, dynamic registration, token, refresh, revoke.
|
|
2
|
+
|
|
3
|
+
Every call goes through `_post`, which applies the same HTTPS guard as API traffic (a code, verifier or
|
|
4
|
+
refresh token never travels over plain http to a non-loopback host) and never follows redirects.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import hashlib
|
|
11
|
+
import secrets
|
|
12
|
+
from typing import Any, Callable
|
|
13
|
+
from urllib.parse import quote, urlencode
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .config import validate_base_url_scheme
|
|
17
|
+
from .errors import TalentPrismError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
RequestFn = Callable[..., Any]
|
|
21
|
+
|
|
22
|
+
CLIENT_NAME = "TalentPrism CLI"
|
|
23
|
+
LOOPBACK_REDIRECT = "http://127.0.0.1/callback"
|
|
24
|
+
SCOPE = "cli:access offline_access"
|
|
25
|
+
OAUTH_TIMEOUT_SECONDS = 30.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def resource_for(base_url: str) -> str:
|
|
29
|
+
return f"{base_url.rstrip('/')}/api/"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def new_verifier() -> str:
|
|
33
|
+
return secrets.token_urlsafe(64)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def code_challenge(verifier: str) -> str:
|
|
37
|
+
digest = hashlib.sha256(verifier.encode("ascii")).digest()
|
|
38
|
+
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def authorize_url(base_url: str, *, client_id: str, redirect_uri: str, state: str, challenge: str) -> str:
|
|
42
|
+
query = urlencode(
|
|
43
|
+
{
|
|
44
|
+
"client_id": client_id,
|
|
45
|
+
"redirect_uri": redirect_uri,
|
|
46
|
+
"response_type": "code",
|
|
47
|
+
"scope": SCOPE,
|
|
48
|
+
"state": state,
|
|
49
|
+
"code_challenge": challenge,
|
|
50
|
+
"code_challenge_method": "S256",
|
|
51
|
+
"resource": resource_for(base_url),
|
|
52
|
+
},
|
|
53
|
+
safe=":/",
|
|
54
|
+
quote_via=quote,
|
|
55
|
+
)
|
|
56
|
+
return f"{base_url.rstrip('/')}/oauth/authorize/?{query}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def register_client(base_url: str, *, request: RequestFn, insecure_ok: bool = False, timeout: float | None = None):
|
|
60
|
+
body = {
|
|
61
|
+
"client_name": CLIENT_NAME,
|
|
62
|
+
"redirect_uris": [LOOPBACK_REDIRECT],
|
|
63
|
+
"grant_types": ["authorization_code", "refresh_token"],
|
|
64
|
+
"response_types": ["code"],
|
|
65
|
+
"token_endpoint_auth_method": "none",
|
|
66
|
+
}
|
|
67
|
+
response = _post(base_url, "/oauth/register/", request, insecure_ok, timeout, json=body)
|
|
68
|
+
payload = _json(response)
|
|
69
|
+
if response.status_code not in (200, 201) or not payload.get("client_id"):
|
|
70
|
+
raise _oauth_error(response, payload, "Could not register the CLI with TalentPrism.")
|
|
71
|
+
return str(payload["client_id"])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def exchange_code(
|
|
75
|
+
base_url: str,
|
|
76
|
+
*,
|
|
77
|
+
client_id: str,
|
|
78
|
+
code: str,
|
|
79
|
+
verifier: str,
|
|
80
|
+
redirect_uri: str,
|
|
81
|
+
request: RequestFn,
|
|
82
|
+
insecure_ok: bool = False,
|
|
83
|
+
timeout: float | None = None,
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
form = {
|
|
86
|
+
"grant_type": "authorization_code",
|
|
87
|
+
"client_id": client_id,
|
|
88
|
+
"code": code,
|
|
89
|
+
"code_verifier": verifier,
|
|
90
|
+
"redirect_uri": redirect_uri,
|
|
91
|
+
"resource": resource_for(base_url),
|
|
92
|
+
}
|
|
93
|
+
return _token_request(base_url, form, request, insecure_ok, timeout)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def refresh_tokens(
|
|
97
|
+
base_url: str,
|
|
98
|
+
*,
|
|
99
|
+
client_id: str,
|
|
100
|
+
refresh_token: str,
|
|
101
|
+
request: RequestFn,
|
|
102
|
+
insecure_ok: bool = False,
|
|
103
|
+
timeout: float | None = None,
|
|
104
|
+
) -> dict[str, Any]:
|
|
105
|
+
form = {
|
|
106
|
+
"grant_type": "refresh_token",
|
|
107
|
+
"client_id": client_id,
|
|
108
|
+
"refresh_token": refresh_token,
|
|
109
|
+
"resource": resource_for(base_url),
|
|
110
|
+
}
|
|
111
|
+
return _token_request(base_url, form, request, insecure_ok, timeout)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def revoke_token(
|
|
115
|
+
base_url: str,
|
|
116
|
+
*,
|
|
117
|
+
client_id: str,
|
|
118
|
+
token: str,
|
|
119
|
+
request: RequestFn,
|
|
120
|
+
insecure_ok: bool = False,
|
|
121
|
+
timeout: float | None = None,
|
|
122
|
+
) -> None:
|
|
123
|
+
response = _post(
|
|
124
|
+
base_url, "/oauth/revoke/", request, insecure_ok, timeout, data=_form({"token": token, "client_id": client_id})
|
|
125
|
+
)
|
|
126
|
+
if response.status_code >= 400:
|
|
127
|
+
raise _oauth_error(response, _json(response), "TalentPrism could not revoke the token.")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def oauth_error_code(exc: TalentPrismError) -> str:
|
|
131
|
+
"""The OAuth `error` value carried by an error raised from this module (e.g. invalid_grant)."""
|
|
132
|
+
return str(exc.details.get("error") or "")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _token_request(base_url, form, request, insecure_ok, timeout) -> dict[str, Any]:
|
|
136
|
+
response = _post(base_url, "/oauth/token/", request, insecure_ok, timeout, data=_form(form))
|
|
137
|
+
payload = _json(response)
|
|
138
|
+
if response.status_code != 200 or not payload.get("access_token"):
|
|
139
|
+
raise _oauth_error(response, payload, "TalentPrism did not issue a token.")
|
|
140
|
+
return payload
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _form(fields: dict[str, str]) -> str:
|
|
144
|
+
return urlencode(fields)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _post(base_url, path, request, insecure_ok, timeout, *, json=None, data=None):
|
|
148
|
+
validate_base_url_scheme(base_url, {"TALENTPRISM_ALLOW_INSECURE_HTTP": "1"} if insecure_ok else {})
|
|
149
|
+
headers = {"Accept": "application/json", "User-Agent": f"TalentPrism CLI/{__version__}"}
|
|
150
|
+
kwargs: dict[str, Any] = {"allow_redirects": False}
|
|
151
|
+
if json is not None:
|
|
152
|
+
kwargs["json"] = json
|
|
153
|
+
else:
|
|
154
|
+
# The token endpoint accepts only form bodies, not JSON.
|
|
155
|
+
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
|
156
|
+
kwargs["data"] = data
|
|
157
|
+
try:
|
|
158
|
+
return request(
|
|
159
|
+
"POST",
|
|
160
|
+
f"{base_url.rstrip('/')}{path}",
|
|
161
|
+
headers=headers,
|
|
162
|
+
timeout=timeout or OAUTH_TIMEOUT_SECONDS,
|
|
163
|
+
**kwargs,
|
|
164
|
+
)
|
|
165
|
+
except OSError as exc:
|
|
166
|
+
raise TalentPrismError(
|
|
167
|
+
code="connection_failed",
|
|
168
|
+
type="transient",
|
|
169
|
+
message=f"Could not reach TalentPrism at {base_url}.",
|
|
170
|
+
details={"error": str(exc)},
|
|
171
|
+
remediation="Check the network connection and base URL, then retry.",
|
|
172
|
+
) from exc
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _json(response) -> dict[str, Any]:
|
|
176
|
+
try:
|
|
177
|
+
payload = response.json()
|
|
178
|
+
except ValueError:
|
|
179
|
+
return {}
|
|
180
|
+
return payload if isinstance(payload, dict) else {}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _oauth_error(response, payload: dict[str, Any], message: str) -> TalentPrismError:
|
|
184
|
+
status = response.status_code
|
|
185
|
+
error = str(payload.get("error") or "")
|
|
186
|
+
transient = status >= 500 or status == 429
|
|
187
|
+
return TalentPrismError(
|
|
188
|
+
code=f"oauth_{error}" if error else ("oauth_unavailable" if transient else "oauth_failed"),
|
|
189
|
+
type="transient" if transient else "auth",
|
|
190
|
+
message=message,
|
|
191
|
+
details={"status": status, "error": error, "error_description": str(payload.get("error_description") or "")},
|
|
192
|
+
remediation="Retry shortly." if transient else "Run `tp login` to sign in again.",
|
|
193
|
+
)
|