Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Validate doclib config values before storing

jinzhenj4bd02f338ef6
diff --git a/mineru/doclib/config_schema.py b/mineru/doclib/config_schema.py
new file mode 100644
index 00000000..b9c5a23b
--- /dev/null
+++ b/mineru/doclib/config_schema.py
@@ -0,0 +1,46 @@
+"""Validation for doclib runtime config keys and values."""
+
+from __future__ import annotations
+
+from urllib.parse import urlparse
+
+from ..errors import InvalidRequestError
+from .config_defaults import CONFIG_DEFAULTS
+
+LOCAL_PARSE_SERVER_MODES = ("disabled", "managed", "self_hosted")
+MANAGED_PARSE_SERVER_TIERS = ("standard", "pro")
+URL_CONFIG_KEYS = ("parse_server.remote.url", "parse_server.local.self_hosted_url")
+
+
+def validate_config_key(key: str) -> None:
+ if key not in CONFIG_DEFAULTS:
+ raise InvalidRequestError("invalid_config_key", f"Unknown config key: {key}", "key")
+
+
+def validate_config_value(key: str, value: str) -> None:
+ validate_config_key(key)
+ if key == "parse_server.local.mode":
+ _validate_enum_value(key, value, LOCAL_PARSE_SERVER_MODES)
+ return
+ if key == "parse_server.local.managed_tier":
+ _validate_enum_value(key, value, MANAGED_PARSE_SERVER_TIERS)
+ return
+ if key in URL_CONFIG_KEYS:
+ allow_empty = key == "parse_server.local.self_hosted_url"
+ _validate_url_value(key, value, allow_empty=allow_empty)
+
+
+def _validate_enum_value(key: str, value: str, allowed: tuple[str, ...]) -> None:
+ if value in allowed:
+ return
+ expected = ", ".join(allowed)
+ raise InvalidRequestError("invalid_config_value", f"{key} must be one of: {expected}.", "value")
+
+
+def _validate_url_value(key: str, value: str, *, allow_empty: bool) -> None:
+ if allow_empty and value == "":
+ return
+ parsed = urlparse(value)
+ if parsed.scheme in ("http", "https") and parsed.hostname:
+ return
+ raise InvalidRequestError("invalid_config_value", f"{key} must be an http or https URL.", "value")
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 22738d7f..4c250304 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+import base64
import os
import re
import signal
@@ -29,6 +30,7 @@ from ..utils.pdf_document import PDFDocument
from ..version import __version__
from .background.parse_server_health import get_health
from .base import AsyncDoclibInterface
+from .config_schema import validate_config_value
from .core.db import DatabaseManager
from .locators import ContentCursor, block_char_ref, block_ref, page_ref, parse_content_cursor
from .rows import (
@@ -839,13 +841,8 @@ class DoclibServer(AsyncDoclibInterface):
return ConfigSetResponse(key=key, value=_mask_config_value(key, value or ""), source=source)
async def _validate_config_set(self, key: str, value: str) -> None:
+ validate_config_value(key, value)
if key == "parse_server.local.mode":
- if value not in ("disabled", "managed", "self_hosted"):
- raise InvalidRequestError(
- "invalid_config_value",
- "parse_server.local.mode must be one of: disabled, managed, self_hosted.",
- key,
- )
if value == "managed":
tier = _validate_managed_parse_server_tier(
(await self.state.config_svc.get("parse_server.local.managed_tier")) or "standard",
diff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.py
index 697a631a..4a9d89e3 100644
--- a/mineru/doclib/services/config_svc.py
+++ b/mineru/doclib/services/config_svc.py
@@ -11,6 +11,7 @@ from typing import cast
from ...errors import InvalidRequestError
from ...types import Tier
from ..config_defaults import CONFIG_DEFAULTS, CONFIG_SOURCE_DEFAULT, CONFIG_SOURCE_OVERRIDE, ConfigSource
+from ..config_schema import validate_config_key, validate_config_value
from ..core.db import DatabaseManager
from ..rows import ConfigRow, RuleRow, WatchTargetRow
from ..types import (
@@ -39,7 +40,7 @@ class ConfigService:
return row["value"] if row else default
async def set(self, key: str, value: str) -> None:
- self._validate_config_key(key)
+ validate_config_value(key, value)
if CONFIG_DEFAULTS[key] == value:
await self.unset(key)
return
@@ -66,15 +67,14 @@ class ConfigService:
overrides = {r["key"]: r["value"] for r in rows}
config = dict(CONFIG_DEFAULTS)
config.update(overrides)
- sources: dict[str, ConfigSource] = {key: CONFIG_SOURCE_DEFAULT for key in CONFIG_DEFAULTS}
+ sources: dict[str, ConfigSource] = dict.fromkeys(CONFIG_DEFAULTS, CONFIG_SOURCE_DEFAULT)
for key in overrides:
if key in CONFIG_DEFAULTS:
sources[key] = CONFIG_SOURCE_OVERRIDE
return config, sources
def _validate_config_key(self, key: str) -> None:
- if key not in CONFIG_DEFAULTS:
- raise InvalidRequestError("invalid_config_key", f"Unknown config key: {key}", "key")
+ validate_config_key(key)
# ── watch targets ───────────────────────────────────────────
diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.py
index d001f549..6ec513be 100644
--- a/tests/unittest/test_doclib_app_startup.py
+++ b/tests/unittest/test_doclib_app_startup.py
@@ -53,6 +53,33 @@ def test_doclib_runtime_dependencies_are_in_base_install() -> None:
assert "watchfiles" in dependency_names
+ ("key", "value"),
+ [
+ ("parse_server.local.mode", "totally-invalid-mode"),
+ ("parse_server.local.managed_tier", "ultra"),
+ ("parse_server.remote.url", "ftp://example.com/api"),
+ ("parse_server.local.self_hosted_url", "not-a-url"),
+ ],
+)
+def test_config_set_rejects_invalid_known_config_values(key: str, value: str, monkeypatch, tmp_path) -> None:
+ def _skip_background_task(*args, **kwargs):
+ return None
+
+ monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)
+
+ cfg = PatchedConfig(doclib={"data_dir": str(tmp_path), "sqlite": {"path": str(tmp_path / "doclib.db")}})
+ with TestClient(doclib_app.create_app(cfg)) as client:
+ response = client.put(f"/api/v1/configs/{key}", json={"value": value})
+ config_response = client.get(f"/api/v1/configs/{key}")
+
+ assert response.status_code == 400
+ payload = response.json()
+ assert payload["error"]["code"] == "invalid_config_value"
+ assert payload["error"]["param"] == "value"
+ assert config_response.json()["source"] == "default"
+
+
def test_config_set_managed_mode_preflights_managed_tier_dependencies(monkeypatch, tmp_path) -> None:
def _skip_background_task(*args, **kwargs):
return None
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 88b952c1..a70bf679 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -732,6 +732,50 @@ def test_config_defaults_are_code_backed_and_unset_removes_override(tmp_path: Pa
asyncio.run(_run())
+def test_config_service_rejects_invalid_known_config_values(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ConfigService(db)
+
+ invalid_values = [
+ ("parse_server.local.mode", "totally-invalid-mode"),
+ ("parse_server.local.managed_tier", "ultra"),
+ ("parse_server.remote.url", "not-a-url"),
+ ("parse_server.remote.url", "ftp://example.com/api"),
+ ("parse_server.local.self_hosted_url", "not-a-url"),
+ ]
+ for key, value in invalid_values:
+ with pytest.raises(InvalidRequestError) as exc_info:
+ await service.set(key, value)
+ assert exc_info.value.code == "invalid_config_value"
+ assert exc_info.value.param == "value"
+
+ assert await service.get("parse_server.local.mode") == CONFIG_DEFAULTS["parse_server.local.mode"]
+ assert await service.get("parse_server.local.managed_tier") == CONFIG_DEFAULTS["parse_server.local.managed_tier"]
+ assert await service.get("parse_server.remote.url") == CONFIG_DEFAULTS["parse_server.remote.url"]
+ assert await service.get("parse_server.local.self_hosted_url") == CONFIG_DEFAULTS["parse_server.local.self_hosted_url"]
+ assert await db.fetchall("SELECT key, value FROM config ORDER BY key") == []
+
+ asyncio.run(_run())
+
+
+def test_config_service_accepts_valid_url_config_values(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ConfigService(db)
+
+ await service.set("parse_server.remote.url", "https://example.com/api")
+ await service.set("parse_server.local.self_hosted_url", "http://127.0.0.1:16580")
+ await service.set("parse_server.local.self_hosted_url", "")
+
+ assert await service.get("parse_server.remote.url") == "https://example.com/api"
+ assert await service.get("parse_server.local.self_hosted_url") == ""
+
+ asyncio.run(_run())
+
+
def test_data_dir_is_not_runtime_kv_config(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))