Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions query_intelligence/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

MIN_RETRIEVAL_TOP_K = 1
MAX_RETRIEVAL_TOP_K = 100
MAX_QUERY_LENGTH = 2000

QuestionStyle = Literal["fact", "why", "compare", "advice", "forecast"]
TimeScope = Literal[
Expand Down Expand Up @@ -134,7 +135,7 @@ class RetrievalResult(BaseModel):


class AnalyzeRequest(BaseModel):
query: str
query: str = Field(min_length=1, max_length=MAX_QUERY_LENGTH)
user_profile: dict[str, Any] = Field(default_factory=dict)
dialog_context: list[dict[str, Any]] = Field(default_factory=list)
debug: bool = False
Expand All @@ -147,7 +148,7 @@ class RetrievalRequest(BaseModel):


class PipelineRequest(BaseModel):
query: str
query: str = Field(min_length=1, max_length=MAX_QUERY_LENGTH)
user_profile: dict[str, Any] = Field(default_factory=dict)
dialog_context: list[dict[str, Any]] = Field(default_factory=list)
top_k: int = Field(default=20, ge=MIN_RETRIEVAL_TOP_K, le=MAX_RETRIEVAL_TOP_K)
Expand Down
20 changes: 19 additions & 1 deletion query_intelligence/external_data/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,31 @@ def _allow_patterns_for_source(source_id: str) -> list[str] | None:
return None


def _safe_zip_extractall(archive: zipfile.ZipFile, extract_dir: Path) -> None:
"""Extract a zip archive while blocking zip-slip path traversal attacks.

zipfile.extractall() does not validate member paths; a malicious archive
could contain entries like ``../../etc/cron.d/evil`` and write files
outside *extract_dir*. This helper resolves every member path and raises
``ValueError`` if the resolved path escapes the target directory.
"""
resolved_root = extract_dir.resolve()
for member in archive.infolist():
target = (extract_dir / member.filename).resolve()
if not target.is_relative_to(resolved_root):
raise ValueError(
f"Blocked unsafe zip member path (zip-slip): {member.filename!r}"
)
archive.extract(member, extract_dir)
Comment on lines +182 to +186

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate all ZIP members before extracting any file

Because extraction happens inside the same loop that performs the path check, an archive containing both safe entries and a later traversal entry will extract the early files and only then raise ValueError. In this failure mode, _extract_zip_files leaves a partially populated extract_dir, and future sync runs skip that archive entirely due the extract_dir.exists() guard, which can silently preserve incomplete/corrupted data. Pre-validating all members (or extracting to a temp dir and committing atomically) avoids this partial-write state.

Useful? React with 👍 / 👎.



def _extract_zip_files(target_dir: Path) -> None:
for path in target_dir.rglob("*.zip"):
extract_dir = path.with_suffix("")
if extract_dir.exists():
continue
with zipfile.ZipFile(path) as archive:
archive.extractall(extract_dir)
_safe_zip_extractall(archive, extract_dir)


def _extract_7z_files(target_dir: Path) -> None:
Expand Down
8 changes: 8 additions & 0 deletions scripts/llm_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,9 @@ def coerce_query(value: Any) -> str:
return query


_MAX_REQUEST_BODY_BYTES = 10 * 1024 * 1024 # 10 MB – prevent OOM via huge Content-Length


def run_service(args: argparse.Namespace) -> None:
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
Expand All @@ -1272,6 +1275,11 @@ def _read_json_body(self) -> dict[str, Any]:
content_length = int(self.headers.get("Content-Length") or "0")
if content_length <= 0:
return {}
if content_length > _MAX_REQUEST_BODY_BYTES:
raise ValueError(
f"Request body too large: {content_length} bytes "
f"(max {_MAX_REQUEST_BODY_BYTES})"
)
raw = self.rfile.read(content_length)
parsed = json.loads(raw.decode("utf-8"))
if not isinstance(parsed, dict):
Expand Down
Loading
Loading