Skip to content
Merged
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: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

# Every job only reads the repository. Without this, the token gets the
# repository's default permissions, which can include write access.
permissions:
contents: read

env:
# Keep every job hermetic: no .env discovery, no credential-dependent paths.
TEXT2SQL_DATA_ROOT: ${{ github.workspace }}/data
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ on:
type: boolean
default: true

# Read-only by default. The two jobs that need more (publish, github-release)
# ask for exactly that at job level.
permissions:
contents: read

jobs:
build:
name: Build and verify
Expand Down
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
vulnerabilities, and `dashboard/dist` is rebuilt, with Vite now
emitting ASCII-only output so KaTeX's U+202A regex bound no longer reads as a
Trojan Source bidi character.
- **Second round of Dependabot alerts.** New floors: `certifi>=2026.10.18`
(drops the compromised emSign roots), `pyasn1>=0.6.5`, and in the extras
`authlib>=1.9.1` and `joserfc>=1.7.6` (dashboard), `litellm>=1.100.4`, and
`soupsieve>=4.0` and `tornado>=6.6.1` (notebook). The soupsieve floor only
applies on Python 3.11.5 and later, because no fixed soupsieve supports older
3.11 releases. For the same reason `uv.lock` now covers Python 3.11.5+ only
(`[tool.uv] environments`); the package still installs on any 3.11. In the
dashboard, typescript-eslint's `minimatch` is overridden to 11.x.
- **File paths built from request values stay in their folder.** Benchmark
ids, judge config names, SQLite `db_id`s and logo file names now go through
one helper, `safe_paths.safe_join`, which refuses anything that is not a
plain name. Before this, a `db_id` such as `../../x` could open any
`x.sqlite` on the host, and a benchmark id sent in a request body could
point the index at a file outside `data/results`. Judge configs also keep
their symlink check: a config file that links outside its folder is refused,
and the config list skips it instead of failing.
- **`llm_judge_config_path` only accepts judge configs.** The playground and
the evaluation job used to load any YAML path a full-tier caller sent. They
now accept only a config from the two judge config folders, by the path the
config list shows or by name, and answer 400 for anything else.
- **The DB2 `LIMIT` rewrite no longer slows down on long whitespace.** The old
pattern rescanned runs of spaces from every position, which took about a
second on a query with 20,000 spaces. Output is unchanged.
- **Workflows run with a read-only token.** `ci.yml` and `release.yml` now set
`permissions: contents: read`; the publish and release jobs keep their own
narrower grants.

### Fixed

Expand Down
18 changes: 13 additions & 5 deletions dashboard/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@
"overrides": {
"mermaid": {
"katex": "$katex"
},
"@typescript-eslint/typescript-estree": {
"minimatch": "^11.0.1"
}
}
}
23 changes: 20 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@ dependencies = [
# These are floors, not pins: a newer version always wins. Remove an entry
# once the package that pulls it in has raised its own floor past this one.
"anyio>=4.14.2", # via httpx, openai, google-genai; TLS host-name spoofing
"certifi>=2026.10.18", # via requests, httpx; drops the compromised emSign roots
"cryptography>=50.0.0", # via google-auth; encrypts stored provider keys
"idna>=3.15", # via requests, httpx
"pillow>=13.0.0", # via matplotlib
"pyasn1>=0.6.4", # via pyasn1-modules <- google-auth
"pyasn1>=0.6.5", # via pyasn1-modules <- google-auth
"urllib3>=2.8.0", # via requests, ibm-watsonx-ai
]

Expand All @@ -68,7 +69,7 @@ dependencies = [
# boto3, and narrows the openai pin, which is a lot to impose on everyone who
# installs the library when the built-in prefixes already reach six providers.
litellm = [
"litellm>=1.50",
"litellm>=1.100.4",
]
# Building the documentation site. Not needed to use the toolkit.
docs = [
Expand Down Expand Up @@ -105,6 +106,12 @@ notebook = [
"jupyter-server>=2.21.0",
"jupyterlab>=4.6.4",
"notebook>=7.6.3",
# Further down the same stack: beautifulsoup4 (via nbconvert) and the
# Jupyter server and kernel accept versions without ReDoS and open-redirect
# fixes. Every fixed soupsieve needs Python 3.11.5+, so older 3.11 releases
# keep what beautifulsoup4 picks; see [tool.uv] below.
"soupsieve>=4.0; python_full_version >= '3.11.5'",
"tornado>=6.6.1",
]
dashboard = [
# Floored at the first FastAPI that accepts Starlette 1.x: the 0.x Starlette
Expand All @@ -116,7 +123,9 @@ dashboard = [
"starlette>=1.3.1",
"uvicorn[standard]>=0.30.0",
# Google OIDC sign-in for shared deployments; unused in local (full) mode.
"authlib>=1.3",
# 1.9.1 fixes JWS/JWT signature forgery; joserfc comes in through it.
"authlib>=1.9.1",
"joserfc>=1.7.6",
"itsdangerous>=2.1",
# MySQL async driver (Beaver benchmark); execution_tools uses mysql+aiomysql://
"pymysql>=1.1.1",
Expand Down Expand Up @@ -148,6 +157,13 @@ Repository = "https://github.com/IBM/text2sql-eval-toolkit"
Changelog = "https://github.com/IBM/text2sql-eval-toolkit/blob/main/CHANGELOG.md"
Issues = "https://github.com/IBM/text2sql-eval-toolkit/issues"

[tool.uv]
# The lockfile covers Python 3.11.5 and later. Below that no patched soupsieve
# exists (it comes in with the notebook extra), and resolving for those versions
# put a 2018 beautifulsoup4 and an unpatched soupsieve in the lock. The
# package itself still installs on any 3.11.
environments = ["python_full_version >= '3.11.5'"]

[tool.setuptools]
package-dir = { "" = "src" }

Expand Down Expand Up @@ -229,6 +245,7 @@ files = [
"src/text2sql_eval_toolkit/utils.py",
"src/text2sql_eval_toolkit/env_loader.py",
"src/text2sql_eval_toolkit/config_args.py",
"src/text2sql_eval_toolkit/safe_paths.py",
]
ignore_missing_imports = true
warn_unused_configs = true
Expand Down
10 changes: 6 additions & 4 deletions src/text2sql_eval_toolkit/execution/execution_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1008,7 +1008,10 @@ async def _run_sqlite_and_store(
return query_count


_LIMIT_RE = re.compile(r"(?is)\s+LIMIT\s+(\d+)\s*$")
# Starts at the word LIMIT rather than at the whitespace before it. A leading
# \s+ made search() rescan a long run of spaces from every position in it,
# which is quadratic on a query padded with whitespace.
_LIMIT_RE = re.compile(r"(?i)(?<=\s)LIMIT\s+(\d+)$")


def _parse_db2_dsn(dsn: str) -> dict:
Expand All @@ -1022,11 +1025,10 @@ def _parse_db2_dsn(dsn: str) -> dict:


def _normalize_sql_for_db2(sql: str) -> str:
s = (sql or "").rstrip().rstrip(";")
s = (sql or "").rstrip().rstrip(";").rstrip()
m = _LIMIT_RE.search(s)
if m:
n = m.group(1)
s = _LIMIT_RE.sub(f" FETCH FIRST {n} ROWS ONLY", s)
s = f"{s[: m.start()].rstrip()} FETCH FIRST {m.group(1)} ROWS ONLY"
return s


Expand Down
8 changes: 7 additions & 1 deletion src/text2sql_eval_toolkit/indexing/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Sequence, Tuple

from text2sql_eval_toolkit.indexing.builder import build_index, index_path_for, is_stale
from text2sql_eval_toolkit.safe_paths import safe_join

# Comparison operators the dashboard exposes, mapped to SQL.
OPERATORS: Dict[str, str] = {
Expand Down Expand Up @@ -140,7 +141,12 @@ def _reap_exited_threads(self) -> None:
def for_benchmark(
cls, benchmark_id: str, results_dir: Path, auto_build: bool = True
) -> "EvalIndex":
source = Path(results_dir) / f"{benchmark_id}-predictions_eval.json"
try:
source = safe_join(results_dir, f"{benchmark_id}-predictions_eval.json")
except ValueError:
raise FileNotFoundError(
f"Not a valid benchmark id: {benchmark_id!r}"
) from None
if not source.is_file():
raise FileNotFoundError(f"Evaluation artifact not found: {source}")
path = index_path_for(source)
Expand Down
70 changes: 70 additions & 0 deletions src/text2sql_eval_toolkit/safe_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#
# Copyright IBM Corp. 2025 - 2026
# SPDX-License-Identifier: Apache-2.0
#

"""
Building file paths from names that come from outside the program.

Benchmark ids, judge config names and database ids arrive in URLs and request
bodies, and each of them ends up as part of a file name. `safe_join` is the one
place that turns such a name into a path.
"""

from __future__ import annotations

import os
from pathlib import Path
from typing import Union


def safe_join(base: Union[str, os.PathLike], *names: str) -> Path:
"""
Join plain file or folder names onto *base*, refusing to leave it.

Each name must be a single path component: no separators, not empty, and not
``.`` or ``..``. The joined path is then normalized and checked to start
with *base*. The name check already rules out an escape; the prefix check is
kept because it is the form CodeQL recognizes as a path-injection guard.

Symlinks are not resolved, so a data folder that is a symlink to another
disk keeps working.

Args:
base: The folder the result must stay inside.
*names: The names to join, outermost first.

Returns:
Path: The absolute, normalized path.

Raises:
ValueError: If a name is not a plain name, or the result is not
inside *base*.

Example:
```python
>>> safe_join("/data/results", "spider-predictions_eval.json")
PosixPath('/data/results/spider-predictions_eval.json')
>>> safe_join("/data/results", "../secrets.json")
Traceback (most recent call last):
...
ValueError: not a plain name: '../secrets.json'
```
"""
if not names:
raise ValueError("no name given")
for name in names:
if (
not isinstance(name, str)
or name in ("", ".", "..")
or "/" in name
or "\\" in name
or "\0" in name
):
raise ValueError(f"not a plain name: {name!r}")
root = os.path.abspath(base)
full = os.path.abspath(os.path.join(root, *names))
prefix = root if root.endswith(os.sep) else root + os.sep
if not full.startswith(prefix):
raise ValueError(f"not a plain name: {'/'.join(names)!r}")
return Path(full)
10 changes: 9 additions & 1 deletion src/text2sql_eval_toolkit/ui/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from text2sql_eval_toolkit.indexing import is_stale as is_index_stale
from text2sql_eval_toolkit.indexing.store import EvalIndex
from text2sql_eval_toolkit.logging import get_logger
from text2sql_eval_toolkit.safe_paths import safe_join
from text2sql_eval_toolkit.ui.capabilities import Tier
from text2sql_eval_toolkit.ui.paths import _eval_not_found_detail, get_results_dir
from text2sql_eval_toolkit.ui.runtime import get_mode
Expand All @@ -48,7 +49,14 @@ def get_index(benchmark_id: str) -> EvalIndex:
cached and reused; a source file that changed on disk invalidates its index,
so a re-run is picked up without restarting the server.
"""
eval_path = get_results_dir() / f"{benchmark_id}-predictions_eval.json"
try:
eval_path = safe_join(
get_results_dir(), f"{benchmark_id}-predictions_eval.json"
)
except ValueError:
raise HTTPException(
status_code=404, detail=_eval_not_found_detail(benchmark_id)
) from None
if not eval_path.exists():
raise HTTPException(
status_code=404, detail=_eval_not_found_detail(benchmark_id)
Expand Down
8 changes: 5 additions & 3 deletions src/text2sql_eval_toolkit/ui/routers_benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
write_json_atomic,
)
from text2sql_eval_toolkit.logging import get_logger
from text2sql_eval_toolkit.safe_paths import safe_join
from text2sql_eval_toolkit.ui.models import (
CreateBenchmarkRequest,
UpdateBenchmarkRequest,
Expand Down Expand Up @@ -244,13 +245,14 @@ def upload_benchmark_logo(req: BenchmarkLogoUploadRequest):

stored_name = f"{benchmark_id}{ext}"
relative_path = Path("benchmarks") / "logos" / stored_name
abs_path = get_data_root() / relative_path
logo_dir = get_data_root() / "benchmarks" / "logos"
abs_path = safe_join(logo_dir, stored_name)
abs_path.parent.mkdir(parents=True, exist_ok=True)

# Keep only one logo per benchmark regardless of extension.
for existing_ext in ALLOWED_LOGO_EXTENSIONS:
existing = abs_path.parent / f"{benchmark_id}{existing_ext}"
if existing.resolve() == abs_path.resolve():
existing = safe_join(logo_dir, f"{benchmark_id}{existing_ext}")
if existing == abs_path:
continue
if existing.exists():
try:
Expand Down
24 changes: 18 additions & 6 deletions src/text2sql_eval_toolkit/ui/routers_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,14 @@
)

from text2sql_eval_toolkit.ui.indexes import get_index
from text2sql_eval_toolkit.ui.routers_judge import judge_config_path_from_request
from text2sql_eval_toolkit.ui.paths import (
get_data_root,
get_results_dir,
load_json,
)
from text2sql_eval_toolkit.logging import get_logger
from text2sql_eval_toolkit.safe_paths import safe_join
from text2sql_eval_toolkit.ui.dataframes import truncate_dataframe
from text2sql_eval_toolkit.utils import get_gt_sqls, get_question

Expand All @@ -94,17 +96,25 @@ def _resolve_sqlite_db_path(db_folder: str, db_id: str) -> Path:
db_filename = f"{db_id}.sqlite"
folder_path = Path(db_folder)

# db_id can come from the request, so it must stay a plain name: a db_id of
# "../x" would otherwise open x.sqlite anywhere on the host.
def under(base: Path) -> Path:
try:
return safe_join(base, db_id, db_filename)
except ValueError:
raise ValueError(f"Invalid db_id: {db_id!r}") from None

# Support both absolute db_folder and relative layouts.
if folder_path.is_absolute():
candidate = folder_path / db_id / db_filename
candidate = under(folder_path)
if candidate.exists():
return candidate

candidates = [
get_data_root() / folder_path / db_id / db_filename,
get_data_root() / db_id / db_filename,
Path(BENCHMARKS_FILE).parent / folder_path / db_id / db_filename,
Path.cwd() / "data" / folder_path / db_id / db_filename,
under(get_data_root() / folder_path),
under(get_data_root()),
under(Path(BENCHMARKS_FILE).parent / folder_path),
under(Path.cwd() / "data" / folder_path),
]
for candidate in candidates:
if candidate.exists():
Expand Down Expand Up @@ -740,7 +750,9 @@ async def playground_evaluate(
llm_cfg = None
if req.use_llm:
try:
llm_cfg = load_llm_judge_config(req.llm_judge_config_path)
llm_cfg = load_llm_judge_config(
judge_config_path_from_request(req.llm_judge_config_path)
)
except FileNotFoundError as e:
raise HTTPException(status_code=400, detail=str(e)) from e

Expand Down
Loading
Loading