Rembg is a tool to remove images background
Harden the HTTP server and raise vulnerable dependency floors (#866)
Daniel Gatis991927b77667
diff --git a/README.md b/README.mdindex d283535..70d4322 100644--- a/README.md+++ b/README.md@@ -233,6 +233,22 @@ For complete API documentation, visit: `http://localhost:7000/api`rembg s --no-ui```+**Serve cloud models (atlascloud, withoutbg):**++They are off by default, because a request without its own `api_key` is billed to the API key set in the server's environment.++```shell+rembg s --allow-remote-models+```++**Limit how many models stay loaded in memory (default 8):**++```shell+rembg s --max-sessions 4+```++The `extras` parameter only accepts `model_path`, `sam_model`, `sam_quant`, `sam_prompt`, `cc`, `cloth_category`, `vitmatte_model`, `putalpha`, `api_key`, `model`, `timeout` and `poll_timeout`.+**Remove background from an image URL:**```shelldiff --git a/pyproject.toml b/pyproject.tomlindex 1a178c3..24508cb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -28,7 +28,8 @@ packages = [{include = "rembg"}]python = "^3.11"jsonschema = "^4.25.1"numpy = "^2.3.0"-pillow = ">=12.1.0,<14.0.0"+# 13.x fixes many decoder CVEs, but gradio (the cli extra) still caps pillow <13.+pillow = ">=12.3.0,<14.0.0"pooch = "^1.8.2"pymatting = "^1.1.14"scikit-image = "^0.26.0"@@ -49,20 +50,22 @@ onnx = {version = "^1.17.0", optional = true}onnxconverter-common = {version = "^1.14.0", optional = true}# CLI dependencies (optional)-aiohttp = {version = "^3.13.2", optional = true}+aiohttp = {version = "^3.14.4", optional = true}asyncer = {version = "^0.0.12", optional = true}click = {version = "^8.3.1", optional = true}-fastapi = {version = "^0.128.0", optional = true}+fastapi = {version = ">=0.128.0,<1.0.0", optional = true}filetype = {version = "^1.2.0", optional = true}-gradio = {version = "^6.2.0", optional = true}-python-multipart = {version = "^0.0.21", optional = true}+gradio = {version = "^6.16.0", optional = true}+python-multipart = {version = ">=0.0.31,<0.1.0", optional = true}sniffio = {version = "^1.3.1", optional = true}+# Not imported directly, but it parses every request; pinned to a fixed release.+starlette = {version = ">=1.3.1,<2.0.0", optional = true}uvicorn = {version = "^0.40.0", optional = true}watchdog = {version = "^6.0.0", optional = true}# Dev dependencies (optional, for pip install .[dev])bandit = {version = "^1.9.2", optional = true}-black = {version = "^26.3.1", optional = true}+black = {version = "^26.10.1", optional = true}flake8 = {version = "^7.3.0", optional = true}imagehash = {version = "^4.3.2", optional = true}isort = {version = "^7.0.0", optional = true}@@ -71,7 +74,7 @@ pytest = {version = "^9.0.2", optional = true}[tool.poetry.group.dev.dependencies]bandit = "^1.9.2"-black = "^26.3.1"+black = "^26.10.1"flake8 = "^7.3.0"imagehash = "^4.3.2"isort = "^7.0.0"@@ -83,7 +86,7 @@ cpu = ["onnxruntime"]gpu = ["onnxruntime-gpu"]rocm = ["onnxruntime-rocm"]fp16 = ["onnx", "onnxconverter-common"]-cli = ["aiohttp", "asyncer", "click", "fastapi", "filetype", "gradio", "python-multipart", "sniffio", "uvicorn", "watchdog"]+cli = ["aiohttp", "asyncer", "click", "fastapi", "filetype", "gradio", "python-multipart", "sniffio", "starlette", "uvicorn", "watchdog"]dev = ["bandit", "black", "flake8", "imagehash", "isort", "mypy", "pytest"][tool.poetry.scripts]diff --git a/rembg/commands/s_command.py b/rembg/commands/s_command.pyindex caa033d..e8d0c39 100644--- a/rembg/commands/s_command.py+++ b/rembg/commands/s_command.py@@ -1,9 +1,12 @@import ipaddressimport jsonimport os+import reimport socket+import threadingimport webbrowser-from typing import List, Optional, Tuple, Union, cast+from collections import OrderedDict+from typing import Any, Dict, List, Optional, Tuple, Unionfrom urllib.parse import urljoin, urlparseimport aiohttp@@ -12,12 +15,12 @@ import uvicornfrom asyncer import asyncifyfrom fastapi import Depends, FastAPI, File, Form, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddleware-from starlette.responses import Response+from starlette.responses import PlainTextResponse, Responsefrom .. import __version__from ..bg import removefrom ..session_factory import new_session-from ..sessions import sessions_names+from ..sessions import sessions_names, sessions_names_no_credentialsfrom ..sessions.base import BaseSession_PROXY_ENV_VARS = (@@ -91,6 +94,177 @@ def _is_blocked_ip(ip: Union[ipaddress.IPv4Address, ipaddress.IPv6Address]) -> breturn blocked(ip) or blocked(_unwrap_ipv6(ip))+# Extras a remote caller may pass. Anything else (`providers`, `sess_opts`,+# `session`, ...) reaches internals the caller has no business choosing.+# Session extras pick which session is built, so they are part of its cache key;+# predict extras only steer a single call and must not build a new session.+_SESSION_EXTRAS = frozenset(+ {+ "model_path",+ "sam_model",+ "sam_quant",+ "api_key",+ "model",+ "timeout",+ "poll_timeout",+ }+)+_PREDICT_EXTRAS = frozenset(+ {"sam_prompt", "cc", "cloth_category", "vitmatte_model", "putalpha"}+)+++def _parse_extras(raw: Optional[str]) -> Tuple[Dict[str, Any], Dict[str, Any]]:+ """Split the caller's JSON extras into (session kwargs, predict kwargs).++ Raises ValueError on malformed JSON or on a key outside the allowlist.+ """+ if not raw:+ return {}, {}++ try:+ extras = json.loads(raw)+ except json.JSONDecodeError:+ raise ValueError("extras must be valid JSON.")++ if not isinstance(extras, dict):+ raise ValueError("extras must be a JSON object.")++ unknown = set(extras) - _SESSION_EXTRAS - _PREDICT_EXTRAS+ if unknown:+ raise ValueError(+ f"Unsupported extras: {', '.join(sorted(unknown))}. "+ f"Allowed: {', '.join(sorted(_SESSION_EXTRAS | _PREDICT_EXTRAS))}."+ )++ session_kwargs = {k: v for k, v in extras.items() if k in _SESSION_EXTRAS}+ predict_kwargs = {k: v for k, v in extras.items() if k in _PREDICT_EXTRAS}+ return session_kwargs, predict_kwargs+++def _parse_bgcolor(raw: Optional[str]) -> Optional[Tuple[int, int, int, int]]:+ """Parse `r,g,b` or `r,g,b,a` into RGBA, raising ValueError on anything else.++ A missing alpha means opaque, as Pillow does for a 3-tuple RGBA color.+ """+ if not raw:+ return None++ try:+ color = tuple(int(part) for part in raw.split(","))+ except ValueError:+ raise ValueError("bgc must be comma separated integers, e.g. 255,255,255,255.")++ if len(color) not in (3, 4) or not all(0 <= c <= 255 for c in color):+ raise ValueError("bgc must have 3 or 4 values between 0 and 255.")++ r, g, b, *alpha = color+ return (r, g, b, alpha[0] if alpha else 255)+++# Largest image accepted, whether uploaded or fetched from a URL.+_MAX_IMAGE_BYTES = 50 * 1024 * 1024+# Room for the multipart boundaries and the form fields around the file.+_MAX_FORM_OVERHEAD_BYTES = 1024 * 1024+++class _BodyTooLarge(Exception):+ pass+++class _LimitUploadSize:+ """Reject POST bodies to `path` larger than `max_bytes` with a 413.++ The multipart parser reads the whole body before the endpoint runs, so the+ limit has to be enforced while the body streams in. Content-Length is+ checked up front, and the received bytes are counted for chunked bodies+ that do not declare one.+ """++ def __init__(self, app, path: str, max_bytes: int):+ self.app = app+ self.path = path+ self.max_bytes = max_bytes++ async def __call__(self, scope, receive, send):+ if (+ scope["type"] != "http"+ or scope["method"] != "POST"+ or scope["path"] != self.path+ ):+ await self.app(scope, receive, send)+ return++ too_large = PlainTextResponse("Image exceeds maximum size.", status_code=413)++ content_length = dict(scope["headers"]).get(b"content-length", b"")+ if content_length.isdigit() and int(content_length) > self.max_bytes:+ await too_large(scope, receive, send)+ return++ received = 0+ exceeded = False++ async def limited_receive():+ nonlocal received, exceeded+ message = await receive()+ if message["type"] == "http.request":+ received += len(message.get("body", b""))+ if received > self.max_bytes:+ exceeded = True+ raise _BodyTooLarge()+ return message++ # FastAPI turns any error raised while parsing the form into a 400, so+ # the exception never reaches this middleware. Drop whatever response+ # the app produces once the limit is hit and answer 413 instead.+ async def guarded_send(message):+ if not exceeded:+ await send(message)++ try:+ await self.app(scope, limited_receive, guarded_send)+ except _BodyTooLarge:+ pass++ if exceeded:+ await too_large(scope, receive, send)+++class _SessionCache:+ """A bounded LRU of sessions.++ Every distinct set of session extras builds a new model in memory, so an+ unbounded cache lets any caller exhaust RAM by varying them.+ """++ def __init__(self, max_size: int):+ self.max_size = max(1, max_size)+ self._sessions: "OrderedDict[tuple, BaseSession]" = OrderedDict()+ self._lock = threading.Lock()++ def get(self, model: str, session_kwargs: Dict[str, Any]) -> BaseSession:+ key = (model, json.dumps(session_kwargs, sort_keys=True, default=str))++ with self._lock:+ session = self._sessions.get(key)+ if session is not None:+ self._sessions.move_to_end(key)+ return session++ # Built outside the lock: loading a model can take seconds and must not+ # stall requests for sessions that are already cached.+ session = new_session(model, **session_kwargs)++ with self._lock:+ self._sessions[key] = session+ self._sessions.move_to_end(key)+ while len(self._sessions) > self.max_size:+ self._sessions.popitem(last=False)++ return session++@click.command( # type: ignorename="s",help="for a http server",@@ -134,14 +308,44 @@ def _is_blocked_ip(ip: Union[ipaddress.IPv4Address, ipaddress.IPv6Address]) -> bshow_default=True,help="disable the Gradio UI (reduces idle CPU usage)",)-def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -> None:+ "--allow-remote-models",+ is_flag=True,+ default=False,+ show_default=True,+ help="also serve cloud models (e.g. atlascloud, withoutbg); requests without "+ "their own api_key are billed to this server's API key environment variables",+)+ "--max-sessions",+ default=8,+ type=click.IntRange(min=1),+ show_default=True,+ help="maximum number of models kept loaded in memory",+)+def s_command(+ port: int,+ host: str,+ log_level: str,+ threads: int,+ no_ui: bool,+ allow_remote_models: bool,+ max_sessions: int,+) -> None:"""Command-line interface for running the FastAPI web server.This function starts the FastAPI web server with the specified port and log level.If the number of worker threads is specified, it sets the thread limiter accordingly."""- sessions: dict[tuple, BaseSession] = {}+ sessions = _SessionCache(max_sessions)++ # Cloud models fall back to the API key in this server's environment, so+ # serving them by default would let anyone reaching the port spend it.+ model_names = (+ sessions_names if allow_remote_models else sessions_names_no_credentials+ )+ model_regex = r"^(" + "|".join(re.escape(n) for n in model_names) + r")$"tags_metadata = [{"name": "Background Removal",@@ -169,6 +373,12 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -docs_url="/api",)+ app.add_middleware(+ _LimitUploadSize,+ path="/api/remove",+ max_bytes=_MAX_IMAGE_BYTES + _MAX_FORM_OVERHEAD_BYTES,+ )+app.add_middleware(CORSMiddleware,allow_credentials=False,@@ -182,7 +392,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self,model: str = Query(description="Model to use when processing image",- regex=r"(" + "|".join(sessions_names) + ")",+ pattern=model_regex,default="bria-rmbg",),a: bool = Query(default=False, description="Enable Alpha Matting"),@@ -199,7 +409,10 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -description="Alpha Matting (Background Threshold)",),ae: int = Query(- default=10, ge=0, description="Alpha Matting (Erode Structure Size)"+ default=10,+ ge=0,+ le=255,+ description="Alpha Matting (Erode Structure Size)",),om: bool = Query(default=False, description="Only Mask"),ppm: bool = Query(default=False, description="Post Process Mask"),@@ -220,18 +433,17 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self.dc = dcself.vm = vmself.extras = extras- self.bgc = (- cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))- if bgc- else None- )+ try:+ self.bgc = _parse_bgcolor(bgc)+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))class CommonQueryPostParams:def __init__(self,model: str = Form(description="Model to use when processing image",- regex=r"(" + "|".join(sessions_names) + ")",+ pattern=model_regex,default="bria-rmbg",),a: bool = Form(default=False, description="Enable Alpha Matting"),@@ -248,7 +460,10 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -description="Alpha Matting (Background Threshold)",),ae: int = Form(- default=10, ge=0, description="Alpha Matting (Erode Structure Size)"+ default=10,+ ge=0,+ le=255,+ description="Alpha Matting (Erode Structure Size)",),om: bool = Form(default=False, description="Only Mask"),ppm: bool = Form(default=False, description="Post Process Mask"),@@ -269,28 +484,21 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self.dc = dcself.vm = vmself.extras = extras- self.bgc = (- cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))- if bgc- else None- )+ try:+ self.bgc = _parse_bgcolor(bgc)+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))def im_without_bg(content: bytes, commons: CommonQueryParams) -> Response:- kwargs = {}-- if commons.extras:- try:- kwargs.update(json.loads(commons.extras))- except Exception:- pass+ try:+ session_kwargs, predict_kwargs = _parse_extras(commons.extras)+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))- # Extras are part of the key: a session built with one caller's api_key- # or model_path must not be handed to a request that passed another.- cache_key = (commons.model, json.dumps(kwargs, sort_keys=True, default=str))- session = sessions.get(cache_key)- if session is None:- session = new_session(commons.model, **kwargs)- sessions[cache_key] = session+ # Session extras are part of the key: a session built with one caller's+ # api_key or model_path must not be handed to a request that passed another.+ session = sessions.get(commons.model, session_kwargs)+ kwargs = {**session_kwargs, **predict_kwargs}return Response(remove(@@ -383,7 +591,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -except ValueError as e:raise HTTPException(status_code=400, detail=str(e))- max_bytes = 50 * 1024 * 1024+ max_bytes = _MAX_IMAGE_BYTES# Pin every connection to an already-validated IP so aiohttp cannot# re-resolve the hostname to a private address (DNS rebinding).@@ -474,19 +682,18 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -"vitmatte": vm,}- extras = {}- if cmd_args:- extras = json.loads(cmd_args)- kwargs.update(extras)+ # The dropdown is only a hint: Gradio's API accepts any value here.+ if model not in model_names:+ raise gr.Error(f"Unsupported model: {model}")++ try:+ session_kwargs, predict_kwargs = _parse_extras(cmd_args)+ except ValueError as e:+ raise gr.Error(str(e))- # Extras are part of the key: a session built with one api_key or- # model_path must not be reused for a request that passed another.- cache_key = (model, json.dumps(extras, sort_keys=True, default=str))- session = sessions.get(cache_key)- if session is None:- session = new_session(model, **kwargs)- sessions[cache_key] = session- kwargs["session"] = session+ kwargs.update(session_kwargs)+ kwargs.update(predict_kwargs)+ kwargs["session"] = sessions.get(model, session_kwargs)return remove(input_image, **kwargs)@@ -494,9 +701,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -inference,[gr.components.Image(type="pil", label="Input"),- gr.components.Dropdown(- sessions_names, value="bria-rmbg", label="Models"- ),+ gr.components.Dropdown(model_names, value="bria-rmbg", label="Models"),gr.components.Checkbox(value=True, label="Alpha matting"),gr.components.Slider(value=240, minimum=0, maximum=255, label="Foreground threshold"diff --git a/rembg/sessions/atlascloud.py b/rembg/sessions/atlascloud.pyindex 150baff..12071c9 100644--- a/rembg/sessions/atlascloud.py+++ b/rembg/sessions/atlascloud.py@@ -5,6 +5,7 @@ import osimport timefrom typing import List, Optionalfrom urllib import error, request+from urllib.parse import urlparsefrom PIL import Imagefrom PIL.Image import Image as PILImage@@ -185,6 +186,11 @@ class AtlasCloudSession(BaseSession):def _fetch(self, url: str) -> bytes:"""Download a prediction output."""+ # The URL comes from the API response, and urllib would also open+ # file:// and other local schemes, so only accept https.+ if urlparse(url).scheme != "https":+ raise RuntimeError(f"atlascloud returned a non-https output URL: {url}")+req = request.Request(url, headers={"User-Agent": USER_AGENT})try:with request.urlopen(req, timeout=self.timeout) as resp:diff --git a/rembg/sessions/base.py b/rembg/sessions/base.pyindex 806c9cb..56862ed 100644--- a/rembg/sessions/base.py+++ b/rembg/sessions/base.py@@ -215,11 +215,13 @@ class BaseSession:if model_path is None:raise ValueError("model_path is required")- abs_path = os.path.abspath(os.path.expanduser(model_path))+ # realpath, not abspath: a symlink inside the models directory must not+ # be able to point the check at a file outside it.+ abs_path = os.path.realpath(os.path.expanduser(model_path))allowed = [- os.path.abspath(cls.rembg_home(*args, **kwargs)),- os.path.abspath(cls.legacy_home(*args, **kwargs)),+ os.path.realpath(cls.rembg_home(*args, **kwargs)),+ os.path.realpath(cls.legacy_home(*args, **kwargs)),]for root in allowed:diff --git a/tests/test_atlascloud.py b/tests/test_atlascloud.pyindex 9bbb528..9eb03dc 100644--- a/tests/test_atlascloud.py+++ b/tests/test_atlascloud.py@@ -219,3 +219,25 @@ def test_default_model_is_the_served_remove_background_model(monkeypatch):monkeypatch.delenv("ATLASCLOUD_MODEL", raising=False)session = atlascloud.AtlasCloudSession("atlascloud", None, api_key="synthetic-key")assert session.model == "midjourney/v8.2/remove-background"+++ "output_url", ["file:///etc/passwd", "http://cdn/x.png", "ftp://cdn/x.png"]+)+def test_predict_refuses_non_https_output_url(monkeypatch, output_url):+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")+ monkeypatch.setattr("rembg.sessions.atlascloud.POLL_INTERVAL", 0)+ session = AtlasCloudSession("atlascloud", None)++ responses = [+ _json_resp({"data": {"id": "req-1", "status": "processing"}}),+ _json_resp({"data": {"status": "completed", "outputs": [output_url]}}),+ ]++ with patch(+ "rembg.sessions.atlascloud.request.urlopen", side_effect=responses+ ) as mock_urlopen:+ with pytest.raises(RuntimeError, match="non-https"):+ session.predict(Image.new("RGB", (8, 8)))++ assert mock_urlopen.call_count == 2diff --git a/tests/test_model_home.py b/tests/test_model_home.pyindex 122e8a9..d451574 100644--- a/tests/test_model_home.py+++ b/tests/test_model_home.py@@ -115,3 +115,15 @@ def test_validate_model_path_rejects_sibling_prefix(clean_env, tmp_path):def test_validate_model_path_requires_the_argument(clean_env):with pytest.raises(ValueError):BaseSession.validate_model_path()+++def test_validate_model_path_rejects_symlink_escape(clean_env, tmp_path):+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))+ models = tmp_path / "new" / "models"+ models.mkdir(parents=True)+ outside = tmp_path / "outside.onnx"+ outside.write_bytes(b"")+ (models / "link.onnx").symlink_to(outside)++ with pytest.raises(ValueError):+ BaseSession.validate_model_path(model_path=str(models / "link.onnx"))diff --git a/tests/test_server_hardening.py b/tests/test_server_hardening.pynew file mode 100644index 0000000..7bd1cba--- /dev/null+++ b/tests/test_server_hardening.py@@ -0,0 +1,171 @@+import importlib+import io+import json+from unittest import mock++import pytest+from fastapi.testclient import TestClient+from PIL import Image++s_command = importlib.import_module("rembg.commands.s_command")+++class FakeSession:+ def __init__(self, model_name, **kwargs):+ self.model_name = model_name+ self.kwargs = kwargs++ def predict(self, img, *args, **kwargs):+ return [Image.new("L", img.size, 255)]+++def png():+ buf = io.BytesIO()+ Image.new("RGB", (4, 4)).save(buf, "PNG")+ return buf.getvalue()+++def built():+ sessions = []++ def fake_new_session(model_name, **kwargs):+ session = FakeSession(model_name, **kwargs)+ sessions.append(session)+ return session++ with mock.patch.object(s_command, "new_session", fake_new_session):+ yield sessions+++def make_client(*cli_args):+ captured = {}+ with mock.patch.object(+ s_command.uvicorn, "run", lambda app, **kw: captured.update(app=app)+ ):+ s_command.s_command.main(["--no-ui", *cli_args], standalone_mode=False)+ return TestClient(captured["app"], raise_server_exceptions=False)+++def post(client, png, model="u2net", **params):+ return client.post(+ "/api/remove", params=params, data={"model": model}, files={"file": png}+ )++[email protected]("model", ["atlascloud", "withoutbg"])+def test_remote_models_are_refused_by_default(png, built, model):+ """Cloud models would bill the server's own API key to any caller."""+ assert post(make_client(), png, model=model).status_code == 422+ assert built == []++[email protected]("model", ["atlascloud", "withoutbg"])+def test_remote_models_can_be_enabled(png, built, model):+ client = make_client("--allow-remote-models")+ assert post(client, png, model=model).status_code == 200+++def test_model_name_must_match_exactly(png, built):+ assert post(make_client(), png, model="zzz-u2net-zzz").status_code == 422+++def test_session_cache_is_bounded(png, built):+ client = make_client("--max-sessions", "2")++ for name in ["a", "b", "c"]:+ extras = json.dumps({"model_path": name})+ assert post(client, png, extras=extras).status_code == 200++ # "a" was evicted, so asking for it again builds a new session.+ post(client, png, extras=json.dumps({"model_path": "a"}))+ assert [s.kwargs["model_path"] for s in built] == ["a", "b", "c", "a"]+++def test_predict_extras_reuse_the_cached_session(png, built):+ client = make_client()++ for i in range(5):+ extras = json.dumps({"sam_prompt": [{"type": "point", "data": [i, i]}]})+ assert post(client, png, extras=extras).status_code == 200++ assert len(built) == 1+++ "extras",+ [+ '{"providers": ["CPUExecutionProvider"]}',+ '{"sess_opts": 1}',+ '{"session": 1}',+ '{"x": 1}',+ "not json",+ "[1, 2]",+ ],+)+def test_unsupported_extras_are_rejected(png, built, extras):+ assert post(make_client(), png, extras=extras).status_code == 400+ assert built == []++[email protected]("bgc", ["abc", "1,2", "1,2,3,4,5", "0,0,0,256", "-1,0,0"])+def test_invalid_bgcolor_is_a_client_error(png, built, bgc):+ assert post(make_client(), png, bgc=bgc).status_code == 400++[email protected]("bgc", ["255,255,255", "0,0,0,255"])+def test_valid_bgcolor_is_accepted(png, built, bgc):+ assert post(make_client(), png, bgc=bgc).status_code == 200+++def test_erode_size_is_bounded(png, built):+ client = make_client()++ def remove(ae):+ data = {"model": "u2net", "a": "true", "ae": ae}+ return client.post("/api/remove", data=data, files={"file": png})++ assert remove("255").status_code == 200+ assert remove("100000").status_code == 422+++def small_upload_limit():+ with mock.patch.object(s_command, "_MAX_IMAGE_BYTES", 1024), mock.patch.object(+ s_command, "_MAX_FORM_OVERHEAD_BYTES", 0+ ):+ yield 1024+++def test_upload_within_limit_is_accepted(png, built, small_upload_limit):+ assert post(make_client(), png).status_code == 200+++def test_oversized_upload_is_rejected(built, small_upload_limit):+ big = b"\0" * (small_upload_limit * 2)+ r = make_client().post("/api/remove", data={"model": "u2net"}, files={"file": big})+ assert r.status_code == 413+ assert built == []+++def test_oversized_chunked_upload_is_rejected(built, small_upload_limit):+ """A body without Content-Length is counted as it streams in."""++ def chunks():+ yield (+ b"--x\r\n"+ b'Content-Disposition: form-data; name="file"; filename="a.png"\r\n'+ b"Content-Type: image/png\r\n\r\n"+ )+ for _ in range(4):+ yield b"\0" * small_upload_limit+ yield b"\r\n--x--\r\n"++ r = make_client().post(+ "/api/remove",+ content=chunks(),+ headers={"Content-Type": "multipart/form-data; boundary=x"},+ )+ assert r.status_code == 413+ assert built == []