Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement public HTTP client policy and validation in FastAPI and router
myhloli36c6ee6fad16
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.pyindex b0c26563..da8e01ac 100644--- a/mineru/cli/fast_api.py+++ b/mineru/cli/fast_api.py@@ -84,6 +84,13 @@ FILE_PARSE_TASK_ID_HEADER = "X-MinerU-Task-Id"FILE_PARSE_TASK_STATUS_HEADER = "X-MinerU-Task-Status"FILE_PARSE_TASK_STATUS_URL_HEADER = "X-MinerU-Task-Status-Url"FILE_PARSE_TASK_RESULT_URL_HEADER = "X-MinerU-Task-Result-Url"+MINERU_API_PUBLIC_BIND_EXPOSED_ENV = "MINERU_API_PUBLIC_BIND_EXPOSED"+MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT_ENV = "MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT"+PUBLIC_HTTP_CLIENT_DISABLED_DETAIL = (+ "Publicly exposed API disables *-http-client backends and server_url by "+ "default. Rebind to 127.0.0.1 or start with "+ "--allow-public-http-client if you understand the SSRF risk."+)SWAGGER_UI_FILE_ARRAY_SCHEMA_EXTRA = {# Swagger UI 5 currently fails to render a usable multi-file picker when# FastAPI emits OpenAPI 3.1 byte arrays with contentMediaType.@@ -251,6 +258,14 @@ def create_app():logger.info(f"Request concurrency limited to {max_concurrent_requests}")app.add_middleware(GZipMiddleware, minimum_size=1000)+ app.state.public_bind_exposed = env_flag_enabled(+ MINERU_API_PUBLIC_BIND_EXPOSED_ENV,+ default=False,+ )+ app.state.allow_public_http_client = env_flag_enabled(+ MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT_ENV,+ default=False,+ )default_service_config, default_model_config = split_service_and_model_config({"enable_vlm_preload": env_flag_enabled(@@ -347,6 +362,54 @@ def get_output_root() -> Path:return root.resolve()+def is_public_bind_host(host: str) -> bool:+ return host in {"0.0.0.0", "::"}+++def configure_public_http_client_policy(+ app: FastAPI,+ *,+ public_bind_exposed: bool,+ allow_public_http_client: bool,+) -> None:+ app.state.public_bind_exposed = public_bind_exposed+ app.state.allow_public_http_client = allow_public_http_client+++def validate_public_http_client_request(+ *,+ public_bind_exposed: bool,+ allow_public_http_client: bool,+ backend: str,+ server_url: str | None,+) -> None:+ if not public_bind_exposed or allow_public_http_client:+ return+ if backend.endswith("-http-client") or bool(server_url and server_url.strip()):+ raise HTTPException(status_code=400, detail=PUBLIC_HTTP_CLIENT_DISABLED_DETAIL)+++def warn_if_public_http_client_policy(host: str, allow_public_http_client: bool) -> None:+ if not is_public_bind_host(host):+ return+ if allow_public_http_client:+ logger.warning(+ "MinerU API is listening on {} with --allow-public-http-client enabled. "+ "Requests may supply remote HTTP inference endpoints and turn the service "+ "into an externally driven outbound request primitive, creating SSRF and "+ "internal network probing risk.",+ host,+ )+ return+ logger.warning(+ "MinerU API is listening on {}. Disabling *-http-client backends and "+ "server_url by default because these inputs let callers choose remote HTTP "+ "inference endpoints; when the API is publicly reachable, that creates SSRF "+ "and internal network probing risk.",+ host,+ )++def validate_parse_method(parse_method: str) -> str:if parse_method not in ALLOWED_PARSE_METHODS:raise HTTPException(@@ -736,6 +799,7 @@ def build_sync_file_parse_response(async def parse_request_form(+ request: Request,files: Annotated[list[UploadFile],File(@@ -844,6 +908,16 @@ async def parse_request_form(Form(description="The ending page for PDF parsing, beginning from 0"),] = 99999,) -> ParseRequestOptions:+ validate_public_http_client_request(+ public_bind_exposed=bool(+ getattr(request.app.state, "public_bind_exposed", False)+ ),+ allow_public_http_client=bool(+ getattr(request.app.state, "allow_public_http_client", False)+ ),+ backend=backend,+ server_url=server_url,+ )effective_return_original_file = return_original_file and response_format_zipreturn ParseRequestOptions(files=files,@@ -1510,6 +1584,14 @@ async def health_check():@click.option("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)")@click.option("--port", default=8000, type=int, help="Server port (default: 8000)")@click.option("--reload", is_flag=True, help="Enable auto-reload (development mode)")+ "--allow-public-http-client",+ is_flag=True,+ help=(+ "Allow *-http-client backends and server_url even when binding the API to "+ "0.0.0.0 or ::."+ ),+)@click.option("--enable-vlm-preload","enable_vlm_preload",@@ -1517,17 +1599,36 @@ async def health_check():default=False,help="Preload the local VLM model during mineru-api startup.",)-def main(ctx, host, port, reload, enable_vlm_preload, **kwargs):+def main(+ ctx,+ host,+ port,+ reload,+ allow_public_http_client,+ enable_vlm_preload,+ **kwargs,+):del kwargsraw_config = arg_parse(ctx)raw_config["enable_vlm_preload"] = enable_vlm_preloadservice_config, model_config = split_service_and_model_config(raw_config)+ public_bind_exposed = is_public_bind_host(host)app.state.service_config = service_configapp.state.config = model_config+ configure_public_http_client_policy(+ app,+ public_bind_exposed=public_bind_exposed,+ allow_public_http_client=allow_public_http_client,+ )os.environ["MINERU_API_ENABLE_VLM_PRELOAD"] = ("1" if service_config["enable_vlm_preload"] else "0")+ os.environ[MINERU_API_PUBLIC_BIND_EXPOSED_ENV] = "1" if public_bind_exposed else "0"+ os.environ[MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT_ENV] = (+ "1" if allow_public_http_client else "0"+ )+ warn_if_public_http_client_policy(host, allow_public_http_client)access_log = not env_flag_enabled("MINERU_API_DISABLE_ACCESS_LOG")print(f"Start MinerU FastAPI Service: http://{host}:{port}")diff --git a/mineru/cli/router.py b/mineru/cli/router.pyindex 0813c50a..5be8c07d 100644--- a/mineru/cli/router.py+++ b/mineru/cli/router.py@@ -64,6 +64,13 @@ HTTP_RETRYABLE_STATUS_CODES = {500, 502, 503, 504}UPSTREAM_FAILURE_THRESHOLD = 3WORKER_REFRESH_INTERVAL_SECONDS = 2.0MIN_HEALTHY_PROCESSING_WINDOW_SIZE = 1+MINERU_ROUTER_PUBLIC_BIND_EXPOSED_ENV = "MINERU_ROUTER_PUBLIC_BIND_EXPOSED"+MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT_ENV = "MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT"+PUBLIC_HTTP_CLIENT_DISABLED_DETAIL = (+ "Publicly exposed API disables *-http-client backends and server_url by "+ "default. Rebind to 127.0.0.1 or start with "+ "--allow-public-http-client if you understand the SSRF risk."+)def utc_now_iso() -> str:@@ -120,6 +127,54 @@ def is_task_terminal(status: str) -> bool:return status in TASK_TERMINAL_STATES+def is_public_bind_host(host: str) -> bool:+ return host in {"0.0.0.0", "::"}+++def configure_public_http_client_policy(+ app: FastAPI,+ *,+ public_bind_exposed: bool,+ allow_public_http_client: bool,+) -> None:+ app.state.public_bind_exposed = public_bind_exposed+ app.state.allow_public_http_client = allow_public_http_client+++def validate_public_http_client_request(+ *,+ public_bind_exposed: bool,+ allow_public_http_client: bool,+ backend: str,+ server_url: str | None,+) -> None:+ if not public_bind_exposed or allow_public_http_client:+ return+ if backend.endswith("-http-client") or bool(server_url and server_url.strip()):+ raise HTTPException(status_code=400, detail=PUBLIC_HTTP_CLIENT_DISABLED_DETAIL)+++def warn_if_public_http_client_policy(host: str, allow_public_http_client: bool) -> None:+ if not is_public_bind_host(host):+ return+ if allow_public_http_client:+ logger.warning(+ "MinerU router is listening on {} with --allow-public-http-client enabled. "+ "Requests may supply remote HTTP inference endpoints and turn the service "+ "into an externally driven outbound request primitive, creating SSRF and "+ "internal network probing risk.",+ host,+ )+ return+ logger.warning(+ "MinerU router is listening on {}. Disabling *-http-client backends and "+ "server_url by default because these inputs let callers choose remote HTTP "+ "inference endpoints; when the API is publicly reachable, that creates SSRF "+ "and internal network probing risk.",+ host,+ )++def cleanup_path(path: str) -> None:try:if os.path.isfile(path):@@ -1056,6 +1111,16 @@ async def submit_router_task(request: Request,payload: MultipartPayload,) -> RouterTaskRecord:+ validate_public_http_client_request(+ public_bind_exposed=bool(+ getattr(request.app.state, "public_bind_exposed", False)+ ),+ allow_public_http_client=bool(+ getattr(request.app.state, "allow_public_http_client", False)+ ),+ backend=payload.get_field_value("backend") or "",+ server_url=payload.get_field_value("server_url"),+ )worker_pool: WorkerPool = request.app.state.worker_poolregistry: RouterTaskRegistry = request.app.state.router_task_registryattempted_servers: set[str] = set()@@ -1305,6 +1370,17 @@ def create_app(settings: RouterSettings | None = None) -> FastAPI:lifespan=lifespan,)app.state.router_settings = resolved_settings+ configure_public_http_client_policy(+ app,+ public_bind_exposed=env_flag_enabled(+ MINERU_ROUTER_PUBLIC_BIND_EXPOSED_ENV,+ default=False,+ ),+ allow_public_http_client=env_flag_enabled(+ MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT_ENV,+ default=False,+ ),+ )app.add_middleware(GZipMiddleware, minimum_size=1000)@app.post(path="/tasks", status_code=202)@@ -1394,6 +1470,14 @@ app = create_app()@click.option("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)")@click.option("--port", default=8002, type=int, help="Server port (default: 8002)")@click.option("--reload", is_flag=True, help="Enable auto-reload (development mode)")+ "--allow-public-http-client",+ is_flag=True,+ help=(+ "Allow *-http-client backends and server_url even when binding the router "+ "to 0.0.0.0 or ::."+ ),+)@click.option("--upstream-url","upstream_urls",@@ -1422,6 +1506,7 @@ def main(host: str,port: int,reload: bool,+ allow_public_http_client: bool,upstream_urls: tuple[str, ...],local_gpus: str,worker_host: str,@@ -1436,7 +1521,13 @@ def main(task_retention_seconds=get_task_retention_seconds(),task_cleanup_interval_seconds=get_task_cleanup_interval_seconds(),)+ public_bind_exposed = is_public_bind_host(host)warn_if_router_preload_ignored(settings)+ configure_public_http_client_policy(+ app,+ public_bind_exposed=public_bind_exposed,+ allow_public_http_client=allow_public_http_client,+ )os.environ["MINERU_ROUTER_UPSTREAM_URLS_JSON"] = json.dumps(list(settings.upstream_urls))os.environ["MINERU_ROUTER_LOCAL_GPUS"] = settings.local_gpusos.environ["MINERU_ROUTER_WORKER_HOST"] = settings.worker_host@@ -1444,6 +1535,13 @@ def main("1" if settings.enable_vlm_preload else "0")os.environ["MINERU_ROUTER_WORKER_ARGS_JSON"] = json.dumps(list(settings.worker_extra_args))+ os.environ[MINERU_ROUTER_PUBLIC_BIND_EXPOSED_ENV] = (+ "1" if public_bind_exposed else "0"+ )+ os.environ[MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT_ENV] = (+ "1" if allow_public_http_client else "0"+ )+ warn_if_public_http_client_policy(host, allow_public_http_client)access_log = not env_flag_enabled("MINERU_API_DISABLE_ACCESS_LOG")print(f"Start MinerU Router Service: http://{host}:{port}")