dut-vault-sdk 0.1.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,6 @@
1
+ """dut-vault-sdk: Centralized Vault In-Memory Configuration SDK."""
2
+
3
+ from dut_vault_sdk.client import VaultClient
4
+ from dut_vault_sdk.store import InMemoryConfigStore
5
+
6
+ __all__ = ["InMemoryConfigStore", "VaultClient"]
@@ -0,0 +1,79 @@
1
+ import argparse
2
+ import os
3
+ import subprocess
4
+ import sys
5
+
6
+ from dut_vault_sdk.client import VaultClient
7
+
8
+
9
+ def main() -> None:
10
+ parser = argparse.ArgumentParser(
11
+ prog="dut-vault",
12
+ description="Centralized Vault CLI Runner - Zero disk artifacts, in-memory secret injection",
13
+ )
14
+ subparsers = parser.add_subparsers(dest="subcommand", required=True)
15
+
16
+ run_parser = subparsers.add_parser(
17
+ "run", help="Run a command with secrets injected into RAM"
18
+ )
19
+ run_parser.add_argument("--project", "-p", required=True, help="Target project ID")
20
+ run_parser.add_argument(
21
+ "--scope", "-s", default=None, help="Secret scope to load (default: all)"
22
+ )
23
+ run_parser.add_argument(
24
+ "--role", "-r", default="user", help="Client user role header"
25
+ )
26
+ run_parser.add_argument(
27
+ "--api-url",
28
+ default=os.environ.get("DUT_VAULT_URL", "http://localhost:8000"),
29
+ help="Central Control Plane API URL",
30
+ )
31
+ run_parser.add_argument(
32
+ "--no-watch",
33
+ action="store_true",
34
+ help="Disable background SSE live-reload listener",
35
+ )
36
+ run_parser.add_argument(
37
+ "command",
38
+ nargs=argparse.REMAINDER,
39
+ help="Command to execute (after '--')",
40
+ )
41
+
42
+ args = parser.parse_args()
43
+
44
+ cmd = args.command
45
+ if cmd and cmd[0] == "--":
46
+ cmd = cmd[1:]
47
+
48
+ if not cmd:
49
+ print(
50
+ "Error: No command specified to run. Usage: dut-vault run --project <ID> -- <CMD>",
51
+ file=sys.stderr,
52
+ )
53
+ sys.exit(1)
54
+
55
+ client = VaultClient(
56
+ base_url=args.api_url,
57
+ project_id=args.project,
58
+ user_role=args.role,
59
+ scope=args.scope,
60
+ inject_environ=True,
61
+ auto_reconnect=not args.no_watch,
62
+ )
63
+
64
+ if args.no_watch:
65
+ client.fetch_secrets()
66
+ else:
67
+ client.connect(wait_for_stream=False)
68
+
69
+ try:
70
+ proc = subprocess.run(cmd, check=False, env=os.environ)
71
+ sys.exit(proc.returncode)
72
+ except KeyboardInterrupt:
73
+ sys.exit(130)
74
+ finally:
75
+ client.disconnect()
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
@@ -0,0 +1,299 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import threading
5
+ import time
6
+ from collections.abc import Callable
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from dut_vault_sdk.store import InMemoryConfigStore
13
+
14
+ logger = logging.getLogger("dut_vault_sdk")
15
+
16
+
17
+ def resolve_mtls_cert(
18
+ cert_path: str | None = None, key_path: str | None = None
19
+ ) -> tuple[str, str] | None:
20
+ """Resolve (client.crt, client.key) from explicit args, env vars, or ~/.dut-vault/."""
21
+ crt = cert_path or os.environ.get("SSL_CERT_FILE")
22
+ key = key_path or os.environ.get("SSL_KEY_FILE")
23
+ if crt and key:
24
+ return (crt, key)
25
+
26
+ default_dir = Path.home() / ".dut-vault"
27
+ default_crt = default_dir / "client.crt"
28
+ default_key = default_dir / "client.key"
29
+ if default_crt.is_file() and default_key.is_file():
30
+ return (str(default_crt), str(default_key))
31
+ return None
32
+
33
+
34
+ class VaultClient:
35
+ """In-memory client for dynamic configuration fetching and real-time hot-reloading."""
36
+
37
+ def __init__(
38
+ self,
39
+ base_url: str = "http://localhost:8000",
40
+ project_id: str = "default",
41
+ user_role: str = "user",
42
+ identity_id: str | None = None,
43
+ scope: str | None = None,
44
+ inject_environ: bool = True,
45
+ auto_reconnect: bool = True,
46
+ max_events: int | None = None,
47
+ virtual_key: str | None = None,
48
+ cert_path: str | None = None,
49
+ key_path: str | None = None,
50
+ http_client: httpx.Client | httpx.AsyncClient | None = None,
51
+ stream_http_client: httpx.AsyncClient | None = None,
52
+ ) -> None:
53
+ self.base_url = base_url.rstrip("/")
54
+ self.project_id = project_id
55
+ self.user_role = user_role
56
+ self.identity_id = identity_id
57
+ self.scope = scope
58
+ self.auto_reconnect = auto_reconnect
59
+ self.max_events = max_events
60
+ self.virtual_key = virtual_key or os.environ.get("X_VIRTUAL_KEY")
61
+ self._cert = resolve_mtls_cert(cert_path, key_path)
62
+ self.store = InMemoryConfigStore(inject_environ=inject_environ)
63
+
64
+ default_headers: dict[str, str] = {}
65
+ if self.virtual_key:
66
+ default_headers["X-Virtual-Key"] = self.virtual_key
67
+
68
+ self._custom_http = http_client
69
+ if isinstance(http_client, httpx.AsyncClient):
70
+ self._async_http = http_client
71
+ self._sync_http = None
72
+ elif isinstance(http_client, httpx.Client):
73
+ self._sync_http = http_client
74
+ self._async_http = None
75
+ else:
76
+ client_kwargs: dict[str, Any] = {
77
+ "timeout": 10.0,
78
+ "headers": default_headers,
79
+ }
80
+ if self._cert is not None:
81
+ client_kwargs["cert"] = self._cert
82
+ self._sync_http = httpx.Client(**client_kwargs)
83
+ self._async_http = httpx.AsyncClient(**client_kwargs)
84
+
85
+ if stream_http_client is not None:
86
+ self._stream_http = stream_http_client
87
+ else:
88
+ stream_kwargs: dict[str, Any] = {
89
+ "timeout": 60.0,
90
+ "headers": default_headers,
91
+ }
92
+ if self._cert is not None:
93
+ stream_kwargs["cert"] = self._cert
94
+ self._stream_http = httpx.AsyncClient(**stream_kwargs)
95
+
96
+ self._stop_event = threading.Event()
97
+ self._connected_event = threading.Event()
98
+ self._stream_thread: threading.Thread | None = None
99
+ self._stream_task: asyncio.Task[Any] | None = None
100
+
101
+ def fetch_secrets(self) -> dict[str, str]:
102
+ """Synchronously fetch latest authorized decrypted secrets into process RAM."""
103
+ url = f"{self.base_url}/api/v1/vault/projects/{self.project_id}/secrets"
104
+ params: dict[str, str] = {}
105
+ if self.scope:
106
+ params["scope"] = self.scope
107
+
108
+ headers = {
109
+ "x-identity-id": self.identity_id or self.user_role,
110
+ "x-user-role": self.user_role,
111
+ }
112
+
113
+ if self._sync_http is not None:
114
+ response = self._sync_http.get(url, params=params, headers=headers)
115
+ response.raise_for_status()
116
+ data = response.json()
117
+ else:
118
+ # Fallback if only async client is provided
119
+ data = asyncio.run(self.fetch_secrets_async())
120
+ return data
121
+
122
+ scopes = data.get("scopes", {})
123
+ all_secrets: dict[str, str] = {}
124
+ for kv_pairs in scopes.values():
125
+ all_secrets.update(kv_pairs)
126
+
127
+ self.store.update_bulk(all_secrets)
128
+ return all_secrets
129
+
130
+ async def fetch_secrets_async(self) -> dict[str, str]:
131
+ """Asynchronously fetch latest authorized decrypted secrets into process RAM."""
132
+ url = f"{self.base_url}/api/v1/vault/projects/{self.project_id}/secrets"
133
+ params: dict[str, str] = {}
134
+ if self.scope:
135
+ params["scope"] = self.scope
136
+
137
+ headers = {
138
+ "x-identity-id": self.identity_id or self.user_role,
139
+ "x-user-role": self.user_role,
140
+ }
141
+ client = self._async_http or httpx.AsyncClient(timeout=10.0)
142
+ try:
143
+ response = await client.get(url, params=params, headers=headers)
144
+ response.raise_for_status()
145
+ data = response.json()
146
+ finally:
147
+ if client is not self._async_http:
148
+ await client.aclose()
149
+
150
+ scopes = data.get("scopes", {})
151
+ all_secrets: dict[str, str] = {}
152
+ for kv_pairs in scopes.values():
153
+ all_secrets.update(kv_pairs)
154
+
155
+ self.store.update_bulk(all_secrets)
156
+ return all_secrets
157
+
158
+ async def _async_stream_worker(self) -> None:
159
+ """Asynchronous worker listening to SSE event stream."""
160
+ stream_url = f"{self.base_url}/api/v1/vault/projects/{self.project_id}/stream"
161
+ params: dict[str, str] = {}
162
+ if self.scope:
163
+ params["scope"] = self.scope
164
+ if self.max_events is not None:
165
+ params["max_events"] = str(self.max_events)
166
+
167
+ headers = {
168
+ "Accept": "text/event-stream",
169
+ "x-identity-id": self.identity_id or self.user_role,
170
+ "x-user-role": self.user_role,
171
+ }
172
+
173
+ client = self._stream_http
174
+
175
+ while not self._stop_event.is_set():
176
+ try:
177
+ async with client.stream(
178
+ "GET", stream_url, params=params, headers=headers, timeout=60.0
179
+ ) as resp:
180
+ resp.raise_for_status()
181
+ current_event_type = "message"
182
+
183
+ async for line in resp.aiter_lines():
184
+ if self._stop_event.is_set():
185
+ break
186
+ if not line:
187
+ continue
188
+
189
+ if line.startswith("event:"):
190
+ current_event_type = line[len("event:") :].strip()
191
+ elif line.startswith("data:"):
192
+ if current_event_type == "connected":
193
+ self._connected_event.set()
194
+ elif current_event_type == "secret_update":
195
+ try:
196
+ await self.fetch_secrets_async()
197
+ except Exception as err:
198
+ logger.warning(
199
+ "Failed to refresh secrets after SSE event: %s",
200
+ err,
201
+ )
202
+ current_event_type = "message"
203
+ except asyncio.CancelledError:
204
+ break
205
+ except Exception as e:
206
+ if self._stop_event.is_set():
207
+ break
208
+ logger.debug("SSE stream connection lost: %s. Retrying...", e)
209
+ await asyncio.sleep(1.0 if self.auto_reconnect else 0.1)
210
+ if not self.auto_reconnect:
211
+ break
212
+
213
+ def _sync_stream_worker(self) -> None:
214
+ """Thread worker running async stream worker inside an independent event loop."""
215
+ loop = asyncio.new_event_loop()
216
+ asyncio.set_event_loop(loop)
217
+ try:
218
+ loop.run_until_complete(self._async_stream_worker())
219
+ finally:
220
+ loop.close()
221
+
222
+ def connect(self, wait_for_stream: bool = False, timeout: float = 3.0) -> None:
223
+ """Synchronously fetch initial secrets into RAM and start background stream thread."""
224
+ self.fetch_secrets()
225
+ self._stop_event.clear()
226
+ self._connected_event.clear()
227
+ self._stream_thread = threading.Thread(
228
+ target=self._sync_stream_worker,
229
+ name=f"vault-stream-{self.project_id}",
230
+ daemon=True,
231
+ )
232
+ self._stream_thread.start()
233
+ if wait_for_stream:
234
+ self._connected_event.wait(timeout=timeout)
235
+
236
+ async def connect_async(
237
+ self, wait_for_stream: bool = False, timeout: float = 3.0
238
+ ) -> None:
239
+ """Asynchronously fetch initial secrets into RAM and start streaming task."""
240
+ await self.fetch_secrets_async()
241
+ self._stop_event.clear()
242
+ self._connected_event.clear()
243
+ self._stream_task = asyncio.create_task(self._async_stream_worker())
244
+ if wait_for_stream:
245
+ start = time.time()
246
+ while not self._connected_event.is_set() and time.time() - start < timeout:
247
+ await asyncio.sleep(0.05)
248
+
249
+ def disconnect(self) -> None:
250
+ """Stop background streaming thread."""
251
+ self._stop_event.set()
252
+ if self._stream_thread and self._stream_thread.is_alive():
253
+ self._stream_thread.join(timeout=2.0)
254
+
255
+ async def disconnect_async(self) -> None:
256
+ """Stop background streaming task."""
257
+ self._stop_event.set()
258
+ if self._stream_task and not self._stream_task.done():
259
+ self._stream_task.cancel()
260
+ try:
261
+ await self._stream_task
262
+ except asyncio.CancelledError:
263
+ pass
264
+
265
+ def get(self, key: str, default: str | None = None) -> str | None:
266
+ return self.store.get(key, default)
267
+
268
+ def get_all(self) -> dict[str, str]:
269
+ return self.store.get_all()
270
+
271
+ def on_change(
272
+ self, key: str, callback: Callable[[str, str | None, str], Any]
273
+ ) -> None:
274
+ self.store.on_change(key, callback)
275
+
276
+ def _build_gateway_kwargs(
277
+ self, service_slug: str | None = None, timeout: float = 30.0
278
+ ) -> dict[str, Any]:
279
+ headers: dict[str, str] = {}
280
+ if self.virtual_key:
281
+ headers["X-Virtual-Key"] = self.virtual_key
282
+ kwargs: dict[str, Any] = {"timeout": timeout, "headers": headers}
283
+ if service_slug:
284
+ kwargs["base_url"] = f"{self.base_url}/services/{service_slug}"
285
+ if self._cert is not None:
286
+ kwargs["cert"] = self._cert
287
+ return kwargs
288
+
289
+ def gateway_client(
290
+ self, service_slug: str | None = None, timeout: float = 30.0
291
+ ) -> httpx.Client:
292
+ """Create a pre-configured sync httpx.Client with mTLS cert and X-Virtual-Key."""
293
+ return httpx.Client(**self._build_gateway_kwargs(service_slug, timeout))
294
+
295
+ def async_gateway_client(
296
+ self, service_slug: str | None = None, timeout: float = 30.0
297
+ ) -> httpx.AsyncClient:
298
+ """Create a pre-configured async httpx.AsyncClient with mTLS cert and X-Virtual-Key."""
299
+ return httpx.AsyncClient(**self._build_gateway_kwargs(service_slug, timeout))
dut_vault_sdk/store.py ADDED
@@ -0,0 +1,91 @@
1
+ import logging
2
+ import os
3
+ import threading
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
+ logger = logging.getLogger("dut_vault_sdk.store")
8
+
9
+
10
+ class InMemoryConfigStore:
11
+ """Thread-safe in-memory configuration store residing strictly in RAM."""
12
+
13
+ def __init__(self, inject_environ: bool = True) -> None:
14
+ self._data: dict[str, str] = {}
15
+ self._lock = threading.RLock()
16
+ self._version: int = 0
17
+ self._inject_environ = inject_environ
18
+ self._listeners: dict[str, list[Callable[[str, str | None, str], Any]]] = {}
19
+
20
+ @property
21
+ def version(self) -> int:
22
+ with self._lock:
23
+ return self._version
24
+
25
+ def get(self, key: str, default: str | None = None) -> str | None:
26
+ """Thread-safe retrieval of configuration key from RAM."""
27
+ with self._lock:
28
+ return self._data.get(key, default)
29
+
30
+ def get_all(self) -> dict[str, str]:
31
+ """Return a thread-safe snapshot copy of all configuration keys in RAM."""
32
+ with self._lock:
33
+ return dict(self._data)
34
+
35
+ def on_change(
36
+ self, key: str, callback: Callable[[str, str | None, str], Any]
37
+ ) -> None:
38
+ """Register a callback hook invoked when a key is modified."""
39
+ with self._lock:
40
+ if key not in self._listeners:
41
+ self._listeners[key] = []
42
+ self._listeners[key].append(callback)
43
+
44
+ def update_bulk(
45
+ self, updates: dict[str, str], version: int | None = None
46
+ ) -> list[str]:
47
+ """
48
+ Atomically update multiple keys in memory and optionally synchronize os.environ.
49
+ Executes registered on_change callbacks for all changed values.
50
+ """
51
+ changed_keys: list[str] = []
52
+ callbacks_to_invoke: list[
53
+ tuple[Callable[[str, str | None, str], Any], str, str | None, str]
54
+ ] = []
55
+
56
+ with self._lock:
57
+ for k, new_v in updates.items():
58
+ old_v = self._data.get(k)
59
+ if old_v != new_v:
60
+ self._data[k] = new_v
61
+ if self._inject_environ:
62
+ os.environ[k] = new_v
63
+ changed_keys.append(k)
64
+
65
+ # Gather specific key callbacks
66
+ for cb in self._listeners.get(k, []):
67
+ callbacks_to_invoke.append((cb, k, old_v, new_v))
68
+ # Gather wildcard callbacks
69
+ for cb in self._listeners.get("*", []):
70
+ callbacks_to_invoke.append((cb, k, old_v, new_v))
71
+
72
+ if version is not None:
73
+ self._version = version
74
+
75
+ # Invoke callbacks
76
+ for cb, k, old_v, new_v in callbacks_to_invoke:
77
+ try:
78
+ cb(k, old_v, new_v)
79
+ except Exception as err:
80
+ logger.warning("Callback error for key %s: %s", k, err)
81
+
82
+ return changed_keys
83
+
84
+ def clear(self) -> None:
85
+ """Clear in-memory store."""
86
+ with self._lock:
87
+ if self._inject_environ:
88
+ for k in self._data:
89
+ os.environ.pop(k, None)
90
+ self._data.clear()
91
+ self._version = 0
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.5
2
+ Name: dut-vault-sdk
3
+ Version: 0.1.0
4
+ Summary: In-memory dynamic configuration SDK, mTLS gateway client, and CLI runner for DUT-AI Vault & Gateway
5
+ License: MIT
6
+ Keywords: configuration,gateway,hot-reload,mtls,secrets,vault
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Security
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: httpx>=0.27.0
18
+ Description-Content-Type: text/markdown
19
+
20
+ # dut-vault-sdk
21
+
22
+ Client SDK and CLI process runner for **DUT-AI Dynamic Vault & Zero-Trust Gateway**:
23
+ - **100% In-Memory RAM storage** (`os.environ`) — zero plaintext `.env` disk artifacts
24
+ - **Auto-discovery mTLS** (`~/.dut-vault/client.crt`, `~/.dut-vault/client.key`) & `X_VIRTUAL_KEY`
25
+ - **Real-Time SSE Hot-Reload** (< 5s latency)
26
+ - **Pre-configured Gateway HTTP client** (`vault.gateway_client("<service_slug>")`)
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ # Using pip
32
+ pip install dut-vault-sdk
33
+
34
+ # Using uv
35
+ uv add dut-vault-sdk
36
+ ```
37
+
38
+ ## Quick Start
39
+
40
+ ### 1. Load Vault Secrets in Python
41
+
42
+ ```python
43
+ import os
44
+ from dut_vault_sdk import VaultClient
45
+
46
+ # Automatically loads ~/.dut-vault/client.crt, client.key & X_VIRTUAL_KEY from env
47
+ vault = VaultClient(
48
+ base_url="https://gateway.dutai.io.vn",
49
+ project_id="<PROJECT_ID>",
50
+ scope="Common",
51
+ inject_environ=True,
52
+ )
53
+
54
+ vault.connect(wait_for_stream=True)
55
+
56
+ openai_key = vault.get("OPENAI_API_KEY", default="")
57
+ db_url = os.getenv("DATABASE_URL")
58
+ ```
59
+
60
+ ### 2. Call Upstream Services via Zero-Trust Gateway
61
+
62
+ ```python
63
+ from dut_vault_sdk import VaultClient
64
+
65
+ vault = VaultClient(base_url="https://gateway.dutai.io.vn")
66
+
67
+ with vault.gateway_client("llm") as client:
68
+ res = client.post("/chat/completions", json={"model": "...", "messages": [...]})
69
+ ```
70
+
71
+ ### 3. CLI Process Runner (Any Language)
72
+
73
+ ```bash
74
+ X_VIRTUAL_KEY=<VIRTUAL_KEY> dut-vault run \
75
+ --project <PROJECT_ID> \
76
+ --api-url https://gateway.dutai.io.vn \
77
+ -- python main.py
78
+ ```
@@ -0,0 +1,8 @@
1
+ dut_vault_sdk/__init__.py,sha256=5FEaP3dZAI9c9WIQ90w5eTDBmB6mN5g38rwNSjCLoYE,216
2
+ dut_vault_sdk/__main__.py,sha256=1efxbsiG5shFddj2AsAxo1iypR8tM6pIGqzW_9a9Yvg,2121
3
+ dut_vault_sdk/client.py,sha256=7tjwIqY6V4aUDiuTgZ4jALbxm3KNkFKR3V4QrvlwPW0,11483
4
+ dut_vault_sdk/store.py,sha256=1JteAUdUOza2iHAUgzWmrbd37Bkq2RVKIwNAroL5uA0,3175
5
+ dut_vault_sdk-0.1.0.dist-info/METADATA,sha256=k-REpdt9O0_Ltyls6b5_7mes4EDScJR2gr6J0rD05Gk,2253
6
+ dut_vault_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ dut_vault_sdk-0.1.0.dist-info/entry_points.txt,sha256=pshYxOTPYIAZcKicqCco1p8QCEehP9xn7lxSdi_Eou4,58
8
+ dut_vault_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dut-vault = dut_vault_sdk.__main__:main