qodalis-cli-server-plugin-data-explorer 1.0.0b24__tar.gz → 1.0.0b25__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.
- {qodalis_cli_server_plugin_data_explorer-1.0.0b24 → qodalis_cli_server_plugin_data_explorer-1.0.0b25}/PKG-INFO +1 -1
- {qodalis_cli_server_plugin_data_explorer-1.0.0b24 → qodalis_cli_server_plugin_data_explorer-1.0.0b25}/pyproject.toml +1 -1
- qodalis_cli_server_plugin_data_explorer-1.0.0b25/qodalis_cli_data_explorer/__init__.py +57 -0
- qodalis_cli_server_plugin_data_explorer-1.0.0b25/qodalis_cli_data_explorer/data_explorer_controller.py +103 -0
- qodalis_cli_server_plugin_data_explorer-1.0.0b25/qodalis_cli_data_explorer/data_explorer_executor.py +199 -0
- qodalis_cli_server_plugin_data_explorer-1.0.0b25/qodalis_cli_data_explorer/data_explorer_policy.py +1007 -0
- {qodalis_cli_server_plugin_data_explorer-1.0.0b24 → qodalis_cli_server_plugin_data_explorer-1.0.0b25}/qodalis_cli_data_explorer/data_explorer_registry.py +29 -5
- qodalis_cli_server_plugin_data_explorer-1.0.0b24/qodalis_cli_data_explorer/__init__.py +0 -11
- qodalis_cli_server_plugin_data_explorer-1.0.0b24/qodalis_cli_data_explorer/data_explorer_controller.py +0 -77
- qodalis_cli_server_plugin_data_explorer-1.0.0b24/qodalis_cli_data_explorer/data_explorer_executor.py +0 -89
- {qodalis_cli_server_plugin_data_explorer-1.0.0b24 → qodalis_cli_server_plugin_data_explorer-1.0.0b25}/.gitignore +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: qodalis-cli-server-plugin-data-explorer
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.0b25
|
|
4
4
|
Summary: Data Explorer plugin for Qodalis CLI servers
|
|
5
5
|
Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
|
|
6
6
|
Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "qodalis-cli-server-plugin-data-explorer"
|
|
7
|
-
version = "1.0.
|
|
7
|
+
version = "1.0.0b25"
|
|
8
8
|
description = "Data Explorer plugin for Qodalis CLI servers"
|
|
9
9
|
readme = { text = "", content-type = "text/plain" }
|
|
10
10
|
license = "MIT"
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Qodalis CLI Data Explorer plugin — registry, executor, and controller."""
|
|
2
|
+
|
|
3
|
+
from .data_explorer_registry import DataExplorerRegistry
|
|
4
|
+
from .data_explorer_executor import (
|
|
5
|
+
AUDIT_QUERY_MAX_LENGTH,
|
|
6
|
+
DataExplorerAuditSink,
|
|
7
|
+
DataExplorerExecutor,
|
|
8
|
+
result_to_dict,
|
|
9
|
+
)
|
|
10
|
+
from .data_explorer_controller import create_data_explorer_router
|
|
11
|
+
from .data_explorer_policy import (
|
|
12
|
+
MASK,
|
|
13
|
+
DataExplorerRateLimiter,
|
|
14
|
+
apply_column_policy,
|
|
15
|
+
can_export,
|
|
16
|
+
can_use_source,
|
|
17
|
+
filter_listing,
|
|
18
|
+
filter_schema,
|
|
19
|
+
glob_to_regex,
|
|
20
|
+
is_object_allowed,
|
|
21
|
+
is_read_only,
|
|
22
|
+
masked_column_error,
|
|
23
|
+
masked_result_error,
|
|
24
|
+
matches_any,
|
|
25
|
+
missing_permissions,
|
|
26
|
+
objects_error,
|
|
27
|
+
query_objects,
|
|
28
|
+
read_only_error,
|
|
29
|
+
sql_objects,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"AUDIT_QUERY_MAX_LENGTH",
|
|
34
|
+
"DataExplorerAuditSink",
|
|
35
|
+
"DataExplorerExecutor",
|
|
36
|
+
"DataExplorerRateLimiter",
|
|
37
|
+
"DataExplorerRegistry",
|
|
38
|
+
"MASK",
|
|
39
|
+
"apply_column_policy",
|
|
40
|
+
"can_export",
|
|
41
|
+
"can_use_source",
|
|
42
|
+
"create_data_explorer_router",
|
|
43
|
+
"filter_listing",
|
|
44
|
+
"filter_schema",
|
|
45
|
+
"glob_to_regex",
|
|
46
|
+
"is_object_allowed",
|
|
47
|
+
"is_read_only",
|
|
48
|
+
"masked_column_error",
|
|
49
|
+
"masked_result_error",
|
|
50
|
+
"matches_any",
|
|
51
|
+
"missing_permissions",
|
|
52
|
+
"objects_error",
|
|
53
|
+
"query_objects",
|
|
54
|
+
"read_only_error",
|
|
55
|
+
"result_to_dict",
|
|
56
|
+
"sql_objects",
|
|
57
|
+
]
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""FastAPI router for the Data Explorer API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict
|
|
6
|
+
from typing import Any, Callable, Optional
|
|
7
|
+
|
|
8
|
+
from fastapi import APIRouter, HTTPException, Request
|
|
9
|
+
from fastapi.responses import JSONResponse
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
from .data_explorer_executor import DataExplorerExecutor, result_to_dict
|
|
13
|
+
from .data_explorer_policy import filter_schema, missing_permissions
|
|
14
|
+
from .data_explorer_registry import DataExplorerRegistry
|
|
15
|
+
|
|
16
|
+
#: Who makes a request (a ``DataExplorerCaller``: permissions, rate limit,
|
|
17
|
+
#: audit); the server supplies it.
|
|
18
|
+
CallerResolver = Callable[[Request], Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _to_camel(snake: str) -> str:
|
|
22
|
+
"""Convert a snake_case string to camelCase."""
|
|
23
|
+
parts = snake.split("_")
|
|
24
|
+
return parts[0] + "".join(w.capitalize() for w in parts[1:])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _camel_keys(obj: Any, *, max_depth: int = 2, _depth: int = 0) -> Any:
|
|
28
|
+
"""Convert dict keys from snake_case to camelCase down to ``max_depth``
|
|
29
|
+
levels of objects, preserving row data as-is."""
|
|
30
|
+
if isinstance(obj, dict):
|
|
31
|
+
result: dict[str, Any] = {}
|
|
32
|
+
for k, v in obj.items():
|
|
33
|
+
new_key = _to_camel(k) if _depth < max_depth else k
|
|
34
|
+
# Don't recurse into "rows" — that's user data
|
|
35
|
+
if new_key == "rows":
|
|
36
|
+
result[new_key] = v
|
|
37
|
+
else:
|
|
38
|
+
result[new_key] = _camel_keys(v, max_depth=max_depth, _depth=_depth + 1)
|
|
39
|
+
return result
|
|
40
|
+
if isinstance(obj, list):
|
|
41
|
+
return [_camel_keys(item, max_depth=max_depth, _depth=_depth) for item in obj]
|
|
42
|
+
return obj
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class DataExplorerExecuteRequest(BaseModel):
|
|
46
|
+
"""Request body for executing a data explorer query."""
|
|
47
|
+
|
|
48
|
+
source: str
|
|
49
|
+
query: str
|
|
50
|
+
parameters: dict[str, Any] | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def create_data_explorer_router(
|
|
54
|
+
registry: DataExplorerRegistry,
|
|
55
|
+
executor: DataExplorerExecutor,
|
|
56
|
+
*,
|
|
57
|
+
caller: Optional[CallerResolver] = None,
|
|
58
|
+
) -> APIRouter:
|
|
59
|
+
"""Create and return a FastAPI router with data-explorer endpoints.
|
|
60
|
+
|
|
61
|
+
- ``GET /sources``: the data sources the caller may use
|
|
62
|
+
- ``GET /schema``: a source's schema (allowed tables, without dropped columns)
|
|
63
|
+
- ``POST /execute``: run a query (403 without the source's permissions,
|
|
64
|
+
429 over its rate limit)
|
|
65
|
+
|
|
66
|
+
``caller`` tells who makes a request (the server supplies it)."""
|
|
67
|
+
router = APIRouter()
|
|
68
|
+
|
|
69
|
+
def caller_of(request: Request) -> Any:
|
|
70
|
+
return caller(request) if caller is not None else None
|
|
71
|
+
|
|
72
|
+
@router.get("/sources")
|
|
73
|
+
async def get_sources(http_request: Request) -> list[dict[str, Any]]:
|
|
74
|
+
return _camel_keys(registry.get_sources(caller_of(http_request)))
|
|
75
|
+
|
|
76
|
+
@router.post("/execute")
|
|
77
|
+
async def execute(request: DataExplorerExecuteRequest, http_request: Request) -> Any:
|
|
78
|
+
result = await executor.execute_async(request.model_dump(), caller_of(http_request))
|
|
79
|
+
code = getattr(result, "error_code", None)
|
|
80
|
+
if code == "forbidden":
|
|
81
|
+
return JSONResponse(status_code=403, content={"error": result.error})
|
|
82
|
+
if code == "rate_limited":
|
|
83
|
+
return JSONResponse(status_code=429, content={"error": result.error})
|
|
84
|
+
return _camel_keys(result_to_dict(result))
|
|
85
|
+
|
|
86
|
+
@router.get("/schema")
|
|
87
|
+
async def get_schema(source: str, http_request: Request) -> Any:
|
|
88
|
+
entry = registry.get(source)
|
|
89
|
+
if entry is None:
|
|
90
|
+
raise HTTPException(status_code=404, detail=f"Unknown data source: '{source}'")
|
|
91
|
+
|
|
92
|
+
provider, options = entry
|
|
93
|
+
missing = missing_permissions(getattr(options, "required_permissions", None), caller_of(http_request))
|
|
94
|
+
if missing:
|
|
95
|
+
return JSONResponse(status_code=403, content={"error": f"forbidden: missing permission {', '.join(missing)}"})
|
|
96
|
+
schema = await provider.get_schema_async(options)
|
|
97
|
+
if schema is None:
|
|
98
|
+
raise HTTPException(status_code=404, detail="Schema introspection is not supported by this data source.")
|
|
99
|
+
|
|
100
|
+
# Three levels: schema → tables → columns (``primaryKey``)
|
|
101
|
+
return _camel_keys(asdict(filter_schema(schema, options)), max_depth=3)
|
|
102
|
+
|
|
103
|
+
return router
|
qodalis_cli_server_plugin_data_explorer-1.0.0b25/qodalis_cli_data_explorer/data_explorer_executor.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Executor that dispatches queries to the correct Data Explorer provider."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import asdict, dataclass
|
|
9
|
+
from typing import Any, Awaitable, Callable, Optional
|
|
10
|
+
|
|
11
|
+
from qodalis_cli_server_abstractions import (
|
|
12
|
+
DataExplorerExecutionContext,
|
|
13
|
+
DataExplorerResult,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from .data_explorer_policy import (
|
|
17
|
+
DataExplorerRateLimiter,
|
|
18
|
+
apply_column_policy,
|
|
19
|
+
filter_listing,
|
|
20
|
+
is_read_only,
|
|
21
|
+
masked_column_error,
|
|
22
|
+
masked_result_error,
|
|
23
|
+
missing_permissions,
|
|
24
|
+
objects_error,
|
|
25
|
+
rate_limit_of,
|
|
26
|
+
read_only_error,
|
|
27
|
+
)
|
|
28
|
+
from .data_explorer_registry import DataExplorerRegistry
|
|
29
|
+
|
|
30
|
+
try: # abstractions with data explorer hardening
|
|
31
|
+
from qodalis_cli_server_abstractions import DataExplorerAuditEntry
|
|
32
|
+
except ImportError: # pragma: no cover - older abstractions package
|
|
33
|
+
@dataclass
|
|
34
|
+
class DataExplorerAuditEntry: # type: ignore[no-redef]
|
|
35
|
+
"""An audit entry the data explorer writes (event ``data_query``)."""
|
|
36
|
+
|
|
37
|
+
event: str
|
|
38
|
+
user_id: str
|
|
39
|
+
user_name: str
|
|
40
|
+
metadata: dict[str, Any]
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger(__name__)
|
|
43
|
+
|
|
44
|
+
#: Writes an audit entry (the server's audit log).
|
|
45
|
+
DataExplorerAuditSink = Callable[[DataExplorerAuditEntry], Awaitable[None]]
|
|
46
|
+
|
|
47
|
+
#: Longest query text kept in an audit entry.
|
|
48
|
+
AUDIT_QUERY_MAX_LENGTH = 2000
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def result_to_dict(result: DataExplorerResult) -> dict[str, Any]:
|
|
52
|
+
"""The result as a snake_case dict; ``error_code`` only when the server
|
|
53
|
+
refused the query (works with older abstractions, whose result has no
|
|
54
|
+
such field)."""
|
|
55
|
+
data = asdict(result)
|
|
56
|
+
code = getattr(result, "error_code", None)
|
|
57
|
+
if code:
|
|
58
|
+
data["error_code"] = code
|
|
59
|
+
else:
|
|
60
|
+
data.pop("error_code", None)
|
|
61
|
+
return data
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class DataExplorerExecutor:
|
|
65
|
+
"""Executes data explorer queries: the source's permissions, rate limit,
|
|
66
|
+
read-only rules, allowed objects and masked columns first, then the provider with a
|
|
67
|
+
timeout, then the row limit, column masking and the audit entry."""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
registry: DataExplorerRegistry,
|
|
72
|
+
*,
|
|
73
|
+
audit: Optional[Callable[[], Optional[DataExplorerAuditSink]]] = None,
|
|
74
|
+
rate_limiter: DataExplorerRateLimiter | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
self._registry = registry
|
|
77
|
+
#: Read on every query, so an audit log mounted later counts.
|
|
78
|
+
self._audit = audit
|
|
79
|
+
self._rate_limiter = rate_limiter or DataExplorerRateLimiter()
|
|
80
|
+
|
|
81
|
+
async def execute_async(self, request: dict[str, Any], caller: Any = None) -> DataExplorerResult:
|
|
82
|
+
"""Execute a query against the named source as ``caller``.
|
|
83
|
+
|
|
84
|
+
``caller`` (a ``DataExplorerCaller``: permissions, rate limit, audit)
|
|
85
|
+
is ``None`` for trusted code. Never raises: errors (and refusals,
|
|
86
|
+
with ``error_code``) are in the result."""
|
|
87
|
+
source = request.get("source", "")
|
|
88
|
+
query = request.get("query", "") or ""
|
|
89
|
+
parameters = request.get("parameters") or {}
|
|
90
|
+
|
|
91
|
+
entry = self._registry.get(source)
|
|
92
|
+
if entry is None:
|
|
93
|
+
return _failure(source, None, f"Unknown data source: {source}", 0, "unknown_source")
|
|
94
|
+
|
|
95
|
+
provider, options = entry
|
|
96
|
+
start = time.monotonic()
|
|
97
|
+
|
|
98
|
+
missing = missing_permissions(getattr(options, "required_permissions", None), caller)
|
|
99
|
+
if missing:
|
|
100
|
+
return await self._refuse(request, options, caller, f"forbidden: missing permission {', '.join(missing)}", "forbidden")
|
|
101
|
+
if not self._rate_limiter.try_acquire(options, caller):
|
|
102
|
+
max_queries, window = rate_limit_of(options) # type: ignore[misc]
|
|
103
|
+
return await self._refuse(
|
|
104
|
+
request, options, caller, f"Too many queries: at most {max_queries} per {window:g} s", "rate_limited",
|
|
105
|
+
)
|
|
106
|
+
if is_read_only(options) and not getattr(provider, "read_only_queries", False):
|
|
107
|
+
error = read_only_error(options.language, query)
|
|
108
|
+
if error:
|
|
109
|
+
return await self._refuse(request, options, caller, error, "read_only")
|
|
110
|
+
objects = objects_error(options, query)
|
|
111
|
+
if objects:
|
|
112
|
+
return await self._refuse(request, options, caller, objects, "object_not_allowed")
|
|
113
|
+
masked = masked_column_error(options, query)
|
|
114
|
+
if masked:
|
|
115
|
+
return await self._refuse(request, options, caller, masked, "masked_column")
|
|
116
|
+
|
|
117
|
+
context = DataExplorerExecutionContext(query=query, parameters=parameters, options=options)
|
|
118
|
+
timeout_s = options.timeout / 1000.0
|
|
119
|
+
try:
|
|
120
|
+
result = await asyncio.wait_for(provider.execute_async(context), timeout=timeout_s)
|
|
121
|
+
except asyncio.TimeoutError:
|
|
122
|
+
result = _failure(source, options, f"Query timed out after {options.timeout}ms", options.timeout)
|
|
123
|
+
except Exception as exc:
|
|
124
|
+
result = _failure(source, options, str(exc), _elapsed_ms(start))
|
|
125
|
+
else:
|
|
126
|
+
if result.row_count > options.max_rows:
|
|
127
|
+
result.rows = result.rows[: options.max_rows]
|
|
128
|
+
result.row_count = options.max_rows
|
|
129
|
+
result.truncated = True
|
|
130
|
+
masked = masked_result_error(options, query, result.columns) if result.success else None
|
|
131
|
+
if masked:
|
|
132
|
+
# A masked column came back under another name: withhold the rows
|
|
133
|
+
result = _failure(source, options, masked, _elapsed_ms(start), "masked_column")
|
|
134
|
+
elif result.success:
|
|
135
|
+
filter_listing(result, options, query)
|
|
136
|
+
apply_column_policy(result, options)
|
|
137
|
+
|
|
138
|
+
await self._write_audit(request, options, caller, result, _elapsed_ms(start))
|
|
139
|
+
return result
|
|
140
|
+
|
|
141
|
+
async def _refuse(self, request: dict[str, Any], options: Any, caller: Any, error: str, code: str) -> DataExplorerResult:
|
|
142
|
+
result = _failure(request.get("source", ""), options, error, 0, code)
|
|
143
|
+
await self._write_audit(request, options, caller, result, 0)
|
|
144
|
+
return result
|
|
145
|
+
|
|
146
|
+
async def _write_audit(self, request: dict[str, Any], options: Any, caller: Any, result: DataExplorerResult, duration_ms: int) -> None:
|
|
147
|
+
"""Writes the ``data_query`` audit entry; a failing audit log does not fail the query."""
|
|
148
|
+
if getattr(options, "audit", True) is False or self._audit is None:
|
|
149
|
+
return
|
|
150
|
+
try:
|
|
151
|
+
sink = self._audit()
|
|
152
|
+
if sink is None:
|
|
153
|
+
return
|
|
154
|
+
query = request.get("query", "") or ""
|
|
155
|
+
if len(query) > AUDIT_QUERY_MAX_LENGTH:
|
|
156
|
+
query = query[:AUDIT_QUERY_MAX_LENGTH] + "…"
|
|
157
|
+
metadata: dict[str, Any] = {
|
|
158
|
+
"source": options.name,
|
|
159
|
+
"query": query,
|
|
160
|
+
"success": result.success,
|
|
161
|
+
"rowCount": result.row_count,
|
|
162
|
+
"durationMs": duration_ms,
|
|
163
|
+
}
|
|
164
|
+
if result.error:
|
|
165
|
+
metadata["error"] = result.error
|
|
166
|
+
remote = getattr(caller, "remote_address", None) if caller is not None else None
|
|
167
|
+
if remote:
|
|
168
|
+
metadata["remoteAddress"] = remote
|
|
169
|
+
await sink(DataExplorerAuditEntry(
|
|
170
|
+
event="data_query",
|
|
171
|
+
user_id=(getattr(caller, "user_id", None) if caller is not None else None) or "",
|
|
172
|
+
user_name=(getattr(caller, "user_name", None) if caller is not None else None) or "anonymous",
|
|
173
|
+
metadata=metadata,
|
|
174
|
+
))
|
|
175
|
+
except Exception:
|
|
176
|
+
logger.exception("Failed to write the data_query audit entry")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _elapsed_ms(start: float) -> int:
|
|
180
|
+
return int((time.monotonic() - start) * 1000)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _failure(source: str, options: Any, error: str, execution_time: int, error_code: str | None = None) -> DataExplorerResult:
|
|
184
|
+
result = DataExplorerResult(
|
|
185
|
+
success=False,
|
|
186
|
+
source=source,
|
|
187
|
+
language=options.language if options is not None else "sql", # type: ignore[arg-type]
|
|
188
|
+
default_output_format=options.default_output_format if options is not None else "table", # type: ignore[arg-type]
|
|
189
|
+
execution_time=execution_time,
|
|
190
|
+
columns=None,
|
|
191
|
+
rows=[],
|
|
192
|
+
row_count=0,
|
|
193
|
+
truncated=False,
|
|
194
|
+
error=error,
|
|
195
|
+
)
|
|
196
|
+
if error_code:
|
|
197
|
+
# Set as an attribute: older abstractions have no such field
|
|
198
|
+
result.error_code = error_code # type: ignore[attr-defined]
|
|
199
|
+
return result
|