test_zero_ports_check.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  1. """scripts/zero_ports_check.py: the external zero-open-ports check.
  2. Hermetic. Nothing here reaches a real network target: an autouse guard fails any
  3. socket call that is not loopback, the API is either a fake object or a local
  4. HTTP server on an ephemeral loopback port (so urllib's real redirect and proxy
  5. machinery runs), and the port accounting uses an injected connect function with
  6. a fake clock. Real sockets are opened only against loopback and only for a
  7. handful of ports.
  8. """
  9. from __future__ import annotations
  10. import ast
  11. import concurrent.futures
  12. import contextlib
  13. import errno
  14. import io
  15. import ipaddress
  16. import itertools
  17. import json
  18. import os
  19. import socket
  20. import stat
  21. import subprocess
  22. import sys
  23. import threading
  24. import traceback
  25. import urllib.error
  26. import urllib.parse
  27. import urllib.request
  28. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  29. from pathlib import Path
  30. import pytest
  31. ROOT = Path(__file__).resolve().parent.parent
  32. SCRIPT = ROOT / "scripts" / "zero_ports_check.py"
  33. sys.path.insert(0, str(ROOT / "scripts"))
  34. import zero_ports_check as zpc
  35. # Built at run time so no secret-shaped literal sits in the file (gitleaks scans it).
  36. CRED = "-".join(("tok", "SECRET", "MARKER", "0123456789")) # noqa: FLY002 - keep it out of the source text
  37. A = "198.51.100.10" # documentation range (TEST-NET-2): never a real address
  38. B = "198.51.100.11"
  39. RESERVED = "198.51.100.50"
  40. PROJ = "proj-1"
  41. U1 = "198.51.100.11" # first address units() builds
  42. TESTNET2 = ipaddress.ip_network("198.51.100.0/24")
  43. def OK(addr: ipaddress.IPv4Address) -> bool:
  44. """The real predicate, plus the documentation range the fixtures use."""
  45. return zpc.default_address_ok(addr) or addr in TESTNET2
  46. # ------------------------------------------------------------------ guards
  47. @pytest.fixture(autouse=True)
  48. def no_external_network(monkeypatch):
  49. real_connect = socket.socket.connect
  50. real_connect_ex = socket.socket.connect_ex
  51. real_getaddrinfo = socket.getaddrinfo
  52. def check(address):
  53. host = address[0] if isinstance(address, tuple) else address
  54. if host != "127.0.0.1":
  55. raise AssertionError("a test tried to reach a non-loopback address")
  56. def connect(self, address):
  57. check(address)
  58. return real_connect(self, address)
  59. def connect_ex(self, address):
  60. check(address)
  61. return real_connect_ex(self, address)
  62. def getaddrinfo(host, *args, **kwargs):
  63. if host not in ("127.0.0.1", "localhost", None):
  64. raise AssertionError("a test tried to resolve a non-loopback name")
  65. return real_getaddrinfo(host, *args, **kwargs)
  66. monkeypatch.setattr(socket.socket, "connect", connect)
  67. monkeypatch.setattr(socket.socket, "connect_ex", connect_ex)
  68. monkeypatch.setattr(socket, "getaddrinfo", getaddrinfo)
  69. for name in ("DIGITALOCEAN_TOKEN", "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY",
  70. "no_proxy", "NO_PROXY", "all_proxy", "ALL_PROXY"):
  71. monkeypatch.delenv(name, raising=False)
  72. # ------------------------------------------------------------------ fakes
  73. BASELINE_TAG = "cah-baseline-tor1"
  74. _NO_TAGS = object()
  75. def droplet(did: int, ip: str | object = A, *, v6=(), v4_extra=(), tags: object = None) -> dict:
  76. v4 = [{"ip_address": "10.116.0.2", "type": "private"}]
  77. if ip is not None:
  78. v4.append({"ip_address": ip, "type": "public"})
  79. v4.extend(v4_extra)
  80. out = {"id": did, "networks": {"v4": v4, "v6": list(v6)}}
  81. if tags is not _NO_TAGS:
  82. out["tags"] = [BASELINE_TAG, "other"] if tags is None else tags
  83. return out
  84. class FakeAPI:
  85. """The DigitalOcean listings the script reads, with knobs for the hostile cases."""
  86. def __init__(self, *, tagged=None, project_droplets=None, projects=None,
  87. reserved4=(), reserved6=(), page_size=200, tag=BASELINE_TAG):
  88. self.tag = tag
  89. self.tagged = [droplet(1001, A), droplet(1002, B)] if tagged is None else tagged
  90. ids = [d["id"] for d in self.tagged] if project_droplets is None else project_droplets
  91. self.projects = [{"id": PROJ, "name": zpc.PROJECT_NAME}] if projects is None else projects
  92. self.resources = [{"urn": f"do:droplet:{i}"} for i in ids] + [{"urn": "do:volume:abc"}]
  93. self.reserved4 = list(reserved4)
  94. self.reserved6 = list(reserved6)
  95. self.page_size = page_size
  96. self.total_override = None
  97. self.cycle = False
  98. self.endless = False
  99. self.calls: list[tuple[str, dict]] = []
  100. def _list(self, key, items, params, total=None):
  101. page = int(params["page"])
  102. if self.cycle:
  103. page = 1
  104. size = self.page_size
  105. chunk = items[(page - 1) * size: page * size]
  106. more = page * size < len(items) or self.cycle
  107. data = {"meta": {"total": len(items) if total is None else total}, key: chunk,
  108. "links": {"pages": {"next": f"https://elsewhere.invalid/x?page={page + 1}"} if more else {}}}
  109. if self.total_override is not None:
  110. data["meta"]["total"] = self.total_override
  111. return data
  112. def get(self, path, params):
  113. self.calls.append((path, dict(params)))
  114. if path == "/v2/projects":
  115. return self._list("projects", self.projects, params)
  116. if path.startswith("/v2/projects/") and path.endswith("/resources"):
  117. return self._list("resources", self.resources, params)
  118. if path == "/v2/droplets":
  119. assert params["tag_name"] == self.tag
  120. if self.endless:
  121. page = int(params["page"])
  122. return {"droplets": [droplet(50000 + page, A)], "meta": {"total": 10**6},
  123. "links": {"pages": {"next": "x"}}}
  124. return self._list("droplets", self.tagged, params)
  125. if path == "/v2/reserved_ips":
  126. return self._list("reserved_ips", self.reserved4, params)
  127. if path == "/v2/reserved_ipv6":
  128. return self._list("reserved_ipv6s", self.reserved6, params)
  129. raise AssertionError(f"unexpected path {path}")
  130. class InlineExecutor:
  131. """Runs each task at submit time: deterministic for the fake-clock tests."""
  132. def __init__(self, max_workers=None):
  133. pass
  134. def submit(self, fn, *args):
  135. fut = concurrent.futures.Future()
  136. try:
  137. fut.set_result(fn(*args))
  138. except (RuntimeError, OSError, ValueError) as exc: # mimic a worker failure
  139. fut.set_exception(exc)
  140. return fut
  141. def shutdown(self, wait=True, cancel_futures=False):
  142. pass
  143. class Clock:
  144. def __init__(self):
  145. self.t = 0.0
  146. def __call__(self):
  147. return self.t
  148. def sleep(self, d):
  149. self.t += d
  150. class Counters:
  151. """Counts every connect, scan or control. Zero after any discovery failure."""
  152. def __init__(self, outcome=zpc.TIMEOUT):
  153. self.scan = 0
  154. self.control = 0
  155. self.outcome = outcome
  156. self.calls = []
  157. def connect(self, address, port, timeout):
  158. self.scan += 1
  159. self.calls.append((address, port))
  160. return self.outcome(address, port) if callable(self.outcome) else self.outcome
  161. def control_connect(self, host, port, timeout):
  162. self.control += 1
  163. def units(n=2) -> zpc.Inventory:
  164. return zpc.Inventory(tuple(
  165. zpc.Unit(f"connector-{i}", f"198.51.100.{10 + i}", 1000 + i) for i in range(1, n + 1)))
  166. def run_main(api, expected=2, *, argv=(), counters=None, token=CRED, env=None, **hook_kw):
  167. counters = counters or Counters()
  168. kw = {
  169. "address_ok": OK,
  170. "connect": counters.connect,
  171. "control_connect": counters.control_connect,
  172. "transport_factory": lambda t: api,
  173. "ports": range(1, 4),
  174. "budget": zpc.Budget(concurrency=4, rate=1e9, batch=4096),
  175. "executor_factory": InlineExecutor,
  176. "sleep": lambda d: None,
  177. }
  178. kw.update(hook_kw)
  179. out = io.StringIO()
  180. environment = {"DIGITALOCEAN_TOKEN": token} if env is None else env
  181. code = zpc.main(["--expect-connectors", str(expected), *argv], env=environment,
  182. hooks=zpc.Hooks(**kw), stdout=out)
  183. return code, out.getvalue(), counters
  184. # ------------------------------------------------------------------ discovery
  185. def test_discovery_happy_path_labels_and_calls():
  186. api = FakeAPI()
  187. inv = zpc.discover(api, 2, "tor1", OK)
  188. assert inv.labels == ("connector-1", "connector-2")
  189. assert [u.address for u in inv.units] == [A, B]
  190. paths = {p for p, _ in api.calls}
  191. assert paths == {"/v2/projects", f"/v2/projects/{PROJ}/resources", "/v2/droplets",
  192. "/v2/reserved_ips", "/v2/reserved_ipv6"}
  193. assert A not in repr(inv) and B not in repr(inv)
  194. def test_tagged_droplet_outside_project_is_ignored_not_scanned():
  195. api = FakeAPI(tagged=[droplet(1001, A), droplet(1002, B), droplet(1003, "198.51.100.99")],
  196. project_droplets=[1001, 1002])
  197. inv = zpc.discover(api, 2, "tor1", OK)
  198. assert {u.droplet_id for u in inv.units} == {1001, 1002}
  199. assert "198.51.100.99" not in {u.address for u in inv.units}
  200. def test_reserved_ip_attached_to_target_is_one_more_target():
  201. api = FakeAPI(reserved4=[{"ip": RESERVED, "droplet": {"id": 1001}},
  202. {"ip": "198.51.100.77", "droplet": None},
  203. {"ip": "198.51.100.78", "droplet": {"id": 4242}}])
  204. inv = zpc.discover(api, 2, "tor1", OK)
  205. assert [u.label for u in inv.units] == ["connector-1", "connector-1-extra-1", "connector-2"]
  206. assert RESERVED in {u.address for u in inv.units}
  207. assert "198.51.100.77" not in {u.address for u in inv.units}
  208. def _bad(**kw):
  209. return FakeAPI(**kw)
  210. def _ip_case(value):
  211. return lambda: FakeAPI(tagged=[droplet(1001, value), droplet(1002, B)])
  212. def _mapped():
  213. return _ip_case("::ffff:198.51.100.10")()
  214. DISCOVERY_FAILURES = {
  215. "pagination-cycle": lambda: _cycle(),
  216. "repeated-item": lambda: FakeAPI(tagged=[droplet(1001, A), droplet(1001, B)], project_droplets=[1001]),
  217. "total-contradicts-pages": lambda: _total(),
  218. "empty-inventory": lambda: FakeAPI(tagged=[], project_droplets=[]),
  219. "fewer-than-expected": lambda: FakeAPI(tagged=[droplet(1001, A)]),
  220. "page-cap-hit": lambda: _endless(),
  221. "non-string-address": _ip_case(None),
  222. "integer-address": _ip_case(3325256714),
  223. "float-address": _ip_case(1.5),
  224. "list-address": _ip_case([A]),
  225. "ipv4-mapped-ipv6": _mapped,
  226. "decimal-spelling": _ip_case("3325256714"),
  227. "octal-spelling": _ip_case("0306.0063.0144.012"),
  228. "leading-zero": _ip_case("198.051.100.10"),
  229. "hex-spelling": _ip_case("0xc6.0x33.0x64.0x0a"),
  230. "trailing-space": _ip_case(A + " "),
  231. "trailing-newline": _ip_case(A + "\n"),
  232. "trailing-prefix": _ip_case(A + "/32"),
  233. "three-octets": _ip_case("198.51.100"),
  234. "private": _ip_case("10.1.2.3"),
  235. "loopback": _ip_case("127.0.0.1"),
  236. "link-local": _ip_case("169.254.1.1"),
  237. "multicast": _ip_case("224.0.0.1"),
  238. "reserved-range": _ip_case("240.0.0.1"),
  239. "cgnat": _ip_case("100.64.0.1"),
  240. "no-public-address": lambda: FakeAPI(tagged=[droplet(1001, None), droplet(1002, B)]),
  241. "public-ipv6-on-droplet": lambda: FakeAPI(tagged=[
  242. droplet(1001, A, v6=[{"ip_address": "2001:db8::1", "type": "public"}]), droplet(1002, B)]),
  243. "malformed-ipv6-entry": lambda: FakeAPI(tagged=[droplet(1001, A, v6=["x"]), droplet(1002, B)]),
  244. "project-droplet-without-tag": lambda: FakeAPI(project_droplets=[1001, 1002, 1999]),
  245. "project-missing": lambda: FakeAPI(projects=[{"id": "p", "name": "other"}]),
  246. "project-duplicated": lambda: FakeAPI(projects=[{"id": "p1", "name": zpc.PROJECT_NAME},
  247. {"id": "p2", "name": zpc.PROJECT_NAME}]),
  248. "project-id-malformed": lambda: FakeAPI(projects=[{"id": "../x", "name": zpc.PROJECT_NAME}]),
  249. "reserved-ipv6-on-target": lambda: FakeAPI(reserved6=[{"ip": "2001:db8::5", "droplet": {"id": 1001}}]),
  250. "reserved-ip-private": lambda: FakeAPI(reserved4=[{"ip": "10.0.0.9", "droplet": {"id": 1001}}]),
  251. "reserved-malformed-assignment": lambda: FakeAPI(reserved4=[{"ip": RESERVED, "droplet": "1001"}]),
  252. "bool-droplet-id": lambda: FakeAPI(tagged=[droplet(True, A), droplet(1002, B)], project_droplets=[1, 1002]),
  253. "duplicate-address": lambda: FakeAPI(tagged=[droplet(1001, A), droplet(1002, A)]),
  254. }
  255. def _cycle():
  256. api = FakeAPI(page_size=1)
  257. api.cycle = True
  258. return api
  259. def _total():
  260. api = FakeAPI()
  261. api.total_override = 5
  262. return api
  263. def _endless():
  264. api = FakeAPI()
  265. api.endless = True
  266. return api
  267. @pytest.mark.parametrize("name", sorted(DISCOVERY_FAILURES))
  268. def test_every_discovery_failure_is_exit_2_with_zero_connects(name):
  269. api = DISCOVERY_FAILURES[name]()
  270. with pytest.raises(zpc.CheckError):
  271. zpc.discover(api, 2, "tor1", OK)
  272. counters = Counters()
  273. code, out, _ = run_main(DISCOVERY_FAILURES[name](), counters=counters)
  274. assert code == 2, out
  275. assert counters.scan == 0 and counters.control == 0
  276. assert "PASS" not in out
  277. for secret in (A, B, CRED):
  278. assert secret not in out
  279. def test_endless_listing_stops_at_the_page_cap():
  280. api = _endless()
  281. with pytest.raises(zpc.CheckError):
  282. zpc.discover(api, 2, "tor1", OK)
  283. assert len([c for c in api.calls if c[0] == "/v2/droplets"]) == zpc.MAX_PAGES
  284. @pytest.mark.parametrize("bad", [0, -1, True, 1.5, "2", None])
  285. def test_expected_must_be_a_positive_int(bad):
  286. with pytest.raises(zpc.CheckError):
  287. zpc.discover(FakeAPI(), bad, "tor1", OK)
  288. @pytest.mark.parametrize("region", ["", "TOR1", "tor1/../x", "tor 1", "a" * 40, "t\n"])
  289. def test_region_is_validated_before_any_request(region):
  290. api = FakeAPI()
  291. with pytest.raises(zpc.CheckError):
  292. zpc.discover(api, 2, region, OK)
  293. assert api.calls == []
  294. def test_default_address_predicate_is_global_only():
  295. for text in ("198.51.100.10", "203.0.113.1", "10.0.0.1", "127.0.0.1", "169.254.0.1", "224.0.0.1"):
  296. assert zpc.default_address_ok(ipaddress.IPv4Address(text)) is False
  297. # ----------------------------------------------- discovery over real urllib
  298. class Site:
  299. """A loopback HTTP server whose answers come from `route(handler) -> (status, headers, body)`."""
  300. def __init__(self, route):
  301. self.hits: list[dict] = []
  302. site = self
  303. class Handler(BaseHTTPRequestHandler):
  304. def do_GET(self): # http.server API name
  305. site.hits.append({"path": self.path, "auth": self.headers.get("Authorization")})
  306. status, headers, body = route(self)
  307. self.send_response(status)
  308. for k, v in headers.items():
  309. self.send_header(k, v)
  310. self.send_header("Content-Length", str(len(body)))
  311. self.end_headers()
  312. self.wfile.write(body)
  313. def log_message(self, *args):
  314. pass
  315. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  316. self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
  317. self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
  318. self.thread.start()
  319. def close(self):
  320. self.server.shutdown()
  321. self.server.server_close()
  322. self.thread.join()
  323. @pytest.fixture
  324. def make_site():
  325. sites = []
  326. def make(route):
  327. site = Site(route)
  328. sites.append(site)
  329. return site
  330. yield make
  331. for site in sites:
  332. site.close()
  333. def json_route(api):
  334. def route(handler):
  335. parts = urllib.parse.urlsplit(handler.path)
  336. params = {k: v[0] for k, v in urllib.parse.parse_qs(parts.query).items()}
  337. return 200, {"Content-Type": "application/json"}, json.dumps(api.get(parts.path, params)).encode()
  338. return route
  339. def test_real_urllib_happy_path_sends_bearer_to_the_fixed_origin_only(make_site):
  340. api = FakeAPI(page_size=1) # forces pagination; the "next" URLs point at elsewhere.invalid
  341. site = make_site(json_route(api))
  342. transport = zpc.ApiTransport(CRED, site.url)
  343. inv = zpc.discover(transport, 2, "tor1", OK)
  344. assert [u.address for u in inv.units] == [A, B]
  345. assert site.hits and all(h["auth"] == f"Bearer {CRED}" for h in site.hits)
  346. assert all(h["path"].startswith("/v2/") for h in site.hits)
  347. def test_returned_next_url_is_never_followed(make_site):
  348. other = make_site(lambda h: (200, {}, b"{}"))
  349. api = FakeAPI(page_size=1)
  350. original = api._list
  351. def list_with_foreign_next(key, items, params, total=None):
  352. data = original(key, items, params, total)
  353. if data["links"]["pages"]:
  354. data["links"]["pages"]["next"] = other.url + "/v2/droplets?page=2"
  355. return data
  356. api._list = list_with_foreign_next
  357. site = make_site(json_route(api))
  358. zpc.discover(zpc.ApiTransport(CRED, site.url), 2, "tor1", OK)
  359. assert other.hits == []
  360. @pytest.mark.parametrize("status", [301, 302, 303, 307, 308])
  361. def test_redirect_is_refused_and_the_token_never_reaches_the_other_host(make_site, status):
  362. other = make_site(lambda h: (200, {}, b"{}"))
  363. first = make_site(lambda h: (status, {"Location": other.url + "/v2/projects"}, b""))
  364. with pytest.raises(zpc.CheckError) as info:
  365. zpc.discover(zpc.ApiTransport(CRED, first.url), 2, "tor1", OK)
  366. assert "redirect" in str(info.value)
  367. assert other.hits == [], "the redirect target was contacted"
  368. assert len(first.hits) == 1
  369. assert CRED not in str(info.value) and CRED not in repr(info.value)
  370. def test_default_urllib_would_follow_the_redirect_so_the_test_above_bites(make_site):
  371. other = make_site(lambda h: (200, {"Content-Type": "application/json"}, b"{}"))
  372. first = make_site(lambda h: (302, {"Location": other.url + "/v2/projects"}, b""))
  373. with contextlib.closing(urllib.request.build_opener().open(first.url + "/v2/projects", timeout=5)):
  374. pass
  375. assert len(other.hits) == 1
  376. def test_proxy_environment_is_ignored(make_site, monkeypatch):
  377. proxy = make_site(lambda h: (200, {}, b"{}"))
  378. site = make_site(json_route(FakeAPI()))
  379. for name in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"):
  380. monkeypatch.setenv(name, proxy.url)
  381. zpc.discover(zpc.ApiTransport(CRED, site.url), 2, "tor1", OK)
  382. assert proxy.hits == []
  383. assert site.hits
  384. def test_proxy_control_default_urllib_does_use_the_proxy(make_site, monkeypatch):
  385. proxy = make_site(lambda h: (200, {"Content-Type": "application/json"}, b"{}"))
  386. site = make_site(lambda h: (200, {}, b"{}"))
  387. monkeypatch.setenv("http_proxy", proxy.url)
  388. with contextlib.closing(urllib.request.build_opener().open(site.url + "/v2/projects", timeout=5)):
  389. pass
  390. assert proxy.hits, "without ProxyHandler({}) the proxy variable would redirect the token"
  391. @pytest.mark.parametrize("body", [
  392. b"not json", b"[]", b"3", b'{"a": 1, "a": 2}', b'{"meta": NaN}', b"\xff\xfe", b"[" * 100000,
  393. b"",
  394. ])
  395. def test_bad_bodies_are_one_typed_error(make_site, body):
  396. site = make_site(lambda h: (200, {}, body))
  397. with pytest.raises(zpc.CheckError):
  398. zpc.discover(zpc.ApiTransport(CRED, site.url), 2, "tor1", OK)
  399. def test_oversized_body_is_refused(make_site):
  400. site = make_site(lambda h: (200, {}, b'{"projects": [], "pad": "' + b"x" * 5000 + b'"}'))
  401. transport = zpc.ApiTransport(CRED, site.url, max_body=1000)
  402. with pytest.raises(zpc.CheckError, match="larger"):
  403. transport.get("/v2/projects", {})
  404. @pytest.mark.parametrize("status", [401, 403, 404, 429, 500, 503])
  405. def test_error_statuses_are_fixed_messages_without_the_body(make_site, status):
  406. site = make_site(lambda h: (status, {}, b"leaky-body-" + CRED.encode()))
  407. with pytest.raises(zpc.CheckError) as info:
  408. zpc.discover(zpc.ApiTransport(CRED, site.url), 2, "tor1", OK)
  409. assert "leaky" not in str(info.value) and CRED not in str(info.value)
  410. assert len(site.hits) == 1, "a read is not retried here: the run is simply cannot-tell"
  411. def test_connection_failure_is_a_typed_error():
  412. probe = socket.socket()
  413. probe.bind(("127.0.0.1", 0))
  414. port = probe.getsockname()[1]
  415. probe.close() # nothing listens here now
  416. with pytest.raises(zpc.CheckError):
  417. zpc.ApiTransport(CRED, f"http://127.0.0.1:{port}").get("/v2/projects", {})
  418. @pytest.mark.parametrize("base", ["http://example.invalid", "https://evil.example", "http://127.0.0.1.evil.example",
  419. "ftp://127.0.0.1", "http://localhost:80"])
  420. def test_a_non_default_origin_is_refused_unless_loopback_http(base):
  421. with pytest.raises(zpc.CheckError):
  422. zpc.ApiTransport(CRED, base)
  423. @pytest.mark.parametrize("token", ["", "short", "has space in it 123", "line\nbreak12345", "x" * 300, None, 5])
  424. def test_malformed_token_is_refused(token):
  425. with pytest.raises(zpc.CheckError):
  426. zpc.ApiTransport(token, "http://127.0.0.1:1")
  427. # ------------------------------------------------------------------- scanning
  428. def full_scan(counters, n_units=2, *, ports=range(1, zpc.MAX_PORT + 1), batch=4096, reread=None):
  429. inv = units(n_units)
  430. clock = Clock()
  431. rereads = []
  432. def default_reread():
  433. rereads.append(1)
  434. return inv
  435. acc = zpc.scan(inv, counters.connect, zpc.Budget(batch=batch), reread=reread or default_reread,
  436. clock=clock, sleep=clock.sleep, executor_factory=InlineExecutor, ports=ports)
  437. return inv, acc, rereads, clock
  438. def test_full_sweep_accounts_for_every_port_exactly_once_and_passes():
  439. counters = Counters()
  440. _inv, acc, rereads, clock = full_scan(counters)
  441. assert counters.scan == 2 * zpc.MAX_PORT
  442. assert len(set(counters.calls)) == 2 * zpc.MAX_PORT, "an attempt was repeated"
  443. assert {p for a, p in counters.calls if a == U1} == set(range(1, 65536))
  444. assert acc.unique == [zpc.MAX_PORT, zpc.MAX_PORT] and acc.duplicates == 0
  445. result = zpc.verdict(acc, 2)
  446. assert result.code == 0 and result.reasons == ()
  447. assert len(rereads) == -(-2 * zpc.MAX_PORT // 4096), "re-read after each batch, including the last"
  448. assert clock.t > 80, "the 1,500/s cap was applied on the (fake) clock"
  449. def test_loopback_listener_is_found_open_and_bound_but_not_listening_is_refused():
  450. open_sock = socket.socket()
  451. open_sock.bind(("127.0.0.1", 0))
  452. open_sock.listen(4)
  453. refused_sock = socket.socket()
  454. refused_sock.bind(("127.0.0.1", 0)) # bound, never listening: stays bound, no port-reuse race
  455. try:
  456. open_port = open_sock.getsockname()[1]
  457. refused_port = refused_sock.getsockname()[1]
  458. inv = zpc.Inventory((zpc.Unit("connector-1", "127.0.0.1", 1),))
  459. acc = zpc.scan(inv, zpc.tcp_connect, zpc.Budget(concurrency=4, rate=1e6, timeout=2.0),
  460. reread=lambda: inv, ports=sorted([open_port, refused_port]))
  461. finally:
  462. open_sock.close()
  463. refused_sock.close()
  464. assert acc.open_ports == [[open_port]]
  465. assert acc.refused_ports == [[refused_port]]
  466. result = zpc.verdict(acc, 1, 2)
  467. assert result.code == 1
  468. assert any("an answer was received" in r for r in result.reasons)
  469. def test_refusal_alone_fails_the_silence_criterion():
  470. acc = zpc.Accounting(("connector-1",))
  471. for port in range(1, 100):
  472. acc.record(0, port, zpc.TIMEOUT)
  473. acc.record(0, 100, zpc.REFUSED)
  474. result = zpc.verdict(acc, 1, 100)
  475. assert result.code == 1
  476. assert "refusal" in " ".join(result.reasons)
  477. def test_all_timeouts_are_exit_0_only_when_complete():
  478. acc = zpc.Accounting(("connector-1",))
  479. for port in range(1, 11):
  480. acc.record(0, port, zpc.TIMEOUT)
  481. assert zpc.verdict(acc, 1, 10).code == 0
  482. assert zpc.verdict(acc, 1, 11).code == 2 # one port short of what was promised
  483. assert zpc.verdict(acc, 2, 10).code == 2 # one connector fewer than expected
  484. def test_missing_final_port_is_exit_2():
  485. acc = zpc.Accounting(("connector-1",))
  486. for port in range(1, zpc.MAX_PORT):
  487. acc.record(0, port, zpc.TIMEOUT)
  488. assert zpc.verdict(acc, 1).code == 2
  489. def test_duplicated_port_is_exit_2():
  490. acc = zpc.Accounting(("connector-1",))
  491. for port in range(1, 11):
  492. acc.record(0, port, zpc.TIMEOUT)
  493. acc.record(0, 5, zpc.TIMEOUT)
  494. assert acc.duplicates == 1
  495. assert zpc.verdict(acc, 1, 10).code == 2
  496. def test_out_of_range_port_is_exit_2():
  497. acc = zpc.Accounting(("connector-1",))
  498. for port in range(1, 11):
  499. acc.record(0, port, zpc.TIMEOUT)
  500. acc.record(0, 0, zpc.TIMEOUT)
  501. acc.record(0, 70000, zpc.TIMEOUT)
  502. assert zpc.verdict(acc, 1, 10).code == 2
  503. @pytest.mark.parametrize("outcome", [zpc.LOCAL, zpc.UNREACHABLE, zpc.ERROR])
  504. def test_error_classes_are_exit_2_and_never_counted_as_timeouts(outcome):
  505. counters = Counters(outcome=lambda a, p: outcome if (a, p) == (U1, 2) else zpc.TIMEOUT)
  506. _inv, acc, _, _ = full_scan(counters, 2, ports=range(1, 5))
  507. assert acc.counts[0][zpc.TIMEOUT] == 3 and acc.counts[0][outcome] == 1
  508. assert zpc.verdict(acc, 2, 4).code == 2
  509. def test_answer_plus_error_exits_1_and_lists_both():
  510. def outcome(a, p):
  511. return {1: zpc.OPEN, 2: zpc.LOCAL}.get(p, zpc.TIMEOUT)
  512. _, acc, _, _ = full_scan(Counters(outcome=outcome), 1, ports=range(1, 5))
  513. result = zpc.verdict(acc, 1, 4)
  514. assert result.code == 1
  515. text = " ".join(result.reasons)
  516. assert "accepted a connection" in text and "local resource error" in text
  517. def test_worker_failure_is_an_error_not_a_timeout():
  518. def explode(address, port, timeout):
  519. raise RuntimeError("boom")
  520. inv = units(1)
  521. acc = zpc.scan(inv, explode, zpc.Budget(), reread=lambda: inv, executor_factory=InlineExecutor,
  522. sleep=lambda d: None, ports=range(1, 4))
  523. assert acc.counts[0][zpc.ERROR] == 3 and acc.counts[0][zpc.TIMEOUT] == 0
  524. assert zpc.verdict(acc, 1, 3).code == 2
  525. def test_bogus_outcome_from_connect_is_an_error():
  526. inv = units(1)
  527. acc = zpc.scan(inv, lambda a, p, t: "weird", zpc.Budget(), reread=lambda: inv,
  528. executor_factory=InlineExecutor, sleep=lambda d: None, ports=range(1, 4))
  529. assert acc.counts[0][zpc.ERROR] == 3
  530. def test_a_worker_that_cannot_start_is_a_local_error():
  531. class NoThreads(InlineExecutor):
  532. def submit(self, fn, *args):
  533. raise RuntimeError("can't start new thread")
  534. inv = units(1)
  535. acc = zpc.scan(inv, lambda a, p, t: zpc.TIMEOUT, zpc.Budget(), reread=lambda: inv,
  536. executor_factory=NoThreads, sleep=lambda d: None, ports=range(1, 4))
  537. assert acc.counts[0][zpc.LOCAL] == 3
  538. assert zpc.verdict(acc, 1, 3).code == 2
  539. @pytest.mark.parametrize("code, expected", [
  540. (errno.ECONNREFUSED, zpc.REFUSED), (errno.ECONNRESET, zpc.REFUSED),
  541. (errno.ETIMEDOUT, zpc.TIMEOUT),
  542. (errno.ENETUNREACH, zpc.UNREACHABLE), (errno.EHOSTUNREACH, zpc.UNREACHABLE),
  543. (errno.EMFILE, zpc.LOCAL), (errno.ENFILE, zpc.LOCAL), (errno.EADDRNOTAVAIL, zpc.LOCAL),
  544. (errno.ENOBUFS, zpc.LOCAL), (errno.ENOMEM, zpc.LOCAL),
  545. (errno.EACCES, zpc.ERROR), (None, zpc.ERROR), (errno.EPERM, zpc.ERROR),
  546. ])
  547. def test_errno_classification(code, expected):
  548. assert zpc.classify_errno(code) == expected
  549. class FakeSocket:
  550. created = 0
  551. closed = 0
  552. def __init__(self, behaviour):
  553. self.behaviour = behaviour
  554. type(self).created += 1
  555. def settimeout(self, t):
  556. if self.behaviour == "settimeout-fails":
  557. raise OSError(errno.EBADF, "x")
  558. def connect(self, address):
  559. b = self.behaviour
  560. if b == "ok":
  561. return
  562. if b == "timeout":
  563. raise TimeoutError()
  564. if isinstance(b, int):
  565. raise OSError(b, "x")
  566. def close(self):
  567. type(self).closed += 1
  568. @pytest.mark.parametrize("behaviour, expected", [
  569. ("ok", zpc.OPEN), ("timeout", zpc.TIMEOUT), (errno.ECONNREFUSED, zpc.REFUSED),
  570. (errno.EMFILE, zpc.LOCAL), (errno.EADDRNOTAVAIL, zpc.LOCAL), (errno.ENOBUFS, zpc.LOCAL),
  571. (errno.ENETUNREACH, zpc.UNREACHABLE), ("settimeout-fails", zpc.LOCAL),
  572. ])
  573. def test_sockets_are_closed_on_every_path(behaviour, expected):
  574. FakeSocket.created = FakeSocket.closed = 0
  575. result = zpc.tcp_connect("192.0.2.1", 80, 1.0, socket_factory=lambda *a: FakeSocket(behaviour))
  576. assert result == expected
  577. assert FakeSocket.created == 1 and FakeSocket.closed == 1
  578. def test_socket_creation_failure_is_a_local_error_with_nothing_to_close():
  579. def factory(*args):
  580. raise OSError(errno.EMFILE, "too many open files")
  581. assert zpc.tcp_connect("192.0.2.1", 80, 1.0, socket_factory=factory) == zpc.LOCAL
  582. def test_peak_concurrency_never_exceeds_the_budget():
  583. lock = threading.Lock()
  584. state = {"now": 0, "peak": 0}
  585. def connect(address, port, timeout):
  586. with lock:
  587. state["now"] += 1
  588. state["peak"] = max(state["peak"], state["now"])
  589. threading.Event().wait(0.002)
  590. with lock:
  591. state["now"] -= 1
  592. return zpc.TIMEOUT
  593. inv = units(1)
  594. acc = zpc.scan(inv, connect, zpc.Budget(concurrency=8, rate=1e7, batch=300), reread=lambda: inv,
  595. ports=range(1, 1201))
  596. assert acc.unique == [1200]
  597. assert 2 <= state["peak"] <= 8
  598. def test_attempt_rate_never_exceeds_the_cap_on_a_fake_clock():
  599. clock = Clock()
  600. stamps = []
  601. def connect(address, port, timeout):
  602. stamps.append(clock())
  603. return zpc.TIMEOUT
  604. inv = units(1)
  605. zpc.scan(inv, connect, zpc.Budget(rate=100.0, concurrency=4, batch=250), reread=lambda: inv,
  606. clock=clock, sleep=clock.sleep, executor_factory=InlineExecutor, ports=range(1, 1001))
  607. assert len(stamps) == 1000
  608. worst = 0
  609. left = 0
  610. for right, t in enumerate(stamps):
  611. while t - stamps[left] >= 1.0 - 1e-9:
  612. left += 1
  613. worst = max(worst, right - left + 1)
  614. assert worst <= 100, f"{worst} attempts started inside one second"
  615. assert stamps[-1] - stamps[0] >= 9.9
  616. def test_inventory_change_between_batches_discards_the_results():
  617. inv = units(2)
  618. changed = zpc.Inventory(inv.units[:1] + (zpc.Unit("connector-2", "198.51.100.99", 1002),))
  619. calls = []
  620. def reread():
  621. calls.append(1)
  622. return inv if len(calls) < 2 else changed
  623. counters = Counters()
  624. clock = Clock()
  625. with pytest.raises(zpc.InventoryChanged):
  626. zpc.scan(inv, counters.connect, zpc.Budget(batch=10), reread=reread, clock=clock,
  627. sleep=clock.sleep, executor_factory=InlineExecutor, ports=range(1, 100))
  628. assert counters.scan == 20, "the sweep stopped after the batch that saw the change"
  629. def test_inventory_change_is_exit_2_and_prints_no_results():
  630. api = FakeAPI()
  631. state = {"n": 0}
  632. original = api.get
  633. def flapping(path, params):
  634. data = original(path, params)
  635. if path == "/v2/droplets":
  636. state["n"] += 1
  637. if state["n"] > 1: # the first call is discovery; the next is the first re-read
  638. data = json.loads(json.dumps(data))
  639. data["droplets"][0]["networks"]["v4"][1]["ip_address"] = "198.51.100.77"
  640. return data
  641. api.get = flapping
  642. code, out, counters = run_main(api)
  643. assert code == 2
  644. assert "results discarded" in out and "PASS" not in out and "attempted" not in out
  645. assert counters.scan == 6
  646. def test_inventory_change_at_the_final_reread_is_detected():
  647. inv = units(1)
  648. calls = []
  649. def reread():
  650. calls.append(1)
  651. return inv if len(calls) < 1 else units(1).__class__(())
  652. with pytest.raises(zpc.InventoryChanged):
  653. zpc.scan(inv, lambda a, p, t: zpc.TIMEOUT, zpc.Budget(batch=4096), reread=reread,
  654. executor_factory=InlineExecutor, sleep=lambda d: None, ports=range(1, 4))
  655. assert len(calls) == 1
  656. def test_discovery_failure_during_a_reread_is_exit_2():
  657. api = FakeAPI()
  658. state = {"n": 0}
  659. original = api.get
  660. def failing(path, params):
  661. if path == "/v2/projects":
  662. state["n"] += 1
  663. if state["n"] > 1:
  664. raise zpc.CheckError("the API could not be reached or the connection failed")
  665. return original(path, params)
  666. api.get = failing
  667. code, out, _ = run_main(api)
  668. assert code == 2 and "PASS" not in out
  669. def test_interrupt_is_exit_2_and_discards_results():
  670. def interrupted(delay):
  671. raise KeyboardInterrupt
  672. code, out, _ = run_main(FakeAPI(), budget=zpc.Budget(concurrency=4, rate=1.0, batch=4096),
  673. sleep=interrupted)
  674. assert code == 2 and "interrupted" in out and "PASS" not in out and "attempted" not in out
  675. def test_low_file_limit_is_cannot_tell_before_any_request():
  676. api = FakeAPI()
  677. code, out, counters = run_main(api, getrlimit=lambda which: (100, 4096), budget=zpc.Budget(concurrency=512))
  678. assert code == 2 and "open-file limit" in out
  679. assert api.calls == [] and counters.scan == 0
  680. with pytest.raises(zpc.CheckError):
  681. zpc.check_nofile(512, lambda which: (512, 512))
  682. zpc.check_nofile(512, lambda which: (4096, 4096))
  683. # ----------------------------------------------------------------- main, e2e
  684. def test_main_pass_prints_only_labels_counts_and_fixed_strings():
  685. code, out, counters = run_main(FakeAPI())
  686. assert code == 0
  687. assert counters.control == 1 and counters.scan == 6
  688. assert "connector-1: attempted 3, timeouts 3, answers 0, errors 0" in out
  689. assert "TCP only; observed from this network only" in out
  690. assert "verdict: PASS" in out
  691. for secret in (A, B, CRED, "198.51.100", "1001"):
  692. assert secret not in out
  693. def test_main_answer_is_exit_1_and_names_port_numbers_only():
  694. counters = Counters(outcome=lambda a, p: zpc.REFUSED if (a, p) == (A, 2) else zpc.TIMEOUT)
  695. code, out, _ = run_main(FakeAPI(), counters=counters)
  696. assert code == 1
  697. assert "connector-1: ports that answered with a refusal: 2" in out
  698. assert "an answer was received" in out
  699. assert A not in out
  700. def test_main_real_threads_and_loopback_listener_end_to_end():
  701. listener = socket.socket()
  702. listener.bind(("127.0.0.1", 0))
  703. listener.listen(4)
  704. try:
  705. port = listener.getsockname()[1]
  706. api = FakeAPI(tagged=[droplet(1001, "127.0.0.1")], project_droplets=[1001])
  707. def control(host, p, timeout):
  708. with socket.create_connection(("127.0.0.1", port), timeout):
  709. pass
  710. out = io.StringIO()
  711. code = zpc.main(
  712. ["--expect-connectors", "1"], env={"DIGITALOCEAN_TOKEN": CRED}, stdout=out,
  713. hooks=zpc.Hooks(address_ok=lambda a: True, control_connect=control, ports=[port],
  714. transport_factory=lambda t: api,
  715. budget=zpc.Budget(concurrency=4, rate=1e6)))
  716. finally:
  717. listener.close()
  718. assert code == 1
  719. assert f"connector-1: open ports: {port}" in out.getvalue()
  720. def test_positive_control_failure_is_cannot_tell_with_zero_scan_connects():
  721. def refuse(host, port, timeout):
  722. raise OSError(errno.ECONNREFUSED, "x")
  723. counters = Counters()
  724. code, out, _ = run_main(FakeAPI(), counters=counters, control_connect=refuse)
  725. assert code == 2 and "positive control" in out and counters.scan == 0
  726. def test_missing_token_is_exit_2_before_any_request():
  727. api = FakeAPI()
  728. out = io.StringIO()
  729. code = zpc.main(["--expect-connectors", "2"], env={}, stdout=out,
  730. hooks=zpc.Hooks(address_ok=OK, ports=range(1, 4)))
  731. assert code == 2 and "token" in out.getvalue()
  732. assert api.calls == []
  733. def test_unreachable_target_network_is_exit_2():
  734. counters = Counters(outcome=zpc.UNREACHABLE)
  735. code, out, _ = run_main(FakeAPI(), counters=counters)
  736. assert code == 2 and "unreachable" in out
  737. # ---------------------------------------------------------------- the token
  738. def _every_path_output():
  739. outputs = []
  740. paths = [
  741. lambda: run_main(FakeAPI()),
  742. lambda: run_main(FakeAPI(), counters=Counters(outcome=zpc.OPEN)),
  743. lambda: run_main(FakeAPI(tagged=[])),
  744. lambda: run_main(FakeAPI(), counters=Counters(outcome=zpc.LOCAL)),
  745. ]
  746. for path in paths:
  747. outputs.append(path()[1])
  748. return outputs
  749. def test_token_never_appears_in_any_output():
  750. for out in _every_path_output():
  751. assert CRED not in out
  752. def test_token_never_appears_in_exception_text_repr_or_traceback(make_site):
  753. for status in (401, 500):
  754. site = make_site(lambda h, s=status: (s, {}, b"x"))
  755. transport = zpc.ApiTransport(CRED, site.url)
  756. with pytest.raises(zpc.CheckError) as info:
  757. transport.get("/v2/projects", {})
  758. blob = "".join(traceback.format_exception(info.value))
  759. for text in (str(info.value), repr(info.value), repr(info.value.args), blob):
  760. assert CRED not in text
  761. assert CRED not in repr(transport) and CRED not in repr(vars(transport))
  762. with pytest.raises(zpc.CheckError) as info:
  763. zpc.ApiTransport("bad token", "http://127.0.0.1:1")
  764. assert "bad token" not in str(info.value)
  765. def test_token_is_not_in_the_report_and_no_child_process_exists(tmp_path, monkeypatch):
  766. def forbidden(*args, **kwargs):
  767. raise AssertionError("a child process was started")
  768. monkeypatch.setattr(subprocess.Popen, "__init__", forbidden)
  769. for name in ("system", "fork", "execv", "execve", "posix_spawn", "popen"):
  770. if hasattr(os, name):
  771. monkeypatch.setattr(os, name, forbidden)
  772. before = dict(os.environ)
  773. report = tmp_path / "report.txt"
  774. code, _out, _ = run_main(FakeAPI(), argv=["--out", str(report)])
  775. assert code == 0
  776. assert CRED not in report.read_text() and A not in report.read_text()
  777. assert dict(os.environ) == before, "the script must not export the token or any variable"
  778. def test_script_source_spawns_nothing_and_reads_only_the_token_variable():
  779. tree = ast.parse(SCRIPT.read_text())
  780. imported = set()
  781. for node in ast.walk(tree):
  782. if isinstance(node, ast.Import):
  783. imported |= {a.name.split(".")[0] for a in node.names}
  784. elif isinstance(node, ast.ImportFrom):
  785. imported.add((node.module or "").split(".")[0])
  786. assert not imported & {"subprocess", "pty", "multiprocessing", "ctypes", "shlex", "pickle"}
  787. names = {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
  788. assert not names & {"system", "popen", "fork", "execv", "execve", "execvp", "posix_spawn",
  789. "spawnv", "putenv", "unsetenv", "getenv", "Popen"}
  790. environ_uses = [n for n in ast.walk(tree) if isinstance(n, ast.Attribute) and n.attr == "environ"]
  791. assert len(environ_uses) == 1, "os.environ is read once, as the default for the env parameter"
  792. gets = [n for n in ast.walk(tree) if isinstance(n, ast.Call)
  793. and isinstance(n.func, ast.Attribute) and n.func.attr == "get"
  794. and isinstance(n.func.value, ast.Name) and n.func.value.id == "env"]
  795. assert len(gets) == 1 and gets[0].args[0].id == "TOKEN_ENV"
  796. assert zpc.TOKEN_ENV == "DIGITALOCEAN_TOKEN"
  797. # -------------------------------------------------- no way to give an address
  798. FORBIDDEN_WORDS = {"host", "hosts", "hostname", "addr", "address", "addresses", "ip", "ips", "target",
  799. "targets", "file", "files", "url", "uri", "cidr", "range", "input", "list", "domain",
  800. "net", "network", "subnet", "from", "source", "inventory"}
  801. def forbidden_options(parser):
  802. bad = []
  803. for action in parser._actions:
  804. for opt in action.option_strings:
  805. words = set(opt.lstrip("-").lower().split("-"))
  806. if words & FORBIDDEN_WORDS:
  807. bad.append(opt)
  808. if not action.option_strings and action.dest != "help":
  809. bad.append(action.dest) # a positional
  810. return bad
  811. def test_no_option_can_name_a_host_address_target_or_file():
  812. parser = zpc.build_parser()
  813. assert forbidden_options(parser) == []
  814. allowed = {"-h", "--help", "--expect-connectors", "--region", "--resource-key", "--out"}
  815. assert {o for a in parser._actions for o in a.option_strings} == allowed
  816. def test_the_option_guard_bites():
  817. import argparse
  818. for name in ("--target", "--host", "--addresses", "--targets-file", "--ip", "--cidr", "--input-file"):
  819. parser = argparse.ArgumentParser()
  820. parser.add_argument(name)
  821. assert forbidden_options(parser) == [name]
  822. parser = argparse.ArgumentParser()
  823. parser.add_argument("where")
  824. assert forbidden_options(parser) == ["where"]
  825. def test_a_positional_address_is_rejected_by_the_parser():
  826. counters = Counters()
  827. with pytest.raises(SystemExit) as info:
  828. zpc.main(["--expect-connectors", "1", "198.51.100.10"], env={"DIGITALOCEAN_TOKEN": CRED},
  829. hooks=zpc.Hooks(), stdout=io.StringIO())
  830. assert info.value.code == 2 and counters.scan == 0
  831. def test_other_environment_variables_cannot_supply_a_target():
  832. env = {"DIGITALOCEAN_TOKEN": CRED, "TARGET": "198.51.100.99", "TARGETS": "198.51.100.99",
  833. "HOST": "198.51.100.99", "ZERO_PORTS_TARGET": "198.51.100.99"}
  834. code, _out, counters = run_main(FakeAPI(), env=env)
  835. assert code == 0
  836. assert "198.51.100.99" not in {a for a, _ in counters.calls}
  837. @pytest.mark.parametrize("flag", ["--target", "--host", "--address", "--file", "--ip"])
  838. def test_unknown_address_like_flags_are_rejected(flag):
  839. with pytest.raises(SystemExit) as info:
  840. zpc.main(["--expect-connectors", "1", flag, "198.51.100.10"], env={}, stdout=io.StringIO())
  841. assert info.value.code == 2
  842. def test_expect_connectors_is_required_and_at_least_one():
  843. with pytest.raises(SystemExit):
  844. zpc.main([], env={}, stdout=io.StringIO())
  845. code, _out, counters = run_main(FakeAPI(), expected=0)
  846. assert code == 2 and counters.scan == 0
  847. def test_cli_without_a_token_exits_2_and_help_exits_0():
  848. env = {"PATH": os.environ.get("PATH", "")}
  849. run = subprocess.run([sys.executable, "-I", str(SCRIPT), "--expect-connectors", "1"],
  850. capture_output=True, text=True, env=env, timeout=60, check=False)
  851. assert run.returncode == 2 and "token" in run.stdout
  852. helped = subprocess.run([sys.executable, "-I", str(SCRIPT), "--help"],
  853. capture_output=True, text=True, env=env, timeout=60, check=False)
  854. assert helped.returncode == 0 and "--expect-connectors" in helped.stdout
  855. # --------------------------------------------------------------------- report
  856. def test_report_is_mode_0600_matches_the_console_and_is_not_overwritten(tmp_path):
  857. report = tmp_path / "r.txt"
  858. code, out, _ = run_main(FakeAPI(), argv=["--out", str(report)])
  859. assert code == 0
  860. assert stat.S_IMODE(report.stat().st_mode) == 0o600
  861. assert report.read_text() == out
  862. api = FakeAPI()
  863. code2, out2, counters = run_main(api, argv=["--out", str(report)])
  864. assert code2 == 2 and "not overwriting" in out2
  865. assert api.calls == [] and counters.scan == 0, "refused before any network use"
  866. assert report.read_text() == out, "the earlier report is untouched"
  867. def test_report_inside_the_repository_is_refused(tmp_path, monkeypatch):
  868. # A stand-in repository under tmp_path: a failing guard must never write into the real tree.
  869. fake_repo = tmp_path / "repo"
  870. fake_repo.mkdir()
  871. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  872. inside = fake_repo / "zero-ports-report-test.txt"
  873. api = FakeAPI()
  874. code, out, _ = run_main(api, argv=["--out", str(inside)])
  875. assert code == 2 and "inside the repository" in out
  876. assert not inside.exists() and api.calls == []
  877. def test_report_in_a_missing_directory_is_refused(tmp_path):
  878. code, _out, _ = run_main(FakeAPI(), argv=["--out", str(tmp_path / "nope" / "r.txt")])
  879. assert code == 2
  880. def test_symlink_report_path_is_not_followed(tmp_path):
  881. target = tmp_path / "victim"
  882. link = tmp_path / "link"
  883. link.symlink_to(target)
  884. code, _out, _ = run_main(FakeAPI(), argv=["--out", str(link)])
  885. assert code == 2 and not target.exists()
  886. def test_symlinked_parent_leading_outside_the_repo_is_refused(tmp_path):
  887. real = tmp_path / "real"
  888. real.mkdir()
  889. (tmp_path / "linkdir").symlink_to(real)
  890. code, _out, _ = run_main(FakeAPI(), argv=["--out", str(tmp_path / "linkdir" / "r.txt")])
  891. assert code == 2 and not (real / "r.txt").exists()
  892. def test_failure_to_write_the_report_is_exit_2(tmp_path, monkeypatch):
  893. def broken(path, lines):
  894. raise zpc.CheckError("the report could not be written")
  895. monkeypatch.setattr(zpc, "write_report", broken)
  896. code, out, _ = run_main(FakeAPI(), argv=["--out", str(tmp_path / "r.txt")])
  897. assert code == 2 and "report could not be written" in out and "PASS" not in out
  898. def test_failure_to_write_never_hides_an_answer(tmp_path, monkeypatch):
  899. monkeypatch.setattr(zpc, "write_report", lambda p, l: (_ for _ in ()).throw(zpc.CheckError("x")))
  900. code, out, _ = run_main(FakeAPI(), counters=Counters(outcome=zpc.OPEN),
  901. argv=["--out", str(tmp_path / "r.txt")])
  902. assert code == 1 and "report could not be written" in out
  903. def test_report_write_really_fails_on_a_read_only_directory(tmp_path):
  904. if os.geteuid() == 0:
  905. pytest.skip("root ignores directory permissions")
  906. ro = tmp_path / "ro"
  907. ro.mkdir()
  908. ro.chmod(0o500)
  909. try:
  910. code, out, _ = run_main(FakeAPI(), argv=["--out", str(ro / "r.txt")])
  911. finally:
  912. ro.chmod(0o700)
  913. assert code == 2 and "PASS" not in out
  914. # ----------------------------------------------------------------------- docs
  915. def test_docs_give_the_full_command_with_doppler_and_the_limits():
  916. guide = (ROOT / "docs" / "stages" / "01-access.md").read_text()
  917. assert "doppler run -- python3 -I scripts/zero_ports_check.py --expect-connectors 2" in guide
  918. for phrase in ("second network", "UDP", "do not destroy", "exit 0", "exit 1", "exit 2"):
  919. assert phrase.lower() in guide.lower(), phrase
  920. wiki = (ROOT / "docs" / "wiki" / "Droplet-Hardening.md").read_text()
  921. assert "zero_ports_check" in wiki and "does not prove" in wiki.lower()
  922. for text in (guide, wiki):
  923. assert not any(tok in text for tok in ("DIGITALOCEAN_TOKEN=do", "dop_v1"))
  924. # ===================================================================== fix round 1
  925. # Finding 1: a TimeoutError outside the connect call is a setup failure, never a "no answer".
  926. class FaultSocket:
  927. """A socket whose setup, connect or close raises on demand."""
  928. def __init__(self, fault):
  929. self.fault = fault
  930. self.closed = 0
  931. def settimeout(self, t):
  932. if self.fault == "settimeout":
  933. raise TimeoutError("setup failed")
  934. def connect(self, address):
  935. if self.fault == "close-after-open":
  936. return
  937. if self.fault == "close-after-refusal":
  938. raise ConnectionRefusedError(errno.ECONNREFUSED, "x")
  939. raise TimeoutError() # a real connect timeout (the close then fails too)
  940. def close(self):
  941. self.closed += 1
  942. if self.fault.startswith("close-after") or self.fault == "close-after-timeout":
  943. raise TimeoutError("close failed")
  944. def _factory_for(fault):
  945. if fault == "factory":
  946. def broken(*args):
  947. raise TimeoutError("socket setup failed")
  948. return broken
  949. return lambda *args: FaultSocket(fault)
  950. SETUP_FAULTS = ["factory", "settimeout", "close-after-timeout"]
  951. ANSWER_THEN_CLOSE_FAULTS = {
  952. "close-after-open": (zpc.OPEN_CLEANUP, zpc.OPEN),
  953. "close-after-refusal": (zpc.REFUSED_CLEANUP, zpc.REFUSED),
  954. }
  955. @pytest.mark.parametrize("fault", SETUP_FAULTS)
  956. def test_timeouterror_outside_connect_is_a_local_error_not_a_timeout(fault):
  957. outcome = zpc.tcp_connect("198.51.100.1", 1, 2, socket_factory=_factory_for(fault))
  958. assert outcome == zpc.LOCAL
  959. @pytest.mark.parametrize("fault", SETUP_FAULTS)
  960. def test_setup_fault_on_every_port_is_exit_2_never_0(fault):
  961. inv = units(1)
  962. factory = _factory_for(fault)
  963. clock = Clock()
  964. ports = range(1, 200) # the fault handling does not depend on the range; the full sweep has its own tests (#527)
  965. acc = zpc.scan(
  966. inv, lambda a, p, t: zpc.tcp_connect(a, p, t, socket_factory=factory),
  967. zpc.Budget(), reread=lambda: inv, clock=clock, sleep=clock.sleep,
  968. executor_factory=InlineExecutor, ports=ports,
  969. )
  970. assert acc.unique == [len(ports)]
  971. assert acc.counts[0][zpc.TIMEOUT] == 0
  972. assert zpc.verdict(acc, 1, len(ports)).code == 2
  973. @pytest.mark.parametrize("fault", sorted(ANSWER_THEN_CLOSE_FAULTS))
  974. def test_a_close_failure_after_an_answer_keeps_the_answer(fault):
  975. tagged, base = ANSWER_THEN_CLOSE_FAULTS[fault]
  976. assert zpc.tcp_connect("198.51.100.1", 1, 2, socket_factory=_factory_for(fault)) == tagged
  977. inv = units(1)
  978. factory = _factory_for(fault)
  979. acc = zpc.scan(
  980. inv, lambda a, p, t: zpc.tcp_connect(a, p, t, socket_factory=factory),
  981. zpc.Budget(), reread=lambda: inv, executor_factory=InlineExecutor,
  982. sleep=lambda d: None, ports=range(1, 4),
  983. )
  984. assert acc.counts[0][base] == 3 and acc.counts[0][zpc.LOCAL] == 0
  985. assert acc.cleanup_problems == [3]
  986. result = zpc.verdict(acc, 1, 3)
  987. assert result.code == 1, "an answer plus an error stays exit 1"
  988. assert any("cleanup" in r for r in result.reasons)
  989. lines = zpc.render(acc, result, zpc.Budget(), 1, 1)
  990. assert any("cleanup problems: 3" in line for line in lines)
  991. def test_a_close_failure_after_a_timeout_still_prevents_pass():
  992. acc = zpc.Accounting(("connector-1",))
  993. for port in range(1, 4):
  994. acc.record(0, port, zpc.LOCAL)
  995. assert zpc.verdict(acc, 1, 3).code == 2
  996. def test_a_real_connect_timeout_is_still_a_timeout_and_the_socket_is_closed():
  997. sock = FaultSocket("timeout")
  998. sock.fault = "timeout"
  999. assert zpc.tcp_connect("198.51.100.1", 1, 2, socket_factory=lambda *a: sock) == zpc.TIMEOUT
  1000. assert sock.closed == 1
  1001. # Finding 2: the token must not be reachable through exception chaining.
  1002. def exception_chain(exc):
  1003. seen, stack, out = set(), [exc], []
  1004. while stack:
  1005. e = stack.pop()
  1006. if e is None or id(e) in seen:
  1007. continue
  1008. seen.add(id(e))
  1009. out.append(e)
  1010. stack.extend([e.__cause__, e.__context__])
  1011. return out
  1012. def assert_chain_is_clean(exc, *secrets):
  1013. chain = exception_chain(exc)
  1014. assert chain
  1015. for e in chain:
  1016. for text in (str(e), repr(e), repr(e.args)):
  1017. for secret in secrets:
  1018. assert secret not in text, f"{type(e).__name__} carries a secret"
  1019. assert exc.__cause__ is None and exc.__context__ is None, "a sanitized error keeps no chain"
  1020. @pytest.mark.parametrize("token", [CRED + "\n", CRED + " ", "\t" + CRED, CRED + "\r\n", CRED + "\x00"])
  1021. def test_token_with_whitespace_or_control_characters_is_refused_with_a_clean_chain(token):
  1022. with pytest.raises(zpc.CheckError) as info:
  1023. zpc.ApiTransport(token, "http://127.0.0.1:1")
  1024. assert_chain_is_clean(info.value, CRED)
  1025. def test_urlerror_carrying_the_token_leaves_no_chain():
  1026. class Opener:
  1027. def open(self, req, timeout=None):
  1028. raise urllib.error.URLError(CRED)
  1029. transport = zpc.ApiTransport(CRED, "http://127.0.0.1:1")
  1030. transport._opener = Opener()
  1031. with pytest.raises(zpc.CheckError) as info:
  1032. transport.get("/v2/projects", {})
  1033. assert_chain_is_clean(info.value, CRED)
  1034. def test_valueerror_carrying_the_header_leaves_no_chain():
  1035. class Opener:
  1036. def open(self, req, timeout=None):
  1037. raise ValueError("Invalid header value " + req.get_header("Authorization", "?"))
  1038. transport = zpc.ApiTransport(CRED, "http://127.0.0.1:1")
  1039. transport._opener = Opener()
  1040. with pytest.raises(zpc.CheckError) as info:
  1041. transport.get("/v2/projects", {})
  1042. assert_chain_is_clean(info.value, CRED)
  1043. def test_http_error_with_a_body_leaves_no_chain(make_site):
  1044. body = b"leaky-body-" + CRED.encode()
  1045. for status in (302, 401, 500):
  1046. site = make_site(lambda h, s=status: (s, {"Location": "http://127.0.0.1:1/x"}, body))
  1047. with pytest.raises(zpc.CheckError) as info:
  1048. zpc.ApiTransport(CRED, site.url).get("/v2/projects", {})
  1049. assert_chain_is_clean(info.value, CRED, "leaky-body")
  1050. def test_json_parse_failure_with_token_like_text_leaves_no_chain(make_site):
  1051. for body in (b'{"x": ' + CRED.encode() + b"}", b"\xff" + CRED.encode(), b'{"a":1,"a":2,"t":"' + CRED.encode() + b'"}'):
  1052. site = make_site(lambda h, b=body: (200, {}, b))
  1053. with pytest.raises(zpc.CheckError) as info:
  1054. zpc.ApiTransport(CRED, site.url).get("/v2/projects", {})
  1055. assert_chain_is_clean(info.value, CRED, "SECRET")
  1056. def test_connection_failure_leaves_no_chain():
  1057. probe = socket.socket()
  1058. probe.bind(("127.0.0.1", 0))
  1059. port = probe.getsockname()[1]
  1060. probe.close()
  1061. with pytest.raises(zpc.CheckError) as info:
  1062. zpc.ApiTransport(CRED, f"http://127.0.0.1:{port}").get("/v2/projects", {})
  1063. assert_chain_is_clean(info.value, CRED)
  1064. @pytest.mark.parametrize("value", ["999.1.1.1", "1.2.3", "not an ip", "::ffff:198.51.100.10"])
  1065. def test_address_parse_failure_leaves_no_chain(value):
  1066. with pytest.raises(zpc.CheckError) as info:
  1067. zpc.parse_public_ipv4(value, OK)
  1068. assert_chain_is_clean(info.value, value)
  1069. def test_positive_control_failure_leaves_no_chain():
  1070. def refuse(host, port, timeout):
  1071. raise OSError(errno.ECONNREFUSED, "secret-detail")
  1072. hooks = zpc.Hooks(control_connect=refuse)
  1073. with pytest.raises(zpc.CheckError) as info:
  1074. zpc.positive_control(hooks)
  1075. assert_chain_is_clean(info.value, "secret-detail")
  1076. def test_report_write_failure_leaves_no_chain(tmp_path):
  1077. target = zpc.check_out_path(str(tmp_path / "r.txt"))
  1078. (tmp_path / "r.txt").write_text("already")
  1079. try:
  1080. with pytest.raises(zpc.CheckError) as info:
  1081. zpc.write_report(target, ["x"])
  1082. finally:
  1083. zpc.close_report_target(target)
  1084. assert_chain_is_clean(info.value, str(tmp_path))
  1085. @pytest.mark.parametrize("region", ["tor1\n", "tor1 ", " tor1"])
  1086. def test_region_with_trailing_whitespace_is_refused(region):
  1087. api = FakeAPI()
  1088. with pytest.raises(zpc.CheckError):
  1089. zpc.discover(api, 2, region, OK)
  1090. assert api.calls == []
  1091. def test_project_id_and_urn_with_trailing_newline_are_refused():
  1092. with pytest.raises(zpc.CheckError):
  1093. zpc.discover(FakeAPI(projects=[{"id": "abc\n", "name": zpc.PROJECT_NAME}]), 2, "tor1", OK)
  1094. api = FakeAPI()
  1095. api.resources = [{"urn": "do:droplet:1001\n"}, {"urn": "do:droplet:1002"}]
  1096. with pytest.raises(zpc.CheckError): # 1001 is tagged but its project urn does not match
  1097. zpc.discover(api, 2, "tor1", OK)
  1098. # Finding 3: the cap applies to connect starts, not to submissions.
  1099. class DelayedExecutor:
  1100. """Queues submissions and releases them all at once on real threads."""
  1101. def __init__(self, max_workers=None, release_at=4):
  1102. self.release_at = release_at
  1103. self.pending = []
  1104. self.threads = []
  1105. def submit(self, fn, *args):
  1106. fut = concurrent.futures.Future()
  1107. self.pending.append((fut, fn, args))
  1108. if len(self.pending) == self.release_at:
  1109. barrier = threading.Barrier(self.release_at)
  1110. def go(f, func, a):
  1111. barrier.wait(5)
  1112. try:
  1113. f.set_result(func(*a))
  1114. except (RuntimeError, OSError, ValueError) as exc:
  1115. f.set_exception(exc)
  1116. for f, func, a in self.pending:
  1117. t = threading.Thread(target=go, args=(f, func, a))
  1118. t.start()
  1119. self.threads.append(t)
  1120. self.pending = []
  1121. return fut
  1122. def shutdown(self, wait=True, cancel_futures=False):
  1123. for t in self.threads:
  1124. t.join(10)
  1125. def test_rate_cap_holds_for_connect_starts_with_delayed_real_threads():
  1126. import time
  1127. stamps = []
  1128. lock = threading.Lock()
  1129. def connect(address, port, timeout):
  1130. with lock:
  1131. stamps.append(time.monotonic())
  1132. return zpc.TIMEOUT
  1133. inv = units(1)
  1134. zpc.scan(inv, connect, zpc.Budget(concurrency=4, rate=20.0, batch=4), reread=lambda: inv,
  1135. executor_factory=DelayedExecutor, ports=range(1, 5))
  1136. stamps.sort()
  1137. assert len(stamps) == 4
  1138. gaps = [b - a for a, b in itertools.pairwise(stamps)]
  1139. assert min(gaps) >= 0.045, f"connect starts bunched: {gaps}"
  1140. def test_rate_limiter_is_thread_safe_on_real_threads():
  1141. import time
  1142. limiter = zpc._RateLimiter(50.0, time.monotonic, time.sleep)
  1143. stamps = []
  1144. lock = threading.Lock()
  1145. def work():
  1146. limiter.wait()
  1147. with lock:
  1148. stamps.append(time.monotonic())
  1149. threads = [threading.Thread(target=work) for _ in range(6)]
  1150. for t in threads:
  1151. t.start()
  1152. for t in threads:
  1153. t.join()
  1154. stamps.sort()
  1155. assert min(b - a for a, b in itertools.pairwise(stamps)) >= 0.015
  1156. # Finding 4: the report parent directory cannot be swapped between validation and write.
  1157. def test_swapping_the_parent_for_a_symlink_into_the_repo_does_not_write_there(tmp_path, monkeypatch):
  1158. fake_repo = tmp_path / "repo"
  1159. fake_repo.mkdir()
  1160. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1161. safe = tmp_path / "safe"
  1162. safe.mkdir()
  1163. target = zpc.check_out_path(str(safe / "r.txt"))
  1164. try:
  1165. safe.rename(tmp_path / "moved")
  1166. safe.symlink_to(fake_repo)
  1167. zpc.write_report(target, ["line"])
  1168. finally:
  1169. zpc.close_report_target(target)
  1170. assert not (fake_repo / "r.txt").exists(), "the report landed inside the repository"
  1171. assert (tmp_path / "moved" / "r.txt").read_text() == "line\n"
  1172. assert stat.S_IMODE((tmp_path / "moved" / "r.txt").stat().st_mode) == 0o600
  1173. def test_a_parent_that_is_a_symlink_into_the_repo_is_refused(tmp_path, monkeypatch):
  1174. fake_repo = tmp_path / "repo"
  1175. (fake_repo / "docs").mkdir(parents=True)
  1176. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1177. link = tmp_path / "link"
  1178. link.symlink_to(fake_repo)
  1179. with pytest.raises(zpc.CheckError):
  1180. zpc.check_out_path(str(link / "r.txt"))
  1181. # an intermediate symlink: the physical parent is repo/docs
  1182. with pytest.raises(zpc.CheckError):
  1183. zpc.check_out_path(str(link / "docs" / "r.txt"))
  1184. assert not (fake_repo / "r.txt").exists()
  1185. def test_a_parent_directly_inside_or_at_the_repo_is_refused_and_outside_is_allowed(tmp_path, monkeypatch):
  1186. fake_repo = tmp_path / "repo"
  1187. (fake_repo / "a" / "b").mkdir(parents=True)
  1188. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1189. for inside in (fake_repo, fake_repo / "a", fake_repo / "a" / "b"):
  1190. with pytest.raises(zpc.CheckError):
  1191. zpc.check_out_path(str(inside / "r.txt"))
  1192. outside = tmp_path / "out"
  1193. outside.mkdir()
  1194. target = zpc.check_out_path(str(outside / "r.txt"))
  1195. zpc.close_report_target(target)
  1196. @pytest.mark.parametrize("name", ["", ".", ".."])
  1197. def test_report_path_without_a_file_name_is_refused(tmp_path, name):
  1198. with pytest.raises(zpc.CheckError):
  1199. zpc.check_out_path(str(tmp_path) + "/" + name)
  1200. # Finding 5: the production workload is 65,535 ports per unit, independent of the generated range.
  1201. def test_production_hooks_use_the_full_range_and_a_run_requires_it():
  1202. assert zpc.Hooks().ports is None, "an override must be explicit"
  1203. assert zpc.Hooks().effective_ports() == range(1, 65536)
  1204. assert zpc.ALL_PORTS == range(1, 65536) and zpc.MAX_PORT == 65535
  1205. def test_main_without_a_ports_override_attempts_all_65535_ports_per_unit():
  1206. api = FakeAPI(tagged=[droplet(1001, A)], project_droplets=[1001])
  1207. counters = Counters()
  1208. clock = Clock()
  1209. hooks = zpc.Hooks(address_ok=OK, connect=counters.connect, control_connect=counters.control_connect,
  1210. transport_factory=lambda t: api, executor_factory=InlineExecutor,
  1211. clock=clock, sleep=clock.sleep)
  1212. out = io.StringIO()
  1213. code = zpc.main(["--expect-connectors", "1"], env={"DIGITALOCEAN_TOKEN": CRED}, hooks=hooks, stdout=out)
  1214. assert code == 0, out.getvalue()
  1215. assert sorted(p for _, p in counters.calls) == list(range(1, 65536))
  1216. assert "attempted 65535" in out.getvalue()
  1217. def test_a_shrunken_production_range_cannot_pass(monkeypatch):
  1218. monkeypatch.setattr(zpc, "ALL_PORTS", range(1, zpc.MAX_PORT))
  1219. api = FakeAPI(tagged=[droplet(1001, A)], project_droplets=[1001])
  1220. clock = Clock()
  1221. counters = Counters()
  1222. hooks = zpc.Hooks(address_ok=OK, connect=counters.connect, control_connect=counters.control_connect,
  1223. transport_factory=lambda t: api, executor_factory=InlineExecutor,
  1224. clock=clock, sleep=clock.sleep)
  1225. out = io.StringIO()
  1226. code = zpc.main(["--expect-connectors", "1"], env={"DIGITALOCEAN_TOKEN": CRED}, hooks=hooks, stdout=out)
  1227. assert code == 2 and "PASS" not in out.getvalue()
  1228. # ------------------------------------------------------------------ extra audit
  1229. PRODUCTION_REFUSED = [
  1230. "::ffff:8.8.8.8", "01.2.3.4", "08.8.8.8", "8.8.8.08", "8.8.8.8 ", " 8.8.8.8", "8.8.8.8\n", "8.8.8.8\x00",
  1231. "8.8.8.8", "8.8.8.8/32", "8.8.8", "8.8.8.8.8", "134744072", "0x08080808",
  1232. "0x8.0x8.0x8.0x8", "010.8.8.8", "8.8.8.256", "-8.8.8.8", "+8.8.8.8", "", "localhost",
  1233. "100.64.0.1", "100.127.255.255", "198.18.0.1", "198.19.255.255",
  1234. "192.0.2.1", "198.51.100.1", "203.0.113.1",
  1235. "0.0.0.0", "0.1.2.3", "240.0.0.1", "255.255.255.255", "224.0.0.1", "239.255.255.255",
  1236. "10.0.0.1", "172.16.0.1", "192.168.1.1", "127.0.0.1", "169.254.169.254", "192.0.0.1",
  1237. ]
  1238. @pytest.mark.parametrize("value", PRODUCTION_REFUSED)
  1239. def test_production_predicate_refuses_every_odd_spelling_and_special_range(value):
  1240. with pytest.raises(zpc.CheckError):
  1241. zpc.parse_public_ipv4(value, zpc.default_address_ok)
  1242. @pytest.mark.parametrize("value", [None, 134744072, 134744072.0, True, b"8.8.8.8", ["8.8.8.8"], {"a": 1}])
  1243. def test_production_predicate_refuses_non_strings(value):
  1244. with pytest.raises(zpc.CheckError):
  1245. zpc.parse_public_ipv4(value, zpc.default_address_ok)
  1246. def test_production_predicate_accepts_a_plain_public_address():
  1247. # A well-known public resolver address, only parsed here; no connection is ever made to it.
  1248. assert zpc.parse_public_ipv4("8.8.8.8", zpc.default_address_ok) == "8.8.8.8"
  1249. def test_argparse_errors_never_echo_the_environment_or_the_token():
  1250. env = {"PATH": os.environ.get("PATH", ""), "DIGITALOCEAN_TOKEN": CRED}
  1251. # Both invocations fail inside argparse, before the token is read or any request is built.
  1252. for args in (["--expect-connectors", "abc"], ["--bogus"], []):
  1253. run = subprocess.run([sys.executable, "-I", str(SCRIPT), *args],
  1254. capture_output=True, text=True, env=env, timeout=60, check=False)
  1255. assert run.returncode == 2
  1256. assert CRED not in run.stdout and CRED not in run.stderr and "SECRET" not in run.stderr
  1257. def open_fd_count():
  1258. return len(os.listdir("/proc/self/fd"))
  1259. def test_no_descriptors_leak_on_discovery_scan_and_report_failures(make_site, tmp_path):
  1260. site500 = make_site(lambda h: (500, {}, b"x"))
  1261. site302 = make_site(lambda h: (302, {"Location": "http://127.0.0.1:1/"}, b""))
  1262. sitejson = make_site(lambda h: (200, {}, b"not json"))
  1263. api = FakeAPI()
  1264. before = open_fd_count()
  1265. for _ in range(25):
  1266. for site in (site500, site302, sitejson):
  1267. with pytest.raises(zpc.CheckError):
  1268. zpc.ApiTransport(CRED, site.url).get("/v2/projects", {})
  1269. # report target opened then never written, then closed; and a write that fails
  1270. target = zpc.check_out_path(str(tmp_path / "leak.txt"))
  1271. (tmp_path / "leak.txt").write_text("x")
  1272. with pytest.raises(zpc.CheckError):
  1273. zpc.write_report(target, ["x"])
  1274. zpc.close_report_target(target)
  1275. (tmp_path / "leak.txt").unlink()
  1276. # a refused report path and a failed run through main
  1277. run_main(api, argv=["--out", str(tmp_path / "missing" / "r.txt")])
  1278. run_main(FakeAPI(tagged=[]))
  1279. run_main(api)
  1280. # allow the loopback servers' own per-connection sockets to settle
  1281. for _ in range(50):
  1282. if open_fd_count() <= before + 3:
  1283. break
  1284. threading.Event().wait(0.02)
  1285. assert open_fd_count() <= before + 3, "descriptors accumulate across failing runs"
  1286. def test_report_target_is_closed_when_main_ends_on_every_path(tmp_path):
  1287. before = open_fd_count()
  1288. for i in range(10):
  1289. report = tmp_path / f"r{i}.txt"
  1290. run_main(FakeAPI(), argv=["--out", str(report)]) # success
  1291. run_main(FakeAPI(tagged=[]), argv=["--out", str(tmp_path / f"f{i}.txt")]) # discovery failure
  1292. run_main(FakeAPI(), counters=Counters(outcome=zpc.OPEN), argv=["--out", str(tmp_path / f"o{i}.txt")])
  1293. assert open_fd_count() <= before + 1
  1294. def test_sockets_do_not_leak_across_many_tcp_connect_failures():
  1295. FakeSocket.created = FakeSocket.closed = 0
  1296. for behaviour in ("ok", "timeout", errno.ECONNREFUSED, errno.EMFILE, "settimeout-fails"):
  1297. for _ in range(50):
  1298. zpc.tcp_connect("192.0.2.1", 80, 1.0, socket_factory=lambda *a, b=behaviour: FakeSocket(b))
  1299. assert FakeSocket.created == FakeSocket.closed == 250
  1300. def test_keyboard_interrupt_with_real_threads_leaves_no_workers_and_discards_results():
  1301. started = threading.Event()
  1302. def slow_connect(address, port, timeout):
  1303. started.set()
  1304. threading.Event().wait(0.05)
  1305. return zpc.TIMEOUT
  1306. calls = []
  1307. def interrupting_reread():
  1308. calls.append(1)
  1309. raise KeyboardInterrupt
  1310. api = FakeAPI()
  1311. out = io.StringIO()
  1312. original_get = api.get
  1313. state = {"projects": 0}
  1314. def get(path, params):
  1315. if path == "/v2/projects":
  1316. state["projects"] += 1
  1317. return original_get(path, params)
  1318. api.get = get
  1319. # The first discovery succeeds; the re-read after the first batch is interrupted.
  1320. def transport_factory(token):
  1321. class T:
  1322. def get(self, path, params):
  1323. if path == "/v2/projects" and state["projects"] >= 1:
  1324. interrupting_reread()
  1325. return get(path, params)
  1326. return T()
  1327. code = zpc.main(
  1328. ["--expect-connectors", "2"], env={"DIGITALOCEAN_TOKEN": CRED}, stdout=out,
  1329. hooks=zpc.Hooks(address_ok=OK, connect=slow_connect, control_connect=lambda h, p, t: None,
  1330. transport_factory=transport_factory, ports=range(1, 41),
  1331. budget=zpc.Budget(concurrency=8, rate=1e6, batch=16)))
  1332. assert code == 2 and "interrupted" in out.getvalue()
  1333. assert "PASS" not in out.getvalue() and "attempted" not in out.getvalue()
  1334. assert calls, "the interrupt was delivered"
  1335. for _ in range(100):
  1336. if not [t for t in threading.enumerate() if t.name.startswith("ThreadPoolExecutor")]:
  1337. break
  1338. threading.Event().wait(0.02)
  1339. assert not [t for t in threading.enumerate() if t.name.startswith("ThreadPoolExecutor")]
  1340. # DigitalOcean response shapes
  1341. def test_total_changing_between_pages_is_refused():
  1342. api = FakeAPI(page_size=1)
  1343. original = api._list
  1344. def list_with_drift(key, items, params, total=None):
  1345. data = original(key, items, params, total)
  1346. if int(params["page"]) >= 2:
  1347. data["meta"]["total"] += 1
  1348. return data
  1349. api._list = list_with_drift
  1350. with pytest.raises(zpc.CheckError, match="total"):
  1351. zpc.discover(api, 2, "tor1", OK)
  1352. def test_droplet_without_networks_or_with_odd_networks_is_refused():
  1353. for bad in ({"id": 1001}, {"id": 1001, "networks": None}, {"id": 1001, "networks": {}},
  1354. {"id": 1001, "networks": {"v4": "x"}}, {"id": 1001, "networks": {"v4": [None]}},
  1355. {"id": 1001, "networks": {"v4": [{"type": "other", "ip_address": A}]}}):
  1356. api = FakeAPI(tagged=[bad, droplet(1002, B)])
  1357. with pytest.raises(zpc.CheckError):
  1358. zpc.discover(api, 2, "tor1", OK)
  1359. def test_only_private_v4_entries_is_refused_and_a_private_entry_is_never_scanned():
  1360. api = FakeAPI(tagged=[droplet(1001, None), droplet(1002, B)])
  1361. with pytest.raises(zpc.CheckError):
  1362. zpc.discover(api, 2, "tor1", OK)
  1363. inv = zpc.discover(FakeAPI(), 2, "tor1", OK)
  1364. assert "10.116.0.2" not in {u.address for u in inv.units}
  1365. def test_duplicate_droplet_ids_across_pages_are_refused():
  1366. api = FakeAPI(tagged=[droplet(1001, A), droplet(1001, A)], project_droplets=[1001], page_size=1)
  1367. with pytest.raises(zpc.CheckError, match="repeated"):
  1368. zpc.discover(api, 1, "tor1", OK)
  1369. def test_reserved_ip_on_a_non_target_droplet_never_becomes_a_target():
  1370. api = FakeAPI(tagged=[droplet(1001, A), droplet(1002, B), droplet(1003, "198.51.100.99")],
  1371. project_droplets=[1001, 1002],
  1372. reserved4=[{"ip": RESERVED, "droplet": {"id": 1003}}, {"ip": "198.51.100.51", "droplet": {"id": 77}}])
  1373. inv = zpc.discover(api, 2, "tor1", OK)
  1374. assert {u.address for u in inv.units} == {A, B}
  1375. def test_reserved_ipv6_on_a_non_target_droplet_is_ignored():
  1376. api = FakeAPI(reserved6=[{"ip": "2001:db8::5", "droplet": {"id": 4242}}])
  1377. assert len(zpc.discover(api, 2, "tor1", OK).units) == 2
  1378. def test_project_resources_listing_is_paginated_and_complete():
  1379. api = FakeAPI(page_size=1)
  1380. inv = zpc.discover(api, 2, "tor1", OK)
  1381. pages = [p["page"] for path, p in api.calls if path.endswith("/resources")]
  1382. assert pages == [1, 2, 3], "droplet, droplet and the volume are three pages of one"
  1383. assert len(inv.units) == 2
  1384. def test_a_project_droplet_found_only_on_a_later_resources_page_still_counts():
  1385. api = FakeAPI(page_size=1)
  1386. api.resources = [{"urn": "do:volume:x"}, {"urn": "do:droplet:1001"}, {"urn": "do:droplet:1002"}]
  1387. assert len(zpc.discover(api, 2, "tor1", OK).units) == 2
  1388. # ===================================================================== fix round 2
  1389. # Finding 1: overdue sleepers must not connect together.
  1390. def test_workers_waking_from_a_long_sleep_do_not_start_together_on_the_fake_clock():
  1391. now = [0.0]
  1392. lock = threading.Lock()
  1393. barrier = threading.Barrier(3)
  1394. sleeps = []
  1395. def sleep(delay):
  1396. with lock:
  1397. first = len(sleeps) < 3
  1398. sleeps.append(delay)
  1399. if first:
  1400. barrier.wait(5) # three sleepers are in flight together
  1401. with lock:
  1402. now[0] = 10.0 # then the world moves on a long way
  1403. else:
  1404. with lock:
  1405. now[0] += delay
  1406. stamps = []
  1407. def connect(address, port, timeout):
  1408. with lock:
  1409. stamps.append(now[0])
  1410. return zpc.TIMEOUT
  1411. inv = units(1)
  1412. zpc.scan(inv, connect, zpc.Budget(concurrency=4, rate=10.0, batch=4), reread=lambda: inv,
  1413. clock=lambda: now[0], sleep=sleep, executor_factory=DelayedExecutor, ports=range(1, 5))
  1414. stamps.sort()
  1415. assert len(stamps) == 4
  1416. gaps = [b - a for a, b in itertools.pairwise(stamps)]
  1417. assert min(gaps) >= 0.1 - 1e-9, f"overdue reservations accumulated credit: {stamps}"
  1418. def test_limiter_grants_are_spaced_from_the_actual_grant_time():
  1419. now = [0.0]
  1420. limiter = zpc._RateLimiter(10.0, lambda: now[0], lambda d: now.__setitem__(0, now[0] + d))
  1421. grants = []
  1422. for _ in range(3):
  1423. limiter.wait()
  1424. grants.append(now[0])
  1425. now[0] = 100.0 # a long idle gap earns no burst of credit
  1426. for _ in range(3):
  1427. limiter.wait()
  1428. grants.append(now[0])
  1429. assert all(b - a >= 0.1 - 1e-9 for a, b in itertools.pairwise(grants)), grants
  1430. # Finding 2: cleanup inside an error handler must not escape sanitization.
  1431. class RaisingBody:
  1432. def read(self, *a):
  1433. return b""
  1434. def close(self):
  1435. raise OSError(errno.EIO, "close failed " + CRED)
  1436. def test_httperror_whose_close_raises_leaves_a_clean_sanitised_error():
  1437. class Opener:
  1438. def open(self, req, timeout=None):
  1439. raise urllib.error.HTTPError(req.full_url, 500, "reason " + CRED, {}, RaisingBody())
  1440. transport = zpc.ApiTransport(CRED, "http://127.0.0.1:1")
  1441. transport._opener = Opener()
  1442. with pytest.raises(zpc.CheckError) as info:
  1443. transport.get("/v2/projects", {})
  1444. assert_chain_is_clean(info.value, CRED, "close failed")
  1445. CLEANUP_ATTRS = ("close", "shutdown", "unlink", "release")
  1446. def unprotected_cleanup_calls(tree):
  1447. """Line numbers of cleanup calls inside an except body that have no try of their own."""
  1448. found = []
  1449. def walk(node, protected):
  1450. if isinstance(node, ast.Try):
  1451. for stmt in node.body:
  1452. walk(stmt, True)
  1453. for handler in node.handlers:
  1454. for stmt in handler.body:
  1455. walk(stmt, protected)
  1456. for stmt in node.orelse + node.finalbody:
  1457. walk(stmt, protected)
  1458. return
  1459. if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
  1460. and node.func.attr in CLEANUP_ATTRS and not protected):
  1461. found.append(node.lineno)
  1462. for child in ast.iter_child_nodes(node):
  1463. walk(child, protected)
  1464. for node in ast.walk(tree):
  1465. if isinstance(node, ast.ExceptHandler):
  1466. for stmt in node.body:
  1467. walk(stmt, False)
  1468. return found
  1469. def test_no_cleanup_call_sits_unprotected_inside_an_except_block():
  1470. offenders = unprotected_cleanup_calls(ast.parse(SCRIPT.read_text()))
  1471. assert offenders == [], f"cleanup inside an except block without its own try: lines {offenders}"
  1472. def test_the_cleanup_audit_bites():
  1473. bad = ast.parse("try:\n pass\nexcept OSError as e:\n e.close()\n")
  1474. good = ast.parse(
  1475. "try:\n pass\nexcept OSError as e:\n try:\n e.close()\n"
  1476. " except OSError:\n pass\n"
  1477. )
  1478. assert unprotected_cleanup_calls(bad) and not unprotected_cleanup_calls(good)
  1479. # Finding 3: a pinned report directory moved into the repository is caught before and after.
  1480. def test_report_directory_renamed_into_the_repo_after_validation_is_not_written(tmp_path, monkeypatch):
  1481. fake_repo = tmp_path / "repo"
  1482. fake_repo.mkdir()
  1483. safe = tmp_path / "safe"
  1484. safe.mkdir()
  1485. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1486. target = zpc.check_out_path(str(safe / "r.txt"))
  1487. try:
  1488. safe.rename(fake_repo / "moved")
  1489. with pytest.raises(zpc.CheckError, match="repository"):
  1490. zpc.write_report(target, ["line"])
  1491. finally:
  1492. zpc.close_report_target(target)
  1493. assert not (fake_repo / "moved" / "r.txt").exists()
  1494. def test_report_directory_moved_in_during_the_write_is_removed(tmp_path, monkeypatch):
  1495. fake_repo = tmp_path / "repo"
  1496. fake_repo.mkdir()
  1497. safe = tmp_path / "safe"
  1498. safe.mkdir()
  1499. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1500. target = zpc.check_out_path(str(safe / "r.txt"))
  1501. real = zpc._inside_repo
  1502. calls = []
  1503. def moving(fd):
  1504. calls.append(1)
  1505. answer = real(fd)
  1506. if len(calls) == 1: # the pre-write check passes, then the directory is moved
  1507. safe.rename(fake_repo / "moved")
  1508. return answer
  1509. monkeypatch.setattr(zpc, "_inside_repo", moving)
  1510. try:
  1511. with pytest.raises(zpc.CheckError, match="repository"):
  1512. zpc.write_report(target, ["line"])
  1513. finally:
  1514. zpc.close_report_target(target)
  1515. assert len(calls) == 2, "checked before creating and again after writing"
  1516. assert not (fake_repo / "moved" / "r.txt").exists(), "the mis-placed report was removed"
  1517. def test_main_reports_exit_2_when_the_report_directory_moves_into_the_repo(tmp_path, monkeypatch):
  1518. fake_repo = tmp_path / "repo"
  1519. fake_repo.mkdir()
  1520. safe = tmp_path / "safe"
  1521. safe.mkdir()
  1522. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1523. real = zpc._inside_repo
  1524. calls = []
  1525. def moving(fd):
  1526. calls.append(1)
  1527. if len(calls) == 2: # validation was call 1; the pre-write check is call 2
  1528. safe.rename(fake_repo / "moved")
  1529. return real(fd)
  1530. monkeypatch.setattr(zpc, "_inside_repo", moving)
  1531. code, out, _ = run_main(FakeAPI(), argv=["--out", str(safe / "r.txt")])
  1532. assert code == 2 and "PASS" not in out
  1533. assert not (fake_repo / "moved" / "r.txt").exists()
  1534. # Finding 4: covered in the edited close-failure tests above.
  1535. # Finding 5: no ambient HTTP debug logging.
  1536. def test_http_handlers_ignore_the_ambient_debuglevel(monkeypatch, capsys, make_site):
  1537. import http.client
  1538. monkeypatch.setattr(http.client.HTTPConnection, "debuglevel", 1)
  1539. monkeypatch.setattr(http.client.HTTPSConnection, "debuglevel", 1)
  1540. opener = zpc.build_opener()
  1541. handlers = [h for h in opener.handlers if hasattr(h, "_debuglevel")]
  1542. assert handlers and all(h._debuglevel == 0 for h in handlers)
  1543. site = make_site(json_route(FakeAPI()))
  1544. zpc.ApiTransport(CRED, site.url).get("/v2/projects", {"page": 1})
  1545. captured = capsys.readouterr()
  1546. assert "send:" not in captured.out and CRED not in captured.out and CRED not in captured.err
  1547. def test_the_default_urllib_would_print_the_header_so_the_debug_test_bites(monkeypatch, capsys, make_site):
  1548. import http.client
  1549. monkeypatch.setattr(http.client.HTTPConnection, "debuglevel", 1)
  1550. site = make_site(lambda h: (200, {"Content-Type": "application/json"}, b"{}"))
  1551. req = urllib.request.Request(site.url + "/x", headers={"Authorization": "Bearer " + CRED})
  1552. with contextlib.closing(urllib.request.build_opener().open(req, timeout=5)):
  1553. pass
  1554. assert CRED in capsys.readouterr().out
  1555. # Finding 6: no leaked descriptor when the ancestry walk fails half way.
  1556. def test_ancestry_walk_does_not_leak_when_fstat_fails(tmp_path, monkeypatch):
  1557. fake_repo = tmp_path / "repo"
  1558. fake_repo.mkdir()
  1559. deep = tmp_path / "a" / "b"
  1560. deep.mkdir(parents=True)
  1561. monkeypatch.setattr(zpc, "_repo_root", lambda: fake_repo)
  1562. dir_fd = os.open(deep, os.O_RDONLY | os.O_DIRECTORY)
  1563. real = os.fstat
  1564. state = {"n": 0, "active": False}
  1565. def flaky(fd):
  1566. if state["active"]:
  1567. state["n"] += 1
  1568. if state["n"] == 2:
  1569. raise OSError(errno.EIO, "fstat failed")
  1570. return real(fd)
  1571. try:
  1572. before = open_fd_count()
  1573. monkeypatch.setattr(os, "fstat", flaky)
  1574. for _ in range(20):
  1575. state.update(n=0, active=True)
  1576. assert zpc._inside_repo(dir_fd) is True, "doubt counts as inside"
  1577. state["active"] = False
  1578. monkeypatch.setattr(os, "fstat", real)
  1579. assert open_fd_count() == before, "the opened parent descriptor leaked"
  1580. finally:
  1581. os.close(dir_fd)
  1582. # Round 4: every returned droplet must itself carry the exact baseline tag.
  1583. def _discover_with(tagged):
  1584. api = FakeAPI(tagged=tagged)
  1585. return zpc.discover(api, len(tagged), "tor1", OK)
  1586. def test_a_droplet_with_the_baseline_tag_is_accepted():
  1587. assert _discover_with([droplet(1001, A)]).labels == ("connector-1",)
  1588. @pytest.mark.parametrize(
  1589. "tags",
  1590. [
  1591. _NO_TAGS,
  1592. [],
  1593. "cah-baseline-tor1",
  1594. 7,
  1595. {"cah-baseline-tor1": 1},
  1596. [1],
  1597. [BASELINE_TAG, 1],
  1598. [BASELINE_TAG, BASELINE_TAG],
  1599. ["cah-baseline-ams3"],
  1600. ["cah-baseline-tor1-x"],
  1601. ["CAH-BASELINE-TOR1"],
  1602. [BASELINE_TAG + "\n"],
  1603. [True],
  1604. ],
  1605. ids=lambda v: "no-tags-member" if v is _NO_TAGS else repr(v),
  1606. )
  1607. def test_a_returned_droplet_without_a_proper_baseline_tag_is_refused(tags):
  1608. tagged = [droplet(1001, "8.8.8.8", tags=tags)]
  1609. with pytest.raises(zpc.CheckError):
  1610. zpc.discover(FakeAPI(tagged=tagged), 1, "tor1", zpc.default_address_ok)
  1611. def test_main_stops_before_the_control_and_any_socket_when_a_tag_is_missing():
  1612. counters = Counters()
  1613. api = FakeAPI(tagged=[droplet(1001, A, tags=_NO_TAGS)])
  1614. code, _out, _ = run_main(api, expected=1, counters=counters)
  1615. assert code == 2 and counters.scan == 0 and counters.control == 0
  1616. # Round 4: the report directory is walked component by component; no symlink anywhere.
  1617. def test_a_symlink_in_an_ancestor_is_refused_even_when_it_leads_to_an_allowed_directory(tmp_path):
  1618. real = tmp_path / "real"
  1619. (real / "sub").mkdir(parents=True)
  1620. link = tmp_path / "link"
  1621. link.symlink_to(real)
  1622. with pytest.raises(zpc.CheckError):
  1623. zpc.check_out_path(str(link / "sub" / "r.txt"))
  1624. # control: the same directory through plain components is accepted
  1625. target = zpc.check_out_path(str(real / "sub" / "r.txt"))
  1626. zpc.close_report_target(target)
  1627. def test_dot_dot_through_a_symlink_is_refused(tmp_path):
  1628. real = tmp_path / "real"
  1629. real.mkdir()
  1630. (tmp_path / "out").mkdir()
  1631. link = tmp_path / "link"
  1632. link.symlink_to(real)
  1633. with pytest.raises(zpc.CheckError):
  1634. zpc.check_out_path(str(link / ".." / "out" / "r.txt"))
  1635. def test_a_relative_path_is_walked_too(tmp_path, monkeypatch):
  1636. real = tmp_path / "real"
  1637. real.mkdir()
  1638. (tmp_path / "link").symlink_to(real)
  1639. monkeypatch.chdir(tmp_path)
  1640. with pytest.raises(zpc.CheckError):
  1641. zpc.check_out_path("link/r.txt")
  1642. target = zpc.check_out_path("real/r.txt")
  1643. zpc.close_report_target(target)
  1644. # Round 5: the baseline tag follows the stack's resource_key when one is set.
  1645. KEY = "tor1-b"
  1646. KEY_TAG = "cah-baseline-tor1-b"
  1647. def _keyed(n=1):
  1648. return [droplet(1000 + i, f"198.51.100.{10 + i}", tags=[KEY_TAG]) for i in range(1, n + 1)]
  1649. def test_resource_key_builds_the_tag_the_stack_publishes():
  1650. api = FakeAPI(tagged=_keyed(), tag=KEY_TAG)
  1651. inv = zpc.discover(api, 1, "tor1", OK, KEY)
  1652. assert inv.labels == ("connector-1",)
  1653. def test_without_a_resource_key_the_region_tag_is_used():
  1654. api = FakeAPI(tagged=[droplet(1001, A)])
  1655. assert zpc.discover(api, 1, "tor1", OK, "").labels == ("connector-1",)
  1656. def test_region_only_query_misses_a_keyed_stack_and_stops():
  1657. # the failure the option exists to fix: the stack tagged cah-baseline-tor1-b
  1658. api = FakeAPI(tagged=_keyed(), tag=BASELINE_TAG)
  1659. with pytest.raises(zpc.CheckError):
  1660. zpc.discover(api, 1, "tor1", OK, "")
  1661. def test_a_droplet_with_only_the_region_tag_is_refused_when_a_key_is_given():
  1662. api = FakeAPI(tagged=[droplet(1001, A)], tag=KEY_TAG)
  1663. with pytest.raises(zpc.CheckError):
  1664. zpc.discover(api, 1, "tor1", OK, KEY)
  1665. def test_main_accepts_resource_key_and_scans():
  1666. api = FakeAPI(tagged=_keyed(), tag=KEY_TAG)
  1667. code, out, counters = run_main(api, expected=1, argv=["--resource-key", KEY])
  1668. assert code == 0 and counters.scan == 3 and "198.51.100" not in out
  1669. @pytest.mark.parametrize(
  1670. "key",
  1671. ["tor1-b\n", "Tor1", "TOR1-B", "a", "1abc", "-abc", "a" * 25, "a;rm", "a b", "a$(x)", "a`x`",
  1672. "a|b", "a&b", "a/../b", "a_b", "a.b", "tor1-b ", " tor1-b", "tör1"],
  1673. )
  1674. def test_a_hostile_resource_key_is_refused_before_any_request(key):
  1675. api = FakeAPI()
  1676. with pytest.raises(zpc.CheckError):
  1677. zpc.discover(api, 1, "tor1", OK, key)
  1678. assert api.calls == []
  1679. @pytest.mark.parametrize("key", ["ab", "a" * 24, "tor1-b", "x-1-2"])
  1680. def test_boundary_resource_keys_are_accepted(key):
  1681. tag = "cah-baseline-" + key
  1682. api = FakeAPI(tagged=[droplet(1001, A, tags=[tag])], tag=tag)
  1683. assert zpc.discover(api, 1, "tor1", OK, key).labels == ("connector-1",)
  1684. def test_main_refuses_a_hostile_resource_key_with_no_socket():
  1685. counters = Counters()
  1686. code, _out, _ = run_main(FakeAPI(), expected=1, counters=counters, argv=["--resource-key", "BAD\n"])
  1687. assert code == 2 and counters.scan == 0 and counters.control == 0