haystack-enterprise-sdk 0.2.0__tar.gz → 1.0.1__tar.gz
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.
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/PKG-INFO +11 -2
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/README.md +9 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/config.py +56 -10
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/haystack_enterprise_api.py +16 -4
- haystack_enterprise_sdk-1.0.1/haystack_enterprise_sdk/_api/oauth.py +372 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_s3/upload.py +1 -1
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_service/files_service.py +53 -25
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_service/pipeline_extract.py +16 -3
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_service/pipeline_transform.py +57 -1
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/cli.py +255 -23
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/pyproject.toml +7 -7
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/pyproject.toml.orig +7 -7
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/LICENSE +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/README.md +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/__init__.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/deployments.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/files.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/pipeline_run.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/shared_prototypes.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_api/upload_sessions.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_console.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_s3/__init__.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_service/deployment_service.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_service/io_spec.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_service/pipeline_service.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_utils/__init__.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/_utils/datetime.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/models.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/py.typed +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/__init__.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/async_client/__init__.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/async_client/async_pipeline_client.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/async_client/deployment_client.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/async_client/files.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/sync_client/__init__.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/sync_client/deployment_client.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/sync_client/files.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/sync_client/pipeline_client.py +0 -0
- {haystack_enterprise_sdk-0.2.0 → haystack_enterprise_sdk-1.0.1}/haystack_enterprise_sdk/workflows/sync_client/utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: haystack-enterprise-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 1.0.1
|
|
4
4
|
Summary: Python SDK and CLI for the Haystack Enterprise Platform
|
|
5
5
|
Keywords: agents,deepset,haystack,llm,pipelines,rag,sdk
|
|
6
6
|
Author: deepset.ai
|
|
@@ -24,7 +24,7 @@ Requires-Dist: structlog>=24.0.0
|
|
|
24
24
|
Requires-Dist: httpx>=0.27.2
|
|
25
25
|
Requires-Dist: python-dotenv>=1.0.1
|
|
26
26
|
Requires-Dist: typer>=0.15.0
|
|
27
|
-
Requires-Dist: click<=8.
|
|
27
|
+
Requires-Dist: click<=8.5.0
|
|
28
28
|
Requires-Dist: tenacity>=8.3.0
|
|
29
29
|
Requires-Dist: aiohttp>=3.10.10
|
|
30
30
|
Requires-Dist: aiofiles>=24.1.0
|
|
@@ -58,6 +58,15 @@ Python SDK and CLI for the Haystack Enterprise Platform.
|
|
|
58
58
|
|
|
59
59
|
## Installation
|
|
60
60
|
|
|
61
|
+
On macOS or Linux, one command installs the CLI. It installs [uv](https://docs.astral.sh/uv/) first if
|
|
62
|
+
you don't have it, and running it again upgrades the CLI:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
curl -fsSL https://raw.githubusercontent.com/deepset-ai/haystack-enterprise-sdk/main/install.sh | bash
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Or install it yourself:
|
|
69
|
+
|
|
61
70
|
```bash
|
|
62
71
|
# Install as a CLI tool
|
|
63
72
|
uv tool install haystack-enterprise-sdk
|
|
@@ -13,6 +13,15 @@ Python SDK and CLI for the Haystack Enterprise Platform.
|
|
|
13
13
|
|
|
14
14
|
## Installation
|
|
15
15
|
|
|
16
|
+
On macOS or Linux, one command installs the CLI. It installs [uv](https://docs.astral.sh/uv/) first if
|
|
17
|
+
you don't have it, and running it again upgrades the CLI:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
curl -fsSL https://raw.githubusercontent.com/deepset-ai/haystack-enterprise-sdk/main/install.sh | bash
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or install it yourself:
|
|
24
|
+
|
|
16
25
|
```bash
|
|
17
26
|
# Install as a CLI tool
|
|
18
27
|
uv tool install haystack-enterprise-sdk
|
|
@@ -2,16 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
import os
|
|
4
4
|
import re
|
|
5
|
-
from dataclasses import dataclass
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
6
|
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Optional
|
|
7
8
|
|
|
8
9
|
import structlog
|
|
9
10
|
from dotenv import load_dotenv
|
|
10
11
|
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from haystack_enterprise_sdk._api.oauth import OAuthAuth
|
|
14
|
+
|
|
11
15
|
logger = structlog.get_logger(__name__)
|
|
12
16
|
|
|
13
17
|
ENV_FILE_PATH = Path.home() / ".haystack-enterprise" / ".env"
|
|
14
18
|
|
|
19
|
+
# Tokens from `haystack-enterprise login` via OAuth, used when no API key is configured.
|
|
20
|
+
CREDENTIALS_PATH = ENV_FILE_PATH.parent / "credentials.json"
|
|
21
|
+
|
|
22
|
+
# Written by `deepset-cloud login` in deepset-cloud-sdk 1.x; still read so existing logins keep working.
|
|
23
|
+
LEGACY_ENV_FILE_PATH = Path.home() / ".deepset-cloud" / ".env"
|
|
24
|
+
|
|
15
25
|
# The deepset platform base URL (without a version suffix).
|
|
16
26
|
PLATFORM_URL = "https://api.cloud.deepset.ai"
|
|
17
27
|
|
|
@@ -37,12 +47,30 @@ def normalize_base_url(url: str) -> str:
|
|
|
37
47
|
return url.rstrip("/")
|
|
38
48
|
|
|
39
49
|
|
|
50
|
+
def _write_private_file(path: Path, text: str) -> None:
|
|
51
|
+
"""Write a file atomically, readable by the current user only.
|
|
52
|
+
|
|
53
|
+
The file is created with mode 600 instead of being tightened after the write, so secrets in it are never
|
|
54
|
+
readable by other users, not even briefly.
|
|
55
|
+
|
|
56
|
+
:param path: The file to write. Its parent directory is created if needed.
|
|
57
|
+
:param text: The file contents.
|
|
58
|
+
"""
|
|
59
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
tmp_path = path.with_name(f"{path.name}.tmp")
|
|
61
|
+
fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
62
|
+
with os.fdopen(fd, "w", encoding="utf-8") as file:
|
|
63
|
+
file.write(text)
|
|
64
|
+
os.replace(tmp_path, path)
|
|
65
|
+
|
|
66
|
+
|
|
40
67
|
def load_environment(show_warnings: bool = True) -> bool:
|
|
41
68
|
"""Load environment variables using a cascading fallback model.
|
|
42
69
|
|
|
43
70
|
1. Load local .env file in current directory if it exists
|
|
44
71
|
2. Load from global ~/.haystack-enterprise/.env to supplement local .env file
|
|
45
|
-
3.
|
|
72
|
+
3. Load from legacy ~/.deepset-cloud/.env to supplement both
|
|
73
|
+
4. Environment variables can override all .env files
|
|
46
74
|
|
|
47
75
|
:param show_warnings: Whether to show warnings about missing files/variables
|
|
48
76
|
:return: True if required environment variables were loaded successfully, False otherwise.
|
|
@@ -50,6 +78,7 @@ def load_environment(show_warnings: bool = True) -> bool:
|
|
|
50
78
|
current_path_env = Path.cwd() / ".env"
|
|
51
79
|
local_loaded = current_path_env.is_file() and load_dotenv(current_path_env)
|
|
52
80
|
global_loaded = ENV_FILE_PATH.is_file() and load_dotenv(ENV_FILE_PATH, override=False)
|
|
81
|
+
legacy_loaded = LEGACY_ENV_FILE_PATH.is_file() and load_dotenv(LEGACY_ENV_FILE_PATH, override=False)
|
|
53
82
|
|
|
54
83
|
# These success messages are gated on ``show_warnings`` so the import-time call
|
|
55
84
|
# (``show_warnings=False``) stays silent, before structlog is even configured.
|
|
@@ -61,8 +90,13 @@ def load_environment(show_warnings: bool = True) -> bool:
|
|
|
61
90
|
logger.info(f"Loaded global .env file at {ENV_FILE_PATH} to supplement local .env file.")
|
|
62
91
|
else:
|
|
63
92
|
logger.info(f"Environment variables successfully loaded from global .env file at {ENV_FILE_PATH}.")
|
|
93
|
+
if legacy_loaded:
|
|
94
|
+
logger.info(
|
|
95
|
+
f"Using legacy configuration at {LEGACY_ENV_FILE_PATH}. "
|
|
96
|
+
f"Run `haystack-enterprise login` to move to {ENV_FILE_PATH}."
|
|
97
|
+
)
|
|
64
98
|
|
|
65
|
-
if not (local_loaded or global_loaded) and show_warnings:
|
|
99
|
+
if not (local_loaded or global_loaded or legacy_loaded) and show_warnings:
|
|
66
100
|
logger.warning(
|
|
67
101
|
"No .env files found. Run `haystack-enterprise login` to create a global configuration file. "
|
|
68
102
|
"You can also create a custom local .env file in your project directory."
|
|
@@ -70,7 +104,9 @@ def load_environment(show_warnings: bool = True) -> bool:
|
|
|
70
104
|
return False
|
|
71
105
|
|
|
72
106
|
# Check for required environment variables
|
|
73
|
-
required_vars = ["
|
|
107
|
+
required_vars = ["API_URL", "DEFAULT_WORKSPACE_NAME"]
|
|
108
|
+
if not CREDENTIALS_PATH.is_file():
|
|
109
|
+
required_vars.insert(0, "API_KEY")
|
|
74
110
|
missing_vars = [var for var in required_vars if not os.getenv(var)]
|
|
75
111
|
|
|
76
112
|
if missing_vars and show_warnings:
|
|
@@ -109,12 +145,15 @@ class CommonConfig:
|
|
|
109
145
|
2. Environment variables
|
|
110
146
|
3. Local .env file in project root
|
|
111
147
|
4. Global .env file in ~/.haystack-enterprise/ (supplements local .env)
|
|
112
|
-
5.
|
|
148
|
+
5. Legacy .env file in ~/.deepset-cloud/ (supplements both)
|
|
149
|
+
6. Built-in defaults
|
|
113
150
|
"""
|
|
114
151
|
|
|
115
152
|
api_key: str = ""
|
|
116
153
|
api_url: str = ""
|
|
117
154
|
safe_mode: bool = False
|
|
155
|
+
# Set from stored OAuth credentials when no API key is configured.
|
|
156
|
+
oauth: Optional["OAuthAuth"] = field(default=None, repr=False)
|
|
118
157
|
|
|
119
158
|
def __post_init__(self) -> None:
|
|
120
159
|
"""Validate config."""
|
|
@@ -126,10 +165,17 @@ class CommonConfig:
|
|
|
126
165
|
if not self.api_url:
|
|
127
166
|
self.api_url = os.getenv("API_URL", PLATFORM_URL)
|
|
128
167
|
|
|
129
|
-
if not self.api_key:
|
|
130
|
-
raise ValueError(
|
|
131
|
-
"API key is required. Either set the API_KEY environment variable or pass api_key parameter. Go to [API Keys](https://cloud.deepset.ai/settings/api-keys) in Haystack Enterprise Platform to get an API key."
|
|
132
|
-
)
|
|
133
|
-
|
|
134
168
|
# Normalize to a bare base URL; the version suffix is appended when building requests.
|
|
135
169
|
self.api_url = normalize_base_url(self.api_url)
|
|
170
|
+
|
|
171
|
+
if not self.api_key and self.oauth is None:
|
|
172
|
+
from haystack_enterprise_sdk._api.oauth import OAuthAuth, OAuthCredentials # noqa: PLC0415 - import cycle
|
|
173
|
+
|
|
174
|
+
credentials = OAuthCredentials.load(self.api_url)
|
|
175
|
+
if credentials is not None:
|
|
176
|
+
self.oauth = OAuthAuth(credentials)
|
|
177
|
+
|
|
178
|
+
if not self.api_key and self.oauth is None:
|
|
179
|
+
raise ValueError(
|
|
180
|
+
"API key is required. Run `haystack-enterprise login`, set the API_KEY environment variable, or pass the api_key parameter. Go to [API Keys](https://cloud.deepset.ai/settings/api-keys) in Haystack Enterprise Platform to get an API key."
|
|
181
|
+
)
|
|
@@ -75,8 +75,11 @@ def _decode_jwt_expiry(token: str) -> Optional[datetime]:
|
|
|
75
75
|
def _unauthorized_message(api_key: str) -> str:
|
|
76
76
|
"""Build a friendly 401 message, naming an expired API key explicitly when the token says so.
|
|
77
77
|
|
|
78
|
-
:param api_key: The API key sent as the bearer token on the failing request.
|
|
78
|
+
:param api_key: The API key sent as the bearer token on the failing request. Empty when the request
|
|
79
|
+
was authenticated with an OAuth login instead.
|
|
79
80
|
"""
|
|
81
|
+
if not api_key:
|
|
82
|
+
return "Authentication failed. Your login session expired or was revoked. Run `haystack-enterprise login`."
|
|
80
83
|
expiry = _decode_jwt_expiry(api_key)
|
|
81
84
|
if expiry is None:
|
|
82
85
|
return "Authentication failed. Your API key may be missing, invalid, or expired."
|
|
@@ -174,6 +177,11 @@ def chat_completions_base_url(api_url: str, workspace_name: str) -> str:
|
|
|
174
177
|
return f"{api_url}/{API_VERSION_PATH}/workspaces/{workspace_name}/deployments/v1"
|
|
175
178
|
|
|
176
179
|
|
|
180
|
+
def _client_auth(config: CommonConfig) -> Optional[httpx.Auth]:
|
|
181
|
+
""":return: The OAuth auth flow when the config has no API key, otherwise None (the key is sent as a header)."""
|
|
182
|
+
return None if config.api_key else config.oauth
|
|
183
|
+
|
|
184
|
+
|
|
177
185
|
class HaystackEnterpriseAPI:
|
|
178
186
|
"""Haystack Enterprise Platform API client.
|
|
179
187
|
|
|
@@ -192,9 +200,11 @@ class HaystackEnterpriseAPI:
|
|
|
192
200
|
self.api_key = config.api_key
|
|
193
201
|
self.headers = {
|
|
194
202
|
"Accept": "application/json",
|
|
195
|
-
"Authorization": f"Bearer {config.api_key}",
|
|
196
203
|
"X-Client-Source": "haystack-enterprise-sdk",
|
|
197
204
|
}
|
|
205
|
+
# With OAuth, the client's auth flow sets the (refreshing) bearer token instead.
|
|
206
|
+
if config.api_key:
|
|
207
|
+
self.headers["Authorization"] = f"Bearer {config.api_key}"
|
|
198
208
|
self.base_url = lambda workspace_name: self._get_base_url(config.api_url)(workspace_name)
|
|
199
209
|
self.client = client
|
|
200
210
|
self.max_attempts = SAFE_MODE_MAX_ATTEMPTS if config.safe_mode else DEFAULT_MAX_ATTEMPTS
|
|
@@ -226,10 +236,12 @@ class HaystackEnterpriseAPI:
|
|
|
226
236
|
if config.safe_mode:
|
|
227
237
|
safe_mode_limits = httpx.Limits(max_keepalive_connections=1, max_connections=1)
|
|
228
238
|
safe_mode_timeout = httpx.Timeout(None)
|
|
229
|
-
async with httpx.AsyncClient(
|
|
239
|
+
async with httpx.AsyncClient(
|
|
240
|
+
limits=safe_mode_limits, timeout=safe_mode_timeout, auth=_client_auth(config)
|
|
241
|
+
) as client:
|
|
230
242
|
yield cls(config, client)
|
|
231
243
|
else:
|
|
232
|
-
async with httpx.AsyncClient() as client:
|
|
244
|
+
async with httpx.AsyncClient(auth=_client_auth(config)) as client:
|
|
233
245
|
yield cls(config, client)
|
|
234
246
|
|
|
235
247
|
async def get(
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"""OAuth 2.0 login for the CLI: authorization code with PKCE over a loopback redirect (RFC 8252), or the device flow.
|
|
2
|
+
|
|
3
|
+
The platform advertises its CLI OAuth client at ``/api/v1/sso/cli-config``. Tokens are stored in
|
|
4
|
+
``~/.haystack-enterprise/credentials.json`` (mode 600) and refreshed transparently by :class:`OAuthAuth`.
|
|
5
|
+
An API key, when configured, always wins over these credentials.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import base64
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import secrets
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import asdict, dataclass
|
|
17
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
18
|
+
from typing import Any, AsyncGenerator, Callable, Dict, Optional
|
|
19
|
+
from urllib.parse import parse_qs, urlencode, urlsplit
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from haystack_enterprise_sdk._api.config import API_VERSION_PATH, CREDENTIALS_PATH, _write_private_file
|
|
24
|
+
|
|
25
|
+
# Refresh this many seconds before the access token expires, so a request never goes out with a dying token.
|
|
26
|
+
EXPIRY_SKEW_SECONDS = 60
|
|
27
|
+
|
|
28
|
+
LOGIN_SUCCESS_PAGE = (
|
|
29
|
+
b"<!doctype html><title>Logged in</title>"
|
|
30
|
+
b"<p>You're logged in to Haystack Enterprise Platform. You can close this tab and return to your terminal.</p>"
|
|
31
|
+
)
|
|
32
|
+
LOGIN_FAILURE_PAGE = b"<!doctype html><title>Login failed</title><p>Login failed. Check your terminal.</p>"
|
|
33
|
+
|
|
34
|
+
DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class OAuthError(Exception):
|
|
38
|
+
"""The OAuth login or token refresh failed."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class CliOAuthConfig:
|
|
43
|
+
"""The platform's CLI OAuth client, as advertised at ``/api/v1/sso/cli-config``."""
|
|
44
|
+
|
|
45
|
+
issuer: str
|
|
46
|
+
client_id: str
|
|
47
|
+
scopes: list[str]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class OAuthCredentials:
|
|
52
|
+
"""Tokens from a CLI login, plus what's needed to refresh them without asking the platform again."""
|
|
53
|
+
|
|
54
|
+
api_url: str
|
|
55
|
+
client_id: str
|
|
56
|
+
token_endpoint: str
|
|
57
|
+
access_token: str
|
|
58
|
+
refresh_token: str
|
|
59
|
+
expires_at: float
|
|
60
|
+
revocation_endpoint: Optional[str] = None
|
|
61
|
+
organization_id: Optional[str] = None
|
|
62
|
+
|
|
63
|
+
def expires_soon(self) -> bool:
|
|
64
|
+
""":return: True if the access token expires within the refresh skew."""
|
|
65
|
+
return time.time() >= self.expires_at - EXPIRY_SKEW_SECONDS
|
|
66
|
+
|
|
67
|
+
def save(self) -> None:
|
|
68
|
+
"""Write the credentials atomically, readable by the current user only."""
|
|
69
|
+
_write_private_file(CREDENTIALS_PATH, json.dumps(asdict(self)))
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def load(cls, api_url: Optional[str] = None) -> Optional[OAuthCredentials]:
|
|
73
|
+
"""Read stored credentials.
|
|
74
|
+
|
|
75
|
+
:param api_url: Only return credentials issued for this API URL.
|
|
76
|
+
:return: The credentials, or None if there are none (for this API URL).
|
|
77
|
+
"""
|
|
78
|
+
try:
|
|
79
|
+
credentials = cls(**json.loads(CREDENTIALS_PATH.read_text(encoding="utf-8")))
|
|
80
|
+
except (OSError, ValueError, TypeError):
|
|
81
|
+
return None
|
|
82
|
+
if api_url is not None and credentials.api_url != api_url:
|
|
83
|
+
return None
|
|
84
|
+
return credentials
|
|
85
|
+
|
|
86
|
+
def with_token_response(self, token: Dict[str, Any]) -> OAuthCredentials:
|
|
87
|
+
""":return: A copy updated from a token endpoint response. Keeps the old refresh token if none is rotated in."""
|
|
88
|
+
return OAuthCredentials(
|
|
89
|
+
**{
|
|
90
|
+
**asdict(self),
|
|
91
|
+
"access_token": token["access_token"],
|
|
92
|
+
"refresh_token": token.get("refresh_token") or self.refresh_token,
|
|
93
|
+
"expires_at": time.time() + float(token.get("expires_in", 300)),
|
|
94
|
+
}
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def delete_credentials() -> bool:
|
|
99
|
+
""":return: True if stored credentials were removed."""
|
|
100
|
+
try:
|
|
101
|
+
CREDENTIALS_PATH.unlink()
|
|
102
|
+
except FileNotFoundError:
|
|
103
|
+
return False
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def fetch_cli_config(api_url: str) -> Optional[CliOAuthConfig]:
|
|
108
|
+
"""Ask the platform whether it offers OAuth login for the CLI.
|
|
109
|
+
|
|
110
|
+
:param api_url: The normalized base API URL.
|
|
111
|
+
:return: The CLI client config, or None if this platform doesn't offer it (yet).
|
|
112
|
+
"""
|
|
113
|
+
try:
|
|
114
|
+
response = httpx.get(f"{api_url}/{API_VERSION_PATH}/sso/cli-config", timeout=10)
|
|
115
|
+
except httpx.HTTPError:
|
|
116
|
+
return None
|
|
117
|
+
if response.status_code != httpx.codes.OK:
|
|
118
|
+
return None
|
|
119
|
+
body = response.json()
|
|
120
|
+
if not body.get("issuer") or not body.get("client_id"):
|
|
121
|
+
return None
|
|
122
|
+
return CliOAuthConfig(issuer=body["issuer"], client_id=body["client_id"], scopes=list(body.get("scopes", [])))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def discover(issuer: str) -> Dict[str, Any]:
|
|
126
|
+
""":return: The issuer's OpenID Connect discovery document."""
|
|
127
|
+
response = httpx.get(f"{issuer.rstrip('/')}/.well-known/openid-configuration", timeout=10)
|
|
128
|
+
response.raise_for_status()
|
|
129
|
+
metadata: Dict[str, Any] = response.json()
|
|
130
|
+
return metadata
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def pkce_pair() -> tuple[str, str]:
|
|
134
|
+
""":return: A PKCE code verifier and its S256 challenge."""
|
|
135
|
+
verifier = secrets.token_urlsafe(64)
|
|
136
|
+
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
|
|
137
|
+
return verifier, challenge
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _request_token(token_endpoint: str, data: Dict[str, str]) -> httpx.Response:
|
|
141
|
+
return httpx.post(token_endpoint, data=data, timeout=30)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _token_or_raise(response: httpx.Response) -> Dict[str, Any]:
|
|
145
|
+
body = response.json() if response.content else {}
|
|
146
|
+
if response.status_code != httpx.codes.OK or "access_token" not in body:
|
|
147
|
+
raise OAuthError(body.get("error_description") or body.get("error") or f"HTTP {response.status_code}")
|
|
148
|
+
return body
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _credentials(
|
|
152
|
+
api_url: str, config: CliOAuthConfig, metadata: Dict[str, Any], token: Dict[str, Any]
|
|
153
|
+
) -> OAuthCredentials:
|
|
154
|
+
if not token.get("refresh_token"):
|
|
155
|
+
raise OAuthError("The platform did not issue a refresh token. Is the offline_access scope enabled?")
|
|
156
|
+
return OAuthCredentials(
|
|
157
|
+
api_url=api_url,
|
|
158
|
+
client_id=config.client_id,
|
|
159
|
+
token_endpoint=metadata["token_endpoint"],
|
|
160
|
+
revocation_endpoint=metadata.get("revocation_endpoint"),
|
|
161
|
+
access_token="",
|
|
162
|
+
refresh_token="",
|
|
163
|
+
expires_at=0,
|
|
164
|
+
).with_token_response(token)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def authorization_code_login(
|
|
168
|
+
api_url: str,
|
|
169
|
+
config: CliOAuthConfig,
|
|
170
|
+
open_url: Callable[[str], None],
|
|
171
|
+
timeout: float,
|
|
172
|
+
) -> OAuthCredentials:
|
|
173
|
+
"""Log in through the browser: authorization code + PKCE, redirected to a one-shot loopback server.
|
|
174
|
+
|
|
175
|
+
:param api_url: The normalized base API URL the credentials are for.
|
|
176
|
+
:param config: The platform's CLI OAuth client.
|
|
177
|
+
:param open_url: Shows the authorization URL to the user (opens the browser and prints it).
|
|
178
|
+
:param timeout: Seconds to wait for the redirect.
|
|
179
|
+
:return: The new credentials.
|
|
180
|
+
:raises OAuthError: If the login was denied, timed out, or the code exchange failed.
|
|
181
|
+
"""
|
|
182
|
+
metadata = discover(config.issuer)
|
|
183
|
+
state = secrets.token_urlsafe(32)
|
|
184
|
+
verifier, challenge = pkce_pair()
|
|
185
|
+
received: Dict[str, str] = {}
|
|
186
|
+
|
|
187
|
+
class _RedirectHandler(BaseHTTPRequestHandler):
|
|
188
|
+
def do_GET(self) -> None: # noqa: N802 - name required by BaseHTTPRequestHandler
|
|
189
|
+
parts = urlsplit(self.path)
|
|
190
|
+
params = {key: values[0] for key, values in parse_qs(parts.query).items()}
|
|
191
|
+
if parts.path != "/callback" or not secrets.compare_digest(
|
|
192
|
+
params.get("state", "").encode(), state.encode()
|
|
193
|
+
):
|
|
194
|
+
self.send_error(400, "Invalid login redirect")
|
|
195
|
+
return
|
|
196
|
+
received.update(params)
|
|
197
|
+
self.send_response(200)
|
|
198
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
199
|
+
self.end_headers()
|
|
200
|
+
self.wfile.write(LOGIN_FAILURE_PAGE if "error" in params else LOGIN_SUCCESS_PAGE)
|
|
201
|
+
|
|
202
|
+
def log_message(self, format: str, *args: Any) -> None: # pylint: disable=redefined-builtin
|
|
203
|
+
"""Keep the default request log off the terminal."""
|
|
204
|
+
|
|
205
|
+
with HTTPServer(("127.0.0.1", 0), _RedirectHandler) as server:
|
|
206
|
+
redirect_uri = f"http://127.0.0.1:{server.server_port}/callback"
|
|
207
|
+
query = urlencode(
|
|
208
|
+
{
|
|
209
|
+
"client_id": config.client_id,
|
|
210
|
+
"response_type": "code",
|
|
211
|
+
"redirect_uri": redirect_uri,
|
|
212
|
+
"scope": " ".join(config.scopes),
|
|
213
|
+
"state": state,
|
|
214
|
+
"code_challenge": challenge,
|
|
215
|
+
"code_challenge_method": "S256",
|
|
216
|
+
}
|
|
217
|
+
)
|
|
218
|
+
open_url(f"{metadata['authorization_endpoint']}?{query}")
|
|
219
|
+
|
|
220
|
+
deadline = time.monotonic() + timeout
|
|
221
|
+
while not received:
|
|
222
|
+
remaining = deadline - time.monotonic()
|
|
223
|
+
if remaining <= 0:
|
|
224
|
+
raise OAuthError("Timed out waiting for the browser login.")
|
|
225
|
+
server.timeout = remaining
|
|
226
|
+
server.handle_request()
|
|
227
|
+
|
|
228
|
+
if "error" in received:
|
|
229
|
+
raise OAuthError(received.get("error_description") or received["error"])
|
|
230
|
+
|
|
231
|
+
token = _token_or_raise(
|
|
232
|
+
_request_token(
|
|
233
|
+
metadata["token_endpoint"],
|
|
234
|
+
{
|
|
235
|
+
"grant_type": "authorization_code",
|
|
236
|
+
"code": received["code"],
|
|
237
|
+
"redirect_uri": redirect_uri,
|
|
238
|
+
"client_id": config.client_id,
|
|
239
|
+
"code_verifier": verifier,
|
|
240
|
+
},
|
|
241
|
+
)
|
|
242
|
+
)
|
|
243
|
+
return _credentials(api_url, config, metadata, token)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def device_login(
|
|
247
|
+
api_url: str,
|
|
248
|
+
config: CliOAuthConfig,
|
|
249
|
+
show_code: Callable[[str, str, Optional[str]], None],
|
|
250
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
251
|
+
) -> OAuthCredentials:
|
|
252
|
+
"""Log in without a local browser, using the device authorization grant (RFC 8628).
|
|
253
|
+
|
|
254
|
+
:param api_url: The normalized base API URL the credentials are for.
|
|
255
|
+
:param config: The platform's CLI OAuth client.
|
|
256
|
+
:param show_code: Shows the user code and verification URLs to the user.
|
|
257
|
+
:param sleep: Waits between polls. Replaced in tests.
|
|
258
|
+
:return: The new credentials.
|
|
259
|
+
:raises OAuthError: If the platform doesn't support the device flow, or the login was denied or expired.
|
|
260
|
+
"""
|
|
261
|
+
metadata = discover(config.issuer)
|
|
262
|
+
if "device_authorization_endpoint" not in metadata:
|
|
263
|
+
raise OAuthError("This platform does not support device login. Run `haystack-enterprise login` instead.")
|
|
264
|
+
|
|
265
|
+
response = httpx.post(
|
|
266
|
+
metadata["device_authorization_endpoint"],
|
|
267
|
+
data={"client_id": config.client_id, "scope": " ".join(config.scopes)},
|
|
268
|
+
timeout=30,
|
|
269
|
+
)
|
|
270
|
+
if response.status_code != httpx.codes.OK:
|
|
271
|
+
raise OAuthError(f"Device login could not start (HTTP {response.status_code}).")
|
|
272
|
+
device = response.json()
|
|
273
|
+
show_code(device["user_code"], device["verification_uri"], device.get("verification_uri_complete"))
|
|
274
|
+
|
|
275
|
+
interval = float(device.get("interval", 5))
|
|
276
|
+
deadline = time.monotonic() + float(device.get("expires_in", 600))
|
|
277
|
+
while time.monotonic() < deadline:
|
|
278
|
+
sleep(interval)
|
|
279
|
+
poll = _request_token(
|
|
280
|
+
metadata["token_endpoint"],
|
|
281
|
+
{"grant_type": DEVICE_CODE_GRANT, "device_code": device["device_code"], "client_id": config.client_id},
|
|
282
|
+
)
|
|
283
|
+
error = (poll.json() if poll.content else {}).get("error")
|
|
284
|
+
if error == "authorization_pending":
|
|
285
|
+
continue
|
|
286
|
+
if error == "slow_down":
|
|
287
|
+
interval += 5
|
|
288
|
+
continue
|
|
289
|
+
return _credentials(api_url, config, metadata, _token_or_raise(poll))
|
|
290
|
+
raise OAuthError("The device code expired before the login was approved.")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def revoke(credentials: OAuthCredentials) -> None:
|
|
294
|
+
"""Revoke the refresh token at the platform, best effort: logout must work offline too."""
|
|
295
|
+
if not credentials.revocation_endpoint:
|
|
296
|
+
return
|
|
297
|
+
try:
|
|
298
|
+
httpx.post(
|
|
299
|
+
credentials.revocation_endpoint,
|
|
300
|
+
data={
|
|
301
|
+
"token": credentials.refresh_token,
|
|
302
|
+
"token_type_hint": "refresh_token",
|
|
303
|
+
"client_id": credentials.client_id,
|
|
304
|
+
},
|
|
305
|
+
timeout=10,
|
|
306
|
+
)
|
|
307
|
+
except httpx.HTTPError:
|
|
308
|
+
pass
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class OAuthAuth(httpx.Auth):
|
|
312
|
+
"""Sends the stored access token and refreshes it before it expires, or once after a 401."""
|
|
313
|
+
|
|
314
|
+
def __init__(self, credentials: OAuthCredentials, transport: Optional[httpx.AsyncBaseTransport] = None) -> None:
|
|
315
|
+
""":param transport: Transport for token refreshes. Replaced in tests."""
|
|
316
|
+
self.credentials = credentials
|
|
317
|
+
self._transport = transport
|
|
318
|
+
self._lock = asyncio.Lock()
|
|
319
|
+
self._lock_loop: Optional[asyncio.AbstractEventLoop] = None
|
|
320
|
+
|
|
321
|
+
def _loop_lock(self) -> asyncio.Lock:
|
|
322
|
+
""":return: The refresh lock for the running event loop.
|
|
323
|
+
|
|
324
|
+
An asyncio.Lock binds to the first loop it makes a request wait on, but the sync clients share one auth across
|
|
325
|
+
calls and run each call on a new loop, so each loop gets its own lock.
|
|
326
|
+
"""
|
|
327
|
+
loop = asyncio.get_running_loop()
|
|
328
|
+
if self._lock_loop is not loop:
|
|
329
|
+
self._lock, self._lock_loop = asyncio.Lock(), loop
|
|
330
|
+
return self._lock
|
|
331
|
+
|
|
332
|
+
async def _refresh(self, stale_token: str) -> None:
|
|
333
|
+
async with self._loop_lock():
|
|
334
|
+
if self.credentials.access_token != stale_token:
|
|
335
|
+
return # another request refreshed while we waited
|
|
336
|
+
# Another process (a second CLI run) may have refreshed already; its refresh token supersedes ours.
|
|
337
|
+
# ponytail: no cross-process lock, add a file lock if concurrent refreshes race on rotated tokens.
|
|
338
|
+
on_disk = OAuthCredentials.load(self.credentials.api_url)
|
|
339
|
+
if on_disk and on_disk.access_token != stale_token and not on_disk.expires_soon():
|
|
340
|
+
self.credentials = on_disk
|
|
341
|
+
return
|
|
342
|
+
refresh_token = on_disk.refresh_token if on_disk else self.credentials.refresh_token
|
|
343
|
+
async with httpx.AsyncClient(timeout=30, transport=self._transport) as client:
|
|
344
|
+
response = await client.post(
|
|
345
|
+
self.credentials.token_endpoint,
|
|
346
|
+
data={
|
|
347
|
+
"grant_type": "refresh_token",
|
|
348
|
+
"refresh_token": refresh_token,
|
|
349
|
+
"client_id": self.credentials.client_id,
|
|
350
|
+
},
|
|
351
|
+
)
|
|
352
|
+
if response.status_code != httpx.codes.OK:
|
|
353
|
+
return # leave the request to fail with 401; the SDK's 401 message says to log in again
|
|
354
|
+
self.credentials = self.credentials.with_token_response(response.json())
|
|
355
|
+
self.credentials.save()
|
|
356
|
+
|
|
357
|
+
async def async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]:
|
|
358
|
+
"""Attach the access token, refreshing first if it is about to expire, and retry once on a 401."""
|
|
359
|
+
if self.credentials.expires_soon():
|
|
360
|
+
await self._refresh(self.credentials.access_token)
|
|
361
|
+
sent_token = self.credentials.access_token
|
|
362
|
+
request.headers["Authorization"] = f"Bearer {sent_token}"
|
|
363
|
+
if self.credentials.organization_id:
|
|
364
|
+
request.headers["X-Organization-ID"] = self.credentials.organization_id
|
|
365
|
+
response = yield request
|
|
366
|
+
|
|
367
|
+
if response.status_code == httpx.codes.UNAUTHORIZED:
|
|
368
|
+
await self._refresh(sent_token)
|
|
369
|
+
if self.credentials.access_token != sent_token:
|
|
370
|
+
await response.aclose()
|
|
371
|
+
request.headers["Authorization"] = f"Bearer {self.credentials.access_token}"
|
|
372
|
+
yield request
|
|
@@ -97,7 +97,7 @@ class S3:
|
|
|
97
97
|
|
|
98
98
|
try:
|
|
99
99
|
# pyrate-limiter 3.x
|
|
100
|
-
self.limiter = Limiter(rate_limit, raise_when_fail=False, max_delay=Duration.SECOND * 1)
|
|
100
|
+
self.limiter = Limiter(rate_limit, raise_when_fail=False, max_delay=Duration.SECOND * 1) # type: ignore[call-arg,unused-ignore]
|
|
101
101
|
self._try_acquire_kwargs: Dict[str, Any] = {}
|
|
102
102
|
except TypeError:
|
|
103
103
|
# pyrate-limiter 4.0.0+ removed raise_when_fail and max_delay
|