diff --git a/docs/preview-notes.md b/docs/preview-notes.md index 8659838..c556d68 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,12 +1,26 @@ -# Modsim 2.0.0a3 preview +# Modsim 2.0.0a4 preview + +Remote models and scenarios load directly from a site such as ModioHub: + +```sh +uvx --prerelease allow modsim==2.0.0a4 --config https://example.org/device.tm.json \ + --scenario https://example.org/device.sim.json --bind 127.0.0.1 --port 5020 +``` + +HTTPS requests identify themselves as `modsim/`, because some CDNs reject +the default Python agent. `--scenario` accepts an HTTPS URL; a remote scenario +cannot name a behavior script. This preview still pins modpoll-wot 0.2.0a4. + +### Previous preview + +#### Modsim 2.0.0a3 + This preview pins modpoll-wot 0.2.0a4. A local TCP simulator can load a full profile 0.2 TM with an audit plan or its independently derived public audit TM. Tests seed the same known values and verify the public model exposes only the selected read spans. -### Previous preview - #### Modsim 2.0.0a2 This candidate uses published modpoll-wot 0.2.0a2 and immutable modbus-models-v1 diff --git a/modsim/__init__.py b/modsim/__init__.py index 6d39a38..981a129 100644 --- a/modsim/__init__.py +++ b/modsim/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0a3" +__version__ = "2.0.0a4" diff --git a/modsim/deployment.py b/modsim/deployment.py index 27312de..21d464c 100644 --- a/modsim/deployment.py +++ b/modsim/deployment.py @@ -7,7 +7,7 @@ from jsonschema import Draft7Validator # type: ignore[import-untyped] from modpoll_wot.loading import load_document # type: ignore[import-untyped] -from .sources import local_path +from .sources import is_remote, local_path, remote_document def obj(properties: dict, required: tuple = ()) -> dict: @@ -68,15 +68,23 @@ def obj(properties: dict, required: tuple = ()) -> dict: def document(path: str, schema: dict) -> dict: - source = Path(local_path(Path.cwd(), path)) - value = load_document(source) + source: str | Path + if is_remote(path): + source = path + value = remote_document(path) + # Behavior scripts are local code; never resolve them from a download. + if isinstance(value, dict) and "script" in value: + raise ValueError(f"{path}: remote scenarios cannot reference scripts") + else: + source = Path(local_path(Path.cwd(), path)) + value = load_document(source) errors = sorted( Draft7Validator(schema).iter_errors(value), key=lambda error: str(error.path) ) if errors: error = errors[0] raise ValueError(f"{source}: {'/'.join(map(str, error.path))}: {error.message}") - return value # type: ignore[no-any-return] + return value def apply_scenario(args: Any) -> None: diff --git a/modsim/sources.py b/modsim/sources.py index 2998f1a..8a4ef92 100644 --- a/modsim/sources.py +++ b/modsim/sources.py @@ -1,12 +1,21 @@ -"""Bounded local JSON and HTTPS model loading.""" +"""Bounded local JSON and HTTPS model and scenario loading.""" import tempfile from pathlib import Path from urllib.parse import urlparse -from urllib.request import urlopen +from urllib.request import Request, urlopen from modpoll_wot.loading import MAX_BYTES, load_document # type: ignore[import-untyped] +from . import __version__ + +# Some CDNs reject the default Python-urllib agent; identify the tool instead. +USER_AGENT = f"modsim/{__version__}" + + +def is_remote(value: str) -> bool: + return bool(urlparse(value).scheme) and not Path(value).is_absolute() + def local_path(base: Path, value: str) -> str: if urlparse(value).scheme and not Path(value).is_absolute(): @@ -15,23 +24,29 @@ def local_path(base: Path, value: str) -> str: def model_document(source: str) -> dict: - url = urlparse(source) - if Path(source).is_absolute() or not url.scheme: + if not is_remote(source): return load_document(source) # type: ignore[no-any-return] + return remote_document(source) + + +def remote_document(source: str) -> dict: + """Load bounded JSON from an HTTPS URL with the shared loader's rules.""" + url = urlparse(source) if url.scheme != "https": - raise ValueError("model URLs must use HTTPS") + raise ValueError("model and scenario URLs must use HTTPS") if url.hostname == "github.com": parts = url.path.strip("/").split("/") if len(parts) >= 5 and parts[2] == "blob": source = "https://raw.githubusercontent.com/" + "/".join( parts[:2] + parts[3:] ) - with urlopen(source, timeout=15) as response: + request = Request(source, headers={"User-Agent": USER_AGENT}) + with urlopen(request, timeout=15) as response: if urlparse(response.geturl()).scheme != "https": - raise ValueError("model redirect must use HTTPS") + raise ValueError("redirect must use HTTPS") payload = response.read(MAX_BYTES + 1) if len(payload) > MAX_BYTES: - raise ValueError(f"model exceeds {MAX_BYTES} bytes") + raise ValueError(f"document exceeds {MAX_BYTES} bytes") # Reuse all bounded JSON parsing rules from the public shared loader. with tempfile.TemporaryDirectory(prefix="modsim-model-") as directory: path = Path(directory) / "model.json" diff --git a/modsim/utils.py b/modsim/utils.py index c65ba38..f6faad5 100644 --- a/modsim/utils.py +++ b/modsim/utils.py @@ -23,7 +23,9 @@ def get_parser() -> argparse.ArgumentParser: ) sources = parser.add_mutually_exclusive_group() sources.add_argument("--config", help="Profile 0.2 TM/TD local path or HTTPS URL") - parser.add_argument("--scenario", help="Local scenario JSON for --config") + parser.add_argument( + "--scenario", help="Scenario JSON local path or HTTPS URL for --config" + ) parser.add_argument("--script", help="Local Python behavior for --config") parser.add_argument( "--allow-scripts", diff --git a/pyproject.toml b/pyproject.toml index a0e3373..cf2c945 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "modsim" -version = "2.0.0a3" +version = "2.0.0a4" description = "A Simple Modbus TCP Device Simulator used for modpoll tool" authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }] readme = "README.md" diff --git a/tests/test_deployment.py b/tests/test_deployment.py index 386a4f5..6531a76 100644 --- a/tests/test_deployment.py +++ b/tests/test_deployment.py @@ -196,7 +196,7 @@ def geturl(self): == "0.2" ) assert ( - request.call_args.args[0] + request.call_args.args[0].full_url == "https://raw.githubusercontent.com/top-maker/modsim/v2/device.json" ) with patch("modsim.sources.urlopen", return_value=Response(b'{"a":1,"a":2}')): diff --git a/tests/test_remote_sources.py b/tests/test_remote_sources.py new file mode 100644 index 0000000..b4744aa --- /dev/null +++ b/tests/test_remote_sources.py @@ -0,0 +1,43 @@ +"""HTTPS model and scenario sources.""" + +from io import BytesIO +import json +from unittest.mock import patch + +import pytest + +from modsim import __version__, deployment, sources + + +class Response(BytesIO): + def __init__(self, payload, url="https://example.invalid/file.json"): + super().__init__(payload) + self.url = url + + def geturl(self): + return self.url + + +def test_remote_documents_identify_modsim(): + payload = json.dumps({"version": "1", "tick": 0.5}).encode() + with patch.object(sources, "urlopen", return_value=Response(payload)) as remote: + scenario = deployment.document( + "https://example.invalid/device.sim.json", deployment.SCENARIO + ) + assert scenario == {"version": "1", "tick": 0.5} + request = remote.call_args.args[0] + assert request.full_url == "https://example.invalid/device.sim.json" + assert request.get_header("User-agent") == f"modsim/{__version__}" + + +def test_remote_scenarios_reject_scripts_and_plain_http(): + payload = json.dumps({"version": "1", "script": "behavior.py"}).encode() + with patch.object(sources, "urlopen", return_value=Response(payload)): + with pytest.raises(ValueError, match="cannot reference scripts"): + deployment.document("https://example.invalid/s.json", deployment.SCENARIO) + with pytest.raises(ValueError, match="must use HTTPS"): + deployment.document("http://example.invalid/s.json", deployment.SCENARIO) + redirected = Response(b"{}", url="http://example.invalid/s.json") + with patch.object(sources, "urlopen", return_value=redirected): + with pytest.raises(ValueError, match="redirect must use HTTPS"): + sources.model_document("https://example.invalid/m.json") diff --git a/uv.lock b/uv.lock index f2df119..cd769f6 100644 --- a/uv.lock +++ b/uv.lock @@ -843,7 +843,7 @@ wheels = [ [[package]] name = "modsim" -version = "2.0.0a3" +version = "2.0.0a4" source = { editable = "." } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" },