diff --git a/fri/server/main.py b/fri/server/main.py index 760db294..c898752f 100644 --- a/fri/server/main.py +++ b/fri/server/main.py @@ -66,6 +66,20 @@ def validate_text_field(value, field_name, max_length=None): raise ValueError(f"Invalid {field_name}: too long (max {max_length} characters)") return True +# cmd.exe runs these as operators even when the args are passed as a list with shell=True +CMD_METACHARS = re.compile(r'[&|<>^%!"\r\n]') + +def validate_run_args(maxtime, params): + """Validate maxtime/params before they reach the maxtime/params scripts.""" + if maxtime: + try: + float(maxtime) + except ValueError: + raise ValueError("Invalid maxtime: must be a number") + if params and platform.uname()[0] == 'Windows' and CMD_METACHARS.search(params): + raise ValueError("Invalid params: contains characters cmd.exe treats as commands") + return True + def get_error_output(e): """Extract error output from CalledProcessError, preferring stderr then output.""" raw_output = None @@ -189,6 +203,15 @@ def build(dir): maxtime = request.args.get('maxtime') apikey = request.args.get('apikey') out_dir = request.args.get('outdir') + try: + validate_input(graphml_file, 'fetch', required=True) + validate_input(out_dir, 'outdir') + validate_input(apikey, 'apikey') + validate_run_args(maxtime, params) + except ValueError as e: + resp = jsonify({'message': str(e)}) + resp.status_code = 400 + return resp output_str = "" if(apikey == None): dirname = secure_filename(dir) @@ -332,6 +355,12 @@ def clear(dir): unlock = request.args.get('unlock') params = request.args.get('params') maxtime = request.args.get('maxtime') + try: + validate_run_args(maxtime, params) + except ValueError as e: + resp = jsonify({'message': str(e)}) + resp.status_code = 400 + return resp dir_name = secure_filename(dir) dir_path = os.path.abspath(os.path.join(concore_path, dir_name)) if(platform.uname()[0]=='Windows'): diff --git a/tests/test_fri_input_validation.py b/tests/test_fri_input_validation.py new file mode 100644 index 00000000..0713653d --- /dev/null +++ b/tests/test_fri_input_validation.py @@ -0,0 +1,68 @@ +"""Query parameters of /build and /clear must not reach cmd.exe unchecked.""" + +import os +import sys +from unittest.mock import patch + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +pytest.importorskip( + "flask", reason="flask not installed — skipping server endpoint tests" +) + + +@pytest.fixture +def server(): + with patch.dict(os.environ, {"FLASK_SECRET_KEY": "test-flask-secret-key"}): + import fri.server.main as mod + + mod.app.config["TESTING"] = True + calls = [] + + def fake_call(args, **kwargs): + calls.append(args) + return 0 + + with patch.object(mod.platform, "uname", return_value=("Windows",)): + with patch.object(mod, "call", fake_call): + with patch.object(mod.subprocess, "check_output", return_value=b""): + with mod.app.test_client() as client: + yield client, calls + + +@pytest.mark.parametrize( + "query", + ["maxtime=100%26calc", "maxtime=abc", "params=a%3D1%26calc", "params=a%3D1|calc"], +) +def test_clear_rejects_unsafe_args(server, query): + client, calls = server + resp = client.post(f"/clear/study?{query}") + assert resp.status_code == 400 + assert calls == [] + + +@pytest.mark.parametrize( + "query", + [ + "fetch=sample%26calc", + "fetch=sample&outdir=out%26calc", + "fetch=sample&apikey=k%26calc", + "fetch=sample&maxtime=100%26calc", + "fetch=sample¶ms=a%3D1%26calc", + ], +) +def test_build_rejects_unsafe_args(server, query): + client, calls = server + resp = client.post(f"/build/study?{query}") + assert resp.status_code == 400 + assert calls == [] + + +def test_clear_passes_valid_args(server): + client, calls = server + resp = client.post("/clear/study?maxtime=100¶ms=a%3D1%3Bb%3D[1,2]") + assert resp.status_code == 201 + assert ["maxtime", "100"] in calls + assert ["params", "a=1;b=[1,2]"] in calls