avoigt1121 commited on
Commit
eb1c0a8
·
2 Parent(s): bd144d63a49368

merge: fix/direct-call-bandit — direct calls check https + clinicaltrials.gov before urlopen; nosec B310 (pre-push scan blocked bd144d6)

Browse files
Files changed (2) hide show
  1. src/direct_calls.py +23 -2
  2. tests/test_direct_calls.py +35 -2
src/direct_calls.py CHANGED
@@ -19,6 +19,7 @@ caller types reaches the URL. This module imports nothing from ``src``.
19
  from __future__ import annotations
20
 
21
  import json
 
22
  import urllib.request
23
  from dataclasses import dataclass
24
  from typing import Any
@@ -44,6 +45,24 @@ DIRECT_CALLS: dict[str, DirectCall] = {
44
  }
45
 
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  def is_direct(tool: str) -> bool:
48
  return tool in DIRECT_CALLS
49
 
@@ -55,8 +74,10 @@ def run(tool: str, args: dict[str, Any], timeout: float) -> dict[str, Any]:
55
  if args:
56
  raise ValueError(f"{tool} takes no arguments")
57
  request = urllib.request.Request(
58
- call.url, headers={"Accept": "application/json", "User-Agent": "pdac-knowledge-agent"}
 
59
  )
60
- with urllib.request.urlopen(request, timeout=timeout) as response:
 
61
  data = json.loads(response.read().decode("utf-8"))
62
  return {"status": "success", "data": data, "metadata": {"source": call.url}}
 
19
  from __future__ import annotations
20
 
21
  import json
22
+ import urllib.parse
23
  import urllib.request
24
  from dataclasses import dataclass
25
  from typing import Any
 
45
  }
46
 
47
 
48
+ # The only scheme and hosts a direct call may open. Checked on every call before urlopen, so a
49
+ # later edit to DIRECT_CALLS cannot reach file://, http:// or another host (bandit B310).
50
+ ALLOWED_SCHEME = "https"
51
+ ALLOWED_HOSTS = frozenset({"clinicaltrials.gov"})
52
+
53
+
54
+ def checked_url(url: str) -> str:
55
+ """``url`` unchanged if it is https on an allowed host, else ValueError."""
56
+ parts = urllib.parse.urlsplit(url)
57
+ if parts.scheme != ALLOWED_SCHEME or parts.hostname not in ALLOWED_HOSTS:
58
+ raise ValueError(
59
+ f"direct calls open only https://{sorted(ALLOWED_HOSTS)} URLs; got {url!r}"
60
+ )
61
+ if parts.username or parts.password or parts.port not in (None, 443):
62
+ raise ValueError(f"direct call URL may not carry credentials or a port: {url!r}")
63
+ return url
64
+
65
+
66
  def is_direct(tool: str) -> bool:
67
  return tool in DIRECT_CALLS
68
 
 
74
  if args:
75
  raise ValueError(f"{tool} takes no arguments")
76
  request = urllib.request.Request(
77
+ checked_url(call.url),
78
+ headers={"Accept": "application/json", "User-Agent": "pdac-knowledge-agent"},
79
  )
80
+ # nosec B310: the URL passed checked_url() above (https, clinicaltrials.gov only, fixed in code).
81
+ with urllib.request.urlopen(request, timeout=timeout) as response: # nosec B310
82
  data = json.loads(response.read().decode("utf-8"))
83
  return {"status": "success", "data": data, "metadata": {"source": call.url}}
tests/test_direct_calls.py CHANGED
@@ -12,8 +12,8 @@ from pathlib import Path
12
 
13
  import pytest
14
 
15
- from src import config, schemas
16
- from src.direct_calls import DIRECT_CALLS, run
17
  from src.tu_client import ToolClient
18
  from tests.conftest import FakeRunner
19
 
@@ -71,3 +71,36 @@ def test_no_other_module_opens_a_url_itself():
71
  p.name for p in ROOT.glob("*.py") if pattern.search(p.read_text(encoding="utf-8"))
72
  ]
73
  assert offenders == ["src/direct_calls.py"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  import pytest
14
 
15
+ from src import config, direct_calls, schemas
16
+ from src.direct_calls import DIRECT_CALLS, DirectCall, checked_url, run
17
  from src.tu_client import ToolClient
18
  from tests.conftest import FakeRunner
19
 
 
71
  p.name for p in ROOT.glob("*.py") if pattern.search(p.read_text(encoding="utf-8"))
72
  ]
73
  assert offenders == ["src/direct_calls.py"]
74
+
75
+
76
+ @pytest.mark.parametrize(
77
+ "url",
78
+ [
79
+ "http://clinicaltrials.gov/api/v2/version",
80
+ "file:///etc/passwd",
81
+ "ftp://clinicaltrials.gov/api/v2/version",
82
+ "https://example.org/api/v2/version",
83
+ "https://clinicaltrials.gov.evil.example/api/v2/version",
84
+ "https://user:pw@clinicaltrials.gov/api/v2/version",
85
+ "https://clinicaltrials.gov:8443/api/v2/version",
86
+ ],
87
+ )
88
+ def test_a_non_https_or_other_host_url_is_refused(url):
89
+ with pytest.raises(ValueError):
90
+ checked_url(url)
91
+
92
+
93
+ def test_run_refuses_a_bad_url_before_opening_anything(monkeypatch):
94
+ opened = []
95
+ monkeypatch.setattr(direct_calls.urllib.request, "urlopen", lambda *a, **k: opened.append(a))
96
+ monkeypatch.setitem(
97
+ DIRECT_CALLS, "bad", DirectCall(source="clinicaltrials", url="http://x.example/", why="t")
98
+ )
99
+ with pytest.raises(ValueError):
100
+ run("bad", {}, timeout=1)
101
+ assert opened == []
102
+
103
+
104
+ @pytest.mark.parametrize("tool", sorted(DIRECT_CALLS))
105
+ def test_every_direct_call_url_passes_the_check(tool):
106
+ assert checked_url(DIRECT_CALLS[tool].url) == DIRECT_CALLS[tool].url