| 1 | """Regression tests for PR 16: Job boards SSRF, host/port injection & ReDoS. |
| 2 | |
| 3 | Covers HIGH-163, HIGH-164, HIGH-167, HIGH-169, HIGH-171, HIGH-173, and HIGH-174. |
| 4 | """ |
| 5 | |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | import io |
| 9 | import socket |
| 10 | import time |
| 11 | import urllib.error |
| 12 | import urllib.request |
| 13 | from concurrent.futures import ThreadPoolExecutor |
| 14 | from email.message import Message |
| 15 | from unittest.mock import patch |
| 16 | |
| 17 | import pytest |
| 18 | |
| 19 | from lib import http, jobs |
| 20 | from lib.job_boards import detect, jibe, kula, oracle, phenom, robots, sitemap, talentbrew |
| 21 | |
| 22 | |
| 23 | # --------------------------------------------------------------------------- |
| 24 | # HIGH-163: _host / parse_board_url / _named_jobs_host / _same_site / URL checks |
| 25 | # --------------------------------------------------------------------------- |
| 26 | |
| 27 | |
| 28 | @pytest.mark.parametrize( |
| 29 | "raw,expected", |
| 30 | [ |
| 31 | ("https://meta.com:443/careers", "meta.com"), |
| 32 | ("https://meta.com.:443/careers", "meta.com"), |
| 33 | ("https://JOBS.ACME.COM/openings", "jobs.acme.com"), |
| 34 | ("http://jobs.company.com@169.254.169.254/latest/meta-data/", ""), |
| 35 | ("https://user:pass@company.com/careers", ""), |
| 36 | ("https://169.254.169.254\\.acme.com/careers", ""), |
| 37 | ("https://acme.com:99999/careers", ""), |
| 38 | ("https://acme..com/careers", ""), |
| 39 | ("https://acme.com../careers", ""), |
| 40 | ("https://acme.com/\r\nX: 1", ""), |
| 41 | ], |
| 42 | ) |
| 43 | def test_high163_host_normalizes_ports_fqdn_and_rejects_userinfo_tricks(raw: str, expected: str): |
| 44 | assert jobs._host(raw) == expected |
| 45 | if expected == "": |
| 46 | assert detect.is_safe_public_url(raw) is False |
| 47 | |
| 48 | |
| 49 | def test_high163_registry_entry_cannot_be_bypassed_with_explicit_port_or_fqdn(): |
| 50 | for site in ( |
| 51 | "https://meta.com:443/careers", |
| 52 | "https://meta.com.:443/careers", |
| 53 | "https://about.meta.com:443/", |
| 54 | "https://tesla.com:8443/careers", |
| 55 | ): |
| 56 | entry = jobs._registry_entry(site) |
| 57 | assert entry is not None and entry[0] == "unreadable", f"bypassed unreadable registry for {site}" |
| 58 | |
| 59 | for site, expected_provider in ( |
| 60 | ("https://apple.com:443/careers", jobs.COMPANY_PROVIDER_APPLE), |
| 61 | ("https://www.amazon.com.:443/", jobs.COMPANY_PROVIDER_AMAZON), |
| 62 | ): |
| 63 | entry = jobs._registry_entry(site) |
| 64 | assert entry is not None and entry[0] == "board" and entry[1]["provider"] == expected_provider |
| 65 | |
| 66 | |
| 67 | def test_high163_parse_board_url_accepts_default_port_and_blocks_userinfo_or_bad_ports(): |
| 68 | assert jobs.parse_board_url("https://boards.greenhouse.io:443/stripe") == ("greenhouse", "stripe") |
| 69 | assert jobs.parse_board_url("https://boards.greenhouse.io.:443/stripe") == ("greenhouse", "stripe") |
| 70 | for bad in ( |
| 71 | "https://user:pass@boards.greenhouse.io/stripe", |
| 72 | "https://evil@boards.greenhouse.io/stripe", |
| 73 | "https://boards.greenhouse.io:8443/stripe", |
| 74 | "https://boards.greenhouse.io:80/stripe", |
| 75 | "http://boards.greenhouse.io:443/stripe", |
| 76 | "https://boards.greenhouse.io\\@evil.com/stripe", |
| 77 | "file:///boards.greenhouse.io/stripe", |
| 78 | ): |
| 79 | assert jobs.parse_board_url(bad) == (None, None), f"expected rejection for {bad}" |
| 80 | |
| 81 | |
| 82 | def test_high163_named_jobs_host_blocks_cctld_generic_userinfo_and_subdomain_spoofs(): |
| 83 | # Multi-part ccTLD bypasses ("com"/"org"/"net" must never be treated as company name). |
| 84 | assert jobs._named_jobs_host("jobs.evil.com", "https://acme.com.au/careers") is False |
| 85 | assert jobs._named_jobs_host("careers.evil.org", "https://acme.org.uk/careers") is False |
| 86 | assert jobs._named_jobs_host("jobs.evil.net", "https://acme.net.au/careers") is False |
| 87 | assert jobs._named_jobs_host("jobs.evil.com", "https://acme.com.br/careers") is False |
| 88 | assert jobs._named_jobs_host("jobs.evil.co.uk", "https://acme.co.uk/careers") is False |
| 89 | # Attacker subdomain containing victim's label on attacker's domain. |
| 90 | assert jobs._named_jobs_host("jobs.acme.evil.com", "https://acme.com/careers") is False |
| 91 | # Userinfo / non-public / IP / reserved suffix spoofs. |
| 92 | assert jobs._named_jobs_host("jobs.company.com@169.254.169.254", "https://company.com/careers") is False |
| 93 | assert jobs._named_jobs_host("jobs.company.local", "https://company.com/careers") is False |
| 94 | assert jobs._named_jobs_host("jobs.company.internal", "https://company.com/careers") is False |
| 95 | assert jobs._named_jobs_host("jobs.company.com:8443", "https://company.com/careers") is False |
| 96 | # Legitimate cross-TLD jobs hosts still work (including from ccTLD pages). |
| 97 | assert jobs._named_jobs_host("explore.jobs.netflix.net", "https://jobs.netflix.com/") is True |
| 98 | assert jobs._named_jobs_host("jobs.acme.net", "https://acme.com.au/careers") is True |
| 99 | assert jobs._named_jobs_host("jobs.acme.com", "https://acme.co.uk/careers") is True |
| 100 | |
| 101 | |
| 102 | def test_high163_jobs_links_and_board_page_block_userinfo_ports_and_cctld_bypasses(): |
| 103 | html = ( |
| 104 | '<a href="http://jobs.company.com@169.254.169.254/latest/meta-data/">Meta</a>' |
| 105 | '<a href="https://jobs.company.com:8443/openings">AltPort</a>' |
| 106 | '<a href="https://jobs.evil.com/openings">EvilCom</a>' |
| 107 | '<a href="https://jobs.acme.com.au/openings">Good</a>' |
| 108 | ) |
| 109 | assert jobs._jobs_links(html, "https://acme.com.au/careers") == ["https://jobs.acme.com.au/openings"] |
| 110 | |
| 111 | # _careers_page_at must refuse non-public/userinfo landed URLs even when named=True. |
| 112 | budget = jobs.LaneBudget() |
| 113 | token = jobs._BUDGET.set(budget) |
| 114 | try: |
| 115 | budget.landed["https://join.disneycareers.com/global/en"] = ( |
| 116 | "http://jobs.disney.com@169.254.169.254/latest/meta-data/" |
| 117 | ) |
| 118 | with patch.object(jobs.http, "get_text", return_value="<p>Open positions</p>"): |
| 119 | page, _gone, _used = jobs._careers_page_at( |
| 120 | "https://join.disneycareers.com/global/en", |
| 121 | guessed=True, company="Disney", site="https://disney.com/", named=True, |
| 122 | ) |
| 123 | assert page is None |
| 124 | finally: |
| 125 | jobs._BUDGET.reset(token) |
| 126 | |
| 127 | # _board_page must never fetch userinfo or port-injected eightFoldCareerUrl. |
| 128 | poisoned_landing = ( |
| 129 | '<div id="careers-eightFoldCareerUrl">https://jobs.acme.com@169.254.169.254/careers</div>' |
| 130 | '<a href="https://jobs.acme.com:8443/jobs">Jobs</a>' |
| 131 | ) |
| 132 | with patch.object(jobs.http, "get_text", side_effect=AssertionError("must not fetch")): |
| 133 | assert jobs._board_page(poisoned_landing, "https://acme.com/careers") == ( |
| 134 | poisoned_landing, "https://acme.com/careers", |
| 135 | ) |
| 136 | |
| 137 | |
| 138 | def test_high163_search_redirect_posting_board_and_domain_use_hostname(): |
| 139 | assert jobs._is_search_redirect("https://google.com:443/url?q=https://evil.com") is True |
| 140 | assert jobs._is_search_redirect("https://duckduckgo.com:443/l/?uddg=https://evil.com") is True |
| 141 | assert jobs._is_search_redirect("https://user@example.com/careers") is True |
| 142 | assert jobs._is_search_redirect("https://acme.com/careers") is False |
| 143 | |
| 144 | assert jobs._posting_board("https://boards.greenhouse.io:443/stripe/jobs/123") == "stripe" |
| 145 | assert jobs._posting_board("https://user@boards.greenhouse.io/stripe/jobs/123") == "" |
| 146 | assert jobs._posting_board("https://boards.greenhouse.io:8443/stripe/jobs/123") == "" |
| 147 | |
| 148 | assert jobs._domain("https://www.walmart.com:443/jobs") == "walmart.com" |
| 149 | assert jobs._domain("https://walmart.com/jobs") == "walmart.com" |
| 150 | assert jobs._domain("https://user@walmart.com/jobs") == "" |
| 151 | |
| 152 | |
| 153 | # --------------------------------------------------------------------------- |
| 154 | # HIGH-164: Linear-time HTML / JSON-LD / site-name / tag-strip / ATS parsing |
| 155 | # --------------------------------------------------------------------------- |
| 156 | |
| 157 | |
| 158 | def test_high164_jobs_html_and_jsonld_parsers_resist_redos_in_under_100ms(): |
| 159 | adversarial_cases = [ |
| 160 | ("extract_jsonld_blocks script", lambda: jobs.extract_jsonld_blocks("<script " * 60_000)), |
| 161 | ( |
| 162 | "extract_jsonld_jobs unclosed ld+json", |
| 163 | lambda: jobs.extract_jsonld_jobs('<script type="application/ld+json">' * 50_000, "https://acme.com/"), |
| 164 | ), |
| 165 | ("stated_names meta", lambda: jobs._stated_names("<meta " * 60_000)), |
| 166 | ("stated_names og_site_name", lambda: jobs._stated_names('<meta property="og:site_name" ' * 50_000)), |
| 167 | ("clean_html unclosed <", lambda: jobs._clean_html("<" * 100_000)), |
| 168 | ("clean_html unclosed <br", lambda: jobs._clean_html("<br " * 60_000)), |
| 169 | ("block_text unclosed <", lambda: jobs._block_text("<" * 100_000)), |
| 170 | ("block_text unclosed <div", lambda: jobs._block_text("<div " * 60_000)), |
| 171 | ("detect_ats long alnum", lambda: jobs.detect_ats("a" * 100_000)), |
| 172 | ("boards_named long alnum", lambda: jobs._boards_named("a" * 100_000)), |
| 173 | ] |
| 174 | for label, fn in adversarial_cases: |
| 175 | cpu_start = time.process_time() |
| 176 | fn() |
| 177 | cpu_elapsed = time.process_time() - cpu_start |
| 178 | assert cpu_elapsed < 1.0, f"{label} took {cpu_elapsed:.4f}s CPU (possible ReDoS)" |
| 179 | |
| 180 | |
| 181 | def test_high164_jobs_links_deduplication_is_linear_on_20k_links(): |
| 182 | html = "".join(f'<a href="https://jobs.acme.com/openings/{i}">Job {i}</a>' for i in range(20_000)) |
| 183 | cpu_start = time.process_time() |
| 184 | links = jobs._jobs_links(html, "https://acme.com/careers") |
| 185 | cpu_elapsed = time.process_time() - cpu_start |
| 186 | assert len(links) == 20_000 |
| 187 | assert links[0] == "https://jobs.acme.com/openings/0" |
| 188 | assert links[-1] == "https://jobs.acme.com/openings/19999" |
| 189 | assert cpu_elapsed < 3.5, f"_jobs_links took {cpu_elapsed:.4f}s CPU on 20k links" |
| 190 | |
| 191 | |
| 192 | def test_high164_html_parser_preserves_jsonld_and_site_name_semantics(): |
| 193 | html = ( |
| 194 | '<meta content="Anduril Industries" property="og:site_name" />' |
| 195 | '<script charset="utf-8" type="application/ld+json; charset=utf-8">' |
| 196 | '{"@type":"Organization","name":"Anduril Corp"}' |
| 197 | "</script>" |
| 198 | '<script type="application/ld+json">' |
| 199 | '{"@type":"JobPosting","title":"Systems Engineer","description":"<p>Build & ship.</p>"}' |
| 200 | "</script>" |
| 201 | ) |
| 202 | assert jobs._stated_names(html) == ["Anduril Corp", "Anduril Industries"] |
| 203 | assert jobs.jsonld_role_text(html) == ("Build & ship.", "Build & ship.") |
| 204 | found = jobs.extract_jsonld_jobs(html, "https://www.anduril.com/careers") |
| 205 | assert len(found) == 1 and found[0]["title"] == "Systems Engineer" |
| 206 | assert found[0]["source_domain"] == "anduril.com" |
| 207 | |
| 208 | |
| 209 | # --------------------------------------------------------------------------- |
| 210 | # HIGH-167: Escaping and validation of remote JSON fields in URLs / detail_url |
| 211 | # --------------------------------------------------------------------------- |
| 212 | |
| 213 | |
| 214 | def test_high167_eightfold_pcsx_and_v2_escape_ids_and_validate_position_urls(): |
| 215 | pcsx_entry = {"name": "Acme", "board": "jobs.acme.com", "domain": "acme.com&admin=1#x", "api": "pcsx"} |
| 216 | pcsx_payload = { |
| 217 | "data": { |
| 218 | "count": 2, |
| 219 | "positions": [ |
| 220 | { |
| 221 | "id": "../../admin?x=1#frag", |
| 222 | "name": "Evil Path Role", |
| 223 | "positionUrl": "@evil.com/phish", |
| 224 | }, |
| 225 | { |
| 226 | "id": "99", |
| 227 | "name": "Good Role", |
| 228 | "positionUrl": "/careers/job/99", |
| 229 | }, |
| 230 | ], |
| 231 | } |
| 232 | } |
| 233 | items, total = jobs.parse_eightfold_response(pcsx_payload, pcsx_entry) |
| 234 | assert total == 2 and len(items) == 2 |
| 235 | bad_row, good_row = items |
| 236 | assert bad_row["url"] == "https://jobs.acme.com/careers/job/..%2F..%2Fadmin%3Fx%3D1%23frag" |
| 237 | assert "@evil.com" not in bad_row["url"] |
| 238 | assert "position_id=..%2F..%2Fadmin%3Fx%3D1%23frag" in bad_row["detail_url"] |
| 239 | assert "domain=acme.com%26admin%3D1%23x" in bad_row["detail_url"] |
| 240 | assert good_row["url"] == "https://jobs.acme.com/careers/job/99" |
| 241 | |
| 242 | # Also test protocol-relative, backslash, absolute, and port-injected positionUrl. |
| 243 | for bad_pos in ("//evil.com/p", "/\\evil.com/p", "https://evil.com/p", ":8443/p"): |
| 244 | rows, _ = jobs.parse_eightfold_response( |
| 245 | {"data": {"count": 1, "positions": [{"id": "7", "name": "R", "positionUrl": bad_pos}]}}, |
| 246 | {"board": "jobs.acme.com", "domain": "acme.com", "api": "pcsx"}, |
| 247 | ) |
| 248 | assert rows[0]["url"] == "https://jobs.acme.com/careers/job/7" |
| 249 | |
| 250 | v2_entry = {"name": "Acme", "board": "explore.jobs.acme.net", "domain": "acme.com", "api": "v2"} |
| 251 | v2_payload = { |
| 252 | "count": 2, |
| 253 | "positions": [ |
| 254 | { |
| 255 | "id": "../../secret?foo=1#bar", |
| 256 | "name": "V2 Evil", |
| 257 | "canonicalPositionUrl": "javascript:alert(1)", |
| 258 | }, |
| 259 | { |
| 260 | "id": "42", |
| 261 | "name": "V2 Evil SSRF", |
| 262 | "canonicalPositionUrl": "http://169.254.169.254/latest/meta-data/", |
| 263 | }, |
| 264 | ], |
| 265 | } |
| 266 | v2_items, _ = jobs.parse_eightfold_response(v2_payload, v2_entry) |
| 267 | assert v2_items[0]["url"] == "https://explore.jobs.acme.net/careers/job/..%2F..%2Fsecret%3Ffoo%3D1%23bar" |
| 268 | assert v2_items[0]["detail_url"] == ( |
| 269 | "https://explore.jobs.acme.net/api/apply/v2/jobs/..%2F..%2Fsecret%3Ffoo%3D1%23bar?domain=acme.com" |
| 270 | ) |
| 271 | assert v2_items[1]["url"] == "https://explore.jobs.acme.net/careers/job/42" |
| 272 | |
| 273 | |
| 274 | def test_high167_amazon_and_apple_reject_authority_spoofing_and_escape_ids(): |
| 275 | amazon_payload = { |
| 276 | "hits": 5, |
| 277 | "jobs": [ |
| 278 | {"id": "1", "title": "Spoof At", "job_path": "@evil.com/phish"}, |
| 279 | {"id": "2", "title": "Spoof ProtoRel", "job_path": "//evil.com/phish"}, |
| 280 | {"id": "3", "title": "Spoof Backslash", "job_path": "/\\evil.com/phish"}, |
| 281 | {"id": "4", "title": "Spoof Port", "job_path": ":8443/en/jobs/1"}, |
| 282 | {"id": "5", "title": "Legit Engineer", "job_path": "/en/jobs/555/legit-engineer"}, |
| 283 | ], |
| 284 | } |
| 285 | amz_items, hits = jobs.parse_amazon_response(amazon_payload) |
| 286 | assert hits == 5 |
| 287 | assert [item["url"] for item in amz_items] == ["https://www.amazon.jobs/en/jobs/555/legit-engineer"] |
| 288 | |
| 289 | apple_payload = { |
| 290 | "res": { |
| 291 | "totalRecords": 1, |
| 292 | "searchResults": [ |
| 293 | { |
| 294 | "id": "1", |
| 295 | "positionId": "../../admin?x=1#frag", |
| 296 | "postingTitle": "Security Engineer", |
| 297 | "transformedPostingTitle": "../../evil?a=1#b", |
| 298 | "locations": [{"name": "Cupertino"}], |
| 299 | } |
| 300 | ], |
| 301 | } |
| 302 | } |
| 303 | apple_items, _ = jobs.parse_apple_response(apple_payload) |
| 304 | assert len(apple_items) == 1 |
| 305 | assert apple_items[0]["detail_url"] == ( |
| 306 | "https://jobs.apple.com/api/v1/jobDetails/..%2F..%2Fadmin%3Fx%3D1%23frag?locale=en-us" |
| 307 | ) |
| 308 | assert apple_items[0]["url"] == ( |
| 309 | "https://jobs.apple.com/en-us/details/..%2F..%2Fadmin%3Fx%3D1%23frag/..%2F..%2Fevil%3Fa%3D1%23b" |
| 310 | ) |
| 311 | |
| 312 | # Oracle / Jibe / Phenom ID escaping. |
| 313 | or_items, _ = oracle.parse_listing( |
| 314 | {"items": [{"TotalJobsCount": 1, "requisitionList": [{"Id": '1",siteNumber=EVIL&x=1', "Title": "Eng"}]}]}, |
| 315 | {"board": "jpmc.fa.oraclecloud.com", "site_number": "CX_1001"}, |
| 316 | ) |
| 317 | assert "&x=1" not in or_items[0]["detail_url"] |
| 318 | assert "%22%2CsiteNumber%3DEVIL%26x%3D1" in or_items[0]["detail_url"] |
| 319 | |
| 320 | jb_items, _ = jibe.parse_listing( |
| 321 | {"totalCount": 1, "jobs": [{"data": {"title": "Eng", "slug": "../../evil?x=1", "req_id": "1"}}]}, |
| 322 | {"board": "careers.amd.com", "jobs_path": "//evil.com"}, |
| 323 | ) |
| 324 | assert jb_items[0]["url"] == "https://careers.amd.com/jobs/..%2F..%2Fevil%3Fx%3D1" |
| 325 | |
| 326 | |
| 327 | # --------------------------------------------------------------------------- |
| 328 | # HIGH-169: redirect_guard & public_only across robots and all board adapters |
| 329 | # --------------------------------------------------------------------------- |
| 330 | |
| 331 | |
| 332 | def _assert_guard_blocks_ssrf(guard, same_host: str, monkeypatch): |
| 333 | assert callable(guard) |
| 334 | answers = { |
| 335 | same_host: ["93.184.216.34"], |
| 336 | f"internal.{same_host}": ["10.0.0.5"], |
| 337 | "evil.example": ["93.184.216.35"], |
| 338 | } |
| 339 | |
| 340 | def fake_getaddrinfo(name, *_args, **_kwargs): |
| 341 | if name not in answers: |
| 342 | raise socket.gaierror("unknown") |
| 343 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (ip, 0)) for ip in answers[name]] |
| 344 | |
| 345 | detect.resolves_public.cache_clear() |
| 346 | monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo) |
| 347 | try: |
| 348 | assert guard(f"https://{same_host}/ok") is True |
| 349 | for bad in ( |
| 350 | "http://169.254.169.254/latest/meta-data/", |
| 351 | "http://127.0.0.1:8080/admin", |
| 352 | "http://[::1]/secret", |
| 353 | "http://[64:ff9b::127.0.0.1]/", |
| 354 | "http://224.0.0.1/", |
| 355 | "https://evil.example/steal", |
| 356 | f"http://{same_host}/downgrade", |
| 357 | f"https://{same_host}:8443/port-hop", |
| 358 | f"https://user:pass@{same_host}/", |
| 359 | "https://internal.local/admin", |
| 360 | "file:///etc/passwd", |
| 361 | ): |
| 362 | assert guard(bad) is False, f"guard must block {bad}" |
| 363 | # Private-IP subdomains are blocked at connect time by public_only=True. |
| 364 | with pytest.raises(detect.public_host.NonPublicAddressError): |
| 365 | detect.public_host.resolve_public_addresses(f"internal.{same_host}", 443) |
| 366 | finally: |
| 367 | detect.resolves_public.cache_clear() |
| 368 | |
| 369 | |
| 370 | def test_high169_robots_and_all_dynamic_board_adapters_enforce_public_only_and_redirect_guard(monkeypatch): |
| 371 | robots.clear_cache() |
| 372 | deadline = time.monotonic() + 10 |
| 373 | date_range = ("2026-10-15", "2026-11-14") |
| 374 | |
| 375 | # 1. robots.rules_for |
| 376 | with patch.object(robots.http, "get_text", return_value="User-agent: *\nAllow: /\n") as mock_get_text: |
| 377 | robots.rules_for("careers.acme.com") |
| 378 | assert mock_get_text.call_args.kwargs.get("public_only") is True |
| 379 | assert mock_get_text.call_args.kwargs.get("max_bytes") == robots.MAX_ROBOTS_BYTES |
| 380 | _assert_guard_blocks_ssrf(mock_get_text.call_args.kwargs.get("redirect_guard"), "careers.acme.com", monkeypatch) |
| 381 | |
| 382 | # Bad hosts rejected before HTTP. |
| 383 | with patch.object(robots.http, "get_text", side_effect=AssertionError("must not fetch")): |
| 384 | for bad_host in ("127.0.0.1", "169.254.169.254", "evil.internal", "careers.acme.com:8443", "user@acme.com"): |
| 385 | assert robots.rules_for(bad_host).rules == [] |
| 386 | |
| 387 | # 2. oracle.read_board & oracle.fetch_details |
| 388 | oracle_entry = {"board": "jpmc.fa.oraclecloud.com", "site_number": "CX_1001"} |
| 389 | with patch.object(oracle.http, "get", return_value={"items": [{"TotalJobsCount": 0, "requisitionList": []}]}) as m_get: |
| 390 | oracle.read_board(oracle_entry, deadline=deadline, date_range=date_range) |
| 391 | assert m_get.call_args.kwargs.get("public_only") is True |
| 392 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "jpmc.fa.oraclecloud.com", monkeypatch) |
| 393 | # Cross-tenant oraclecloud redirect must ALSO be blocked! |
| 394 | detect.resolves_public.cache_clear() |
| 395 | monkeypatch.setattr( |
| 396 | socket, "getaddrinfo", |
| 397 | lambda name, *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))], |
| 398 | ) |
| 399 | assert m_get.call_args.kwargs["redirect_guard"]("https://other.fa.oraclecloud.com/x") is False |
| 400 | detect.resolves_public.cache_clear() |
| 401 | |
| 402 | with patch.object(oracle.http, "get", return_value={"items": [{"ExternalDescriptionStr": "<p>Hi</p>"}]}) as m_get: |
| 403 | oracle.fetch_details([{"detail_url": "https://jpmc.fa.oraclecloud.com/detail/1"}], deadline=deadline) |
| 404 | assert m_get.call_args.kwargs.get("public_only") is True |
| 405 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "jpmc.fa.oraclecloud.com", monkeypatch) |
| 406 | |
| 407 | # 3. jibe.read_board & jibe.search_story |
| 408 | jibe_entry = {"board": "careers.amd.com", "jobs_path": "/jobs"} |
| 409 | with patch.object(jibe.http, "get", return_value={"totalCount": 0, "jobs": []}) as m_get: |
| 410 | jibe.read_board(jibe_entry, deadline=deadline, date_range=date_range) |
| 411 | assert m_get.call_args.kwargs.get("public_only") is True |
| 412 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "careers.amd.com", monkeypatch) |
| 413 | |
| 414 | with patch.object(jibe.http, "get", return_value={"totalCount": 0, "jobs": []}) as m_get: |
| 415 | jibe.search_story(jibe_entry, "ai", deadline_monotonic=deadline) |
| 416 | assert m_get.call_args.kwargs.get("public_only") is True |
| 417 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "careers.amd.com", monkeypatch) |
| 418 | |
| 419 | # 4. phenom.read_board & phenom.fetch_details |
| 420 | phenom_entry = {"board": "careers.cisco.com", "country": "us", "lang": "en"} |
| 421 | with patch.object(phenom.http, "post", return_value={"refineSearch": {"totalHits": 0, "data": {"jobs": []}}}) as m_post: |
| 422 | phenom.read_board(phenom_entry, deadline=deadline, date_range=date_range) |
| 423 | assert m_post.call_args.kwargs.get("public_only") is True |
| 424 | _assert_guard_blocks_ssrf(m_post.call_args.kwargs.get("redirect_guard"), "careers.cisco.com", monkeypatch) |
| 425 | |
| 426 | with patch.object(jobs.http, "get_text", return_value="") as m_text: |
| 427 | phenom.fetch_details([{"url": "https://careers.cisco.com/us/en/job/1"}], deadline=deadline) |
| 428 | assert m_text.call_args.kwargs.get("public_only") is True |
| 429 | _assert_guard_blocks_ssrf(m_text.call_args.kwargs.get("redirect_guard"), "careers.cisco.com", monkeypatch) |
| 430 | |
| 431 | # 5. talentbrew.read_board & talentbrew.fetch_details |
| 432 | tb_entry = {"board": "jobs.boeing.com"} |
| 433 | with patch.object(talentbrew.http, "get", return_value={"results": "<ul></ul>"}) as m_get: |
| 434 | talentbrew.read_board(tb_entry, deadline=deadline, date_range=date_range) |
| 435 | assert m_get.call_args.kwargs.get("public_only") is True |
| 436 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "jobs.boeing.com", monkeypatch) |
| 437 | |
| 438 | with patch.object(jobs.http, "get_text", return_value="") as m_text: |
| 439 | talentbrew.fetch_details([{"url": "https://jobs.boeing.com/job/1"}], deadline=deadline) |
| 440 | assert m_text.call_args.kwargs.get("public_only") is True |
| 441 | _assert_guard_blocks_ssrf(m_text.call_args.kwargs.get("redirect_guard"), "jobs.boeing.com", monkeypatch) |
| 442 | |
| 443 | # 6. kula.read_board & kula.fetch_details |
| 444 | kula_entry = {"board": "careers.kula.ai", "slug": "acme"} |
| 445 | kula_html = '<script>self.__next_f.push([1, "{\\"jobs\\":[]}"])</script>' |
| 446 | with patch.object(kula.http, "get_text", return_value=kula_html) as m_text: |
| 447 | kula.read_board(kula_entry, deadline=deadline, date_range=date_range) |
| 448 | assert m_text.call_args.kwargs.get("public_only") is True |
| 449 | assert m_text.call_args.kwargs.get("max_bytes") == detect.MAX_HTML_BYTES |
| 450 | _assert_guard_blocks_ssrf(m_text.call_args.kwargs.get("redirect_guard"), "careers.kula.ai", monkeypatch) |
| 451 | |
| 452 | with patch.object(jobs.http, "get_text", return_value="") as m_text: |
| 453 | kula.fetch_details([{"url": "https://careers.kula.ai/acme/1-eng"}], deadline=deadline) |
| 454 | assert m_text.call_args.kwargs.get("public_only") is True |
| 455 | _assert_guard_blocks_ssrf(m_text.call_args.kwargs.get("redirect_guard"), "careers.kula.ai", monkeypatch) |
| 456 | |
| 457 | # 7. Eightfold & Apple readers/detail fetchers enforce public_only + redirect_guard. |
| 458 | ef_entry = {"board": "jobs.acme.com", "domain": "acme.com", "api": "pcsx"} |
| 459 | with patch.object(jobs.http, "get", return_value={"data": {"count": 0, "positions": []}}) as m_get: |
| 460 | jobs.read_eightfold_board(ef_entry, deadline=deadline, date_range=date_range) |
| 461 | assert m_get.call_args.kwargs.get("public_only") is True |
| 462 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "jobs.acme.com", monkeypatch) |
| 463 | |
| 464 | with patch.object(jobs.http, "get", return_value={"data": {"jobDescription": "<p>Hi</p>"}}) as m_get: |
| 465 | jobs.fetch_eightfold_details([{"detail_url": "https://jobs.acme.com/api/pcsx/position_details?position_id=1"}], deadline=deadline) |
| 466 | assert m_get.call_args.kwargs.get("public_only") is True |
| 467 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "jobs.acme.com", monkeypatch) |
| 468 | |
| 469 | with patch.object(jobs.http, "get", return_value={"res": {"description": "Hi"}}) as m_get: |
| 470 | jobs.fetch_apple_details([{"detail_url": "https://jobs.apple.com/api/v1/jobDetails/1?locale=en-us"}], deadline=deadline) |
| 471 | assert m_get.call_args.kwargs.get("public_only") is True |
| 472 | _assert_guard_blocks_ssrf(m_get.call_args.kwargs.get("redirect_guard"), "jobs.apple.com", monkeypatch) |
| 473 | |
| 474 | # 8. Pre-fetch validation refuses non-public board/detail URLs without calling HTTP. |
| 475 | with patch.object(http, "get", side_effect=AssertionError("must not call get")), \ |
| 476 | patch.object(http, "post", side_effect=AssertionError("must not call post")), \ |
| 477 | patch.object(http, "get_text", side_effect=AssertionError("must not call get_text")): |
| 478 | assert oracle.read_board({"board": "169.254.169.254", "site_number": "CX_1"}, deadline=deadline, date_range=date_range)[0] == [] |
| 479 | assert oracle.fetch_details([{"detail_url": "http://127.0.0.1:8080/x"}], deadline=deadline) == (0, 1) |
| 480 | assert jibe.read_board({"board": "evil.internal"}, deadline=deadline, date_range=date_range)[0] == [] |
| 481 | with pytest.raises(http.HTTPError): |
| 482 | jibe.search_story({"board": "127.0.0.1"}, "ai", deadline_monotonic=deadline) |
| 483 | assert phenom.read_board({"board": "careers.acme.com:8443"}, deadline=deadline, date_range=date_range)[0] == [] |
| 484 | assert phenom.fetch_details([{"url": "https://careers.acme.com:8443/job/1"}], deadline=deadline) == (0, 1) |
| 485 | assert talentbrew.read_board({"board": "localhost"}, deadline=deadline, date_range=date_range)[0] == [] |
| 486 | assert talentbrew.fetch_details([{"url": "http://169.254.169.254/job/1"}], deadline=deadline) == (0, 1) |
| 487 | assert kula.fetch_details([{"url": "https://evil.example/acme/1-eng"}], deadline=deadline) == (0, 1) |
| 488 | |
| 489 | |
| 490 | def test_high169_redirect_handler_blocks_302_to_metadata_with_shared_guard(): |
| 491 | handler = http._StripAuthOnCrossOriginRedirect() |
| 492 | req = urllib.request.Request("https://careers.acme.com/robots.txt") |
| 493 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 494 | setattr(req, http._REDIRECT_GUARD_ATTR, detect.same_site_redirect_guard(req.full_url)) |
| 495 | for target in ( |
| 496 | "http://169.254.169.254/latest/meta-data/", |
| 497 | "http://127.0.0.1:8080/", |
| 498 | "https://careers.acme.com:8443/robots.txt", |
| 499 | "https://evil.example/robots.txt", |
| 500 | ): |
| 501 | with pytest.raises(urllib.error.HTTPError) as exc: |
| 502 | handler.redirect_request(req, io.BytesIO(), 302, "Found", Message(), target) |
| 503 | assert exc.value.code == 403 |
| 504 | |
| 505 | |
| 506 | def test_high169_same_site_redirect_guard_skips_live_dns_by_default_so_transient_dns_retries(monkeypatch): |
| 507 | def fail_dns(*_args, **_kwargs): |
| 508 | raise socket.gaierror(-3, "Temporary failure in name resolution") |
| 509 | |
| 510 | monkeypatch.setattr(socket, "getaddrinfo", fail_dns) |
| 511 | detect.resolves_public.cache_clear() |
| 512 | try: |
| 513 | # Default guard (resolves=None) does not run live DNS, so transient DNS |
| 514 | # failures are NOT converted into non-retryable HTTP 403 errors; live |
| 515 | # DNS + IP pinning happens in http's public_only=True transport instead. |
| 516 | guard = detect.same_site_redirect_guard("https://careers.acme.com/robots.txt") |
| 517 | assert guard("https://careers.acme.com/next") is True |
| 518 | assert guard("https://evil.example/next") is False |
| 519 | assert guard("http://careers.acme.com/downgrade") is False |
| 520 | |
| 521 | handler = http._StripAuthOnCrossOriginRedirect() |
| 522 | req = urllib.request.Request("https://careers.acme.com/robots.txt") |
| 523 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 524 | setattr(req, http._REDIRECT_GUARD_ATTR, guard) |
| 525 | followed = handler.redirect_request( |
| 526 | req, io.BytesIO(), 302, "Found", Message(), "https://careers.acme.com/next", |
| 527 | ) |
| 528 | assert followed is not None and followed.full_url == "https://careers.acme.com/next" |
| 529 | |
| 530 | # Explicit resolves=... is still honored when callers request it. |
| 531 | explicit_guard = detect.same_site_redirect_guard( |
| 532 | "https://careers.acme.com/robots.txt", resolves=detect.resolves_public, |
| 533 | ) |
| 534 | assert explicit_guard("https://careers.acme.com/next") is False |
| 535 | finally: |
| 536 | detect.resolves_public.cache_clear() |
| 537 | |
| 538 | |
| 539 | # --------------------------------------------------------------------------- |
| 540 | # HIGH-171: _same_site public-suffix/multi-tenant/IP bypass & Phenom base_url |
| 541 | # --------------------------------------------------------------------------- |
| 542 | |
| 543 | |
| 544 | def test_high169_protocol_downgrade_blocked_while_upgrade_allowed(monkeypatch): |
| 545 | detect.resolves_public.cache_clear() |
| 546 | monkeypatch.setattr( |
| 547 | socket, |
| 548 | "getaddrinfo", |
| 549 | lambda name, *_a, **_k: [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))], |
| 550 | ) |
| 551 | try: |
| 552 | https_guard = detect.same_site_redirect_guard("https://careers.acme.com/robots.txt") |
| 553 | assert https_guard("https://careers.acme.com/next") is True |
| 554 | assert https_guard("http://careers.acme.com/next") is False |
| 555 | |
| 556 | http_guard = detect.same_site_redirect_guard("http://careers.acme.com/robots.txt") |
| 557 | assert http_guard("http://careers.acme.com/step1") is True |
| 558 | assert http_guard("https://careers.acme.com/next") is True |
| 559 | # Guard itself is stateless so retries from http:// still succeed. |
| 560 | assert http_guard("http://careers.acme.com/step1") is True |
| 561 | |
| 562 | careers_https_guard = detect.public_redirect_guard("https://acme.com/careers") |
| 563 | assert careers_https_guard("https://jobs.acme.com/openings") is True |
| 564 | assert careers_https_guard("http://jobs.acme.com/openings") is False |
| 565 | |
| 566 | careers_http_guard = detect.public_redirect_guard("http://acme.com/careers") |
| 567 | assert careers_http_guard("https://jobs.acme.com/openings") is True |
| 568 | assert careers_http_guard("http://jobs.acme.com/step1") is True |
| 569 | |
| 570 | # _careers_fetch attaches the non-downgrade guard to http.get_text. |
| 571 | with patch.object(jobs.http, "get_text", return_value="<html></html>") as mock_get_text: |
| 572 | jobs._careers_fetch("https://acme.com/careers", "acme.com", guessed=False) |
| 573 | attached_guard = mock_get_text.call_args.kwargs.get("redirect_guard") |
| 574 | assert callable(attached_guard) |
| 575 | assert attached_guard("https://jobs.acme.com/") is True |
| 576 | assert attached_guard("http://jobs.acme.com/") is False |
| 577 | |
| 578 | # Multi-hop http -> https -> http is blocked statelessly by http._StripAuthOnCrossOriginRedirect. |
| 579 | handler = http._StripAuthOnCrossOriginRedirect() |
| 580 | req0 = urllib.request.Request("http://careers.acme.com/start") |
| 581 | setattr(req0, http._REDIRECT_GUARD_ATTR, detect.same_site_redirect_guard("http://careers.acme.com/start")) |
| 582 | req1 = handler.redirect_request(req0, None, 302, "Found", {}, "https://careers.acme.com/upgraded") |
| 583 | assert req1 is not None and req1.full_url == "https://careers.acme.com/upgraded" |
| 584 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 585 | handler.redirect_request(req1, None, 302, "Found", {}, "http://careers.acme.com/downgraded") |
| 586 | assert exc_info.value.code == 403 |
| 587 | assert "HTTPS downgrade" in str(exc_info.value.reason) |
| 588 | |
| 589 | # End-to-end through http.request: |
| 590 | # 1) http -> https -> http is refused with 403. |
| 591 | # 2) http -> http -> https retry after transient error succeeds on attempt 2. |
| 592 | import io |
| 593 | from email.message import Message |
| 594 | |
| 595 | def make_resp(url: str, status: int, body: bytes = b"", headers_dict: dict[str, str] | None = None): |
| 596 | msg = Message() |
| 597 | for k, v in (headers_dict or {}).items(): |
| 598 | msg[k] = v |
| 599 | resp = urllib.response.addinfourl(io.BytesIO(body), msg, url, code=status) |
| 600 | resp.msg = "OK" if status == 200 else "Found" |
| 601 | return resp |
| 602 | |
| 603 | class _FakeTransport(urllib.request.BaseHandler): |
| 604 | def __init__(self, script): |
| 605 | self._script = script |
| 606 | |
| 607 | def http_open(self, req): |
| 608 | return self._script(req) |
| 609 | |
| 610 | def https_open(self, req): |
| 611 | return self._script(req) |
| 612 | |
| 613 | def build_test_opener(script): |
| 614 | opener = urllib.request.OpenerDirector() |
| 615 | opener.add_handler(_FakeTransport(script)) |
| 616 | opener.add_handler(http._StripAuthOnCrossOriginRedirect()) |
| 617 | opener.add_handler(urllib.request.HTTPErrorProcessor()) |
| 618 | opener.add_handler(urllib.request.HTTPDefaultErrorHandler()) |
| 619 | return opener |
| 620 | |
| 621 | def downgrade_script(req): |
| 622 | if req.full_url == "http://acme.com/start": |
| 623 | return make_resp(req.full_url, 302, headers_dict={"Location": "https://acme.com/secure"}) |
| 624 | if req.full_url == "https://acme.com/secure": |
| 625 | return make_resp(req.full_url, 302, headers_dict={"Location": "http://acme.com/downgrade"}) |
| 626 | return make_resp(req.full_url, 200, b"should-not-reach") |
| 627 | |
| 628 | monkeypatch.setattr(http, "_opener", build_test_opener(downgrade_script)) |
| 629 | with pytest.raises(http.HTTPError) as downgrade_err: |
| 630 | http.request( |
| 631 | "GET", |
| 632 | "http://acme.com/start", |
| 633 | retries=1, |
| 634 | raw=True, |
| 635 | redirect_guard=detect.same_site_redirect_guard("http://acme.com/start"), |
| 636 | ) |
| 637 | assert downgrade_err.value.status_code == 403 |
| 638 | |
| 639 | hop2_attempts = {"count": 0} |
| 640 | visited_urls: list[str] = [] |
| 641 | |
| 642 | def retry_script(req): |
| 643 | visited_urls.append(req.full_url) |
| 644 | if req.full_url == "http://acme.com/start": |
| 645 | return make_resp(req.full_url, 302, headers_dict={"Location": "http://acme.com/hop1"}) |
| 646 | if req.full_url == "http://acme.com/hop1": |
| 647 | return make_resp(req.full_url, 302, headers_dict={"Location": "https://acme.com/hop2"}) |
| 648 | if req.full_url == "https://acme.com/hop2": |
| 649 | hop2_attempts["count"] += 1 |
| 650 | if hop2_attempts["count"] == 1: |
| 651 | raise urllib.error.URLError(socket.gaierror(-3, "Temporary failure")) |
| 652 | return make_resp(req.full_url, 200, b"recovered-after-retry") |
| 653 | return make_resp(req.full_url, 404, b"missing") |
| 654 | |
| 655 | monkeypatch.setattr(http, "_opener", build_test_opener(retry_script)) |
| 656 | monkeypatch.setattr(http.time, "sleep", lambda _s: None) |
| 657 | body = http.request( |
| 658 | "GET", |
| 659 | "http://acme.com/start", |
| 660 | retries=2, |
| 661 | raw=True, |
| 662 | redirect_guard=detect.same_site_redirect_guard("http://acme.com/start"), |
| 663 | ) |
| 664 | assert body == "recovered-after-retry" |
| 665 | assert hop2_attempts["count"] == 2 |
| 666 | assert visited_urls == [ |
| 667 | "http://acme.com/start", "http://acme.com/hop1", "https://acme.com/hop2", |
| 668 | "http://acme.com/start", "http://acme.com/hop1", "https://acme.com/hop2", |
| 669 | ] |
| 670 | |
| 671 | # sitemap._on_site rejects https -> http landed downgrade. |
| 672 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 673 | assert sitemap._on_site( |
| 674 | "https://jobs.acme.com/en/jobs/1", |
| 675 | lambda landed: (landed.append("http://jobs.acme.com/en/jobs/1"), "downgraded")[1], |
| 676 | ) is None |
| 677 | assert sitemap._on_site( |
| 678 | "http://jobs.acme.com/en/jobs/1", |
| 679 | lambda landed: (landed.extend(["https://jobs.acme.com/a", "http://jobs.acme.com/b"]), "downgraded")[1], |
| 680 | ) is None |
| 681 | finally: |
| 682 | detect.resolves_public.cache_clear() |
| 683 | |
| 684 | |
| 685 | def test_high171_same_site_blocks_public_suffixes_multi_tenant_and_ips(): |
| 686 | for left, right in ( |
| 687 | ("evil.co.uk", "careers.barclays.co.uk"), |
| 688 | ("evil.com.au", "jobs.foo.com.au"), |
| 689 | ("evil.org.uk", "jobs.foo.org.uk"), |
| 690 | ("evil.github.io", "app.github.io"), |
| 691 | ("evil.netlify.app", "app.netlify.app"), |
| 692 | ("evil.vercel.app", "app.vercel.app"), |
| 693 | ("evil.pages.dev", "app.pages.dev"), |
| 694 | ("evil.herokuapp.com", "app.herokuapp.com"), |
| 695 | ("evil.s3.amazonaws.com", "victim.s3.amazonaws.com"), |
| 696 | ("evil.s3.amazonaws.com", "s3.amazonaws.com"), |
| 697 | ("evil.github.io", "github.io"), |
| 698 | ("evil.co.uk", "co.uk"), |
| 699 | ("127.0.0.1", "10.0.0.1"), |
| 700 | ("127.0.0.1", "127.0.0.1"), |
| 701 | ("93.184.216.34", "93.184.216.34"), |
| 702 | ("::1", "::1"), |
| 703 | ("jobs.acme.com:8443", "acme.com"), |
| 704 | ("user@jobs.acme.com", "acme.com"), |
| 705 | ): |
| 706 | assert detect._same_site(left, right) is False, f"detect._same_site({left!r}, {right!r}) must be False" |
| 707 | assert jobs._same_site(left, right) is False, f"jobs._same_site({left!r}, {right!r}) must be False" |
| 708 | |
| 709 | assert detect.registrable_domain("s3.amazonaws.com") == "" |
| 710 | assert detect.registrable_domain("www.s3.amazonaws.com") == "" |
| 711 | assert detect.registrable_domain("victim.s3.amazonaws.com") == "victim.s3.amazonaws.com" |
| 712 | assert detect._same_site("sub.victim.s3.amazonaws.com", "victim.s3.amazonaws.com") is True |
| 713 | assert jobs._same_site("sub.victim.s3.amazonaws.com", "victim.s3.amazonaws.com") is True |
| 714 | assert detect._same_site("careers.barclays.co.uk", "www.barclays.co.uk") is True |
| 715 | assert detect._same_site("sub.app.github.io", "app.github.io") is True |
| 716 | assert jobs._same_site("sub.app.github.io", "app.github.io") is True |
| 717 | |
| 718 | |
| 719 | def test_high171_phenom_rejects_port_userinfo_and_canonicalizes_base_url(): |
| 720 | template = ( |
| 721 | '<script src="https://cdn.phenompeople.com/x.js"></script>' |
| 722 | '<script>phApp.ddo={}; var cfg={"baseUrl":"%s"};</script>' |
| 723 | ) |
| 724 | # Arbitrary non-443 port and userinfo must be rejected completely. |
| 725 | for poisoned in ( |
| 726 | "https://user:pass@careers.victim.com:8443/us/en/", |
| 727 | "https://user@careers.victim.com/us/en/", |
| 728 | "https://careers.victim.com:8443/us/en/", |
| 729 | "https://careers.victim.com:80/us/en/", |
| 730 | "https://evil.co.uk/us/en/", |
| 731 | "https://127.0.0.1/us/en/", |
| 732 | ): |
| 733 | assert detect.detect_platform(template % poisoned, "https://careers.victim.com/us/en") is None |
| 734 | |
| 735 | # Explicit :443 is canonicalized without port in entry["base_url"]. |
| 736 | detected = detect.detect_platform( |
| 737 | template % "https://careers.victim.com:443/us/en/", |
| 738 | "https://www.victim.com/careers", |
| 739 | ) |
| 740 | assert detected == ( |
| 741 | "phenom", |
| 742 | { |
| 743 | "provider": "phenom", |
| 744 | "board": "careers.victim.com", |
| 745 | "country": "us", |
| 746 | "lang": "en", |
| 747 | "base_url": "https://careers.victim.com/us/en/", |
| 748 | }, |
| 749 | ) |
| 750 | |
| 751 | # Direct phenom.parse_listing sanitizes tampered base_url and URL-encodes jobId. |
| 752 | payload = {"refineSearch": {"totalHits": 1, "data": {"jobs": [{"title": "Eng", "jobId": "../../admin?x=1#"}]}}} |
| 753 | items, _ = phenom.parse_listing( |
| 754 | payload, |
| 755 | {"board": "careers.victim.com", "base_url": "https://user@careers.victim.com:8443/us/en/"}, |
| 756 | ) |
| 757 | assert items[0]["url"] == "https://careers.victim.com/job/..%2F..%2Fadmin%3Fx%3D1%23" |
| 758 | |
| 759 | # Oracle data-apibaseurl must also reject non-443 ports while allowing :443. |
| 760 | oracle_bad_port = '<div data-apibaseurl="https://jobs.acme.com:8443" data-sitenumber="CX_1"></div>' |
| 761 | assert detect.detect_platform(oracle_bad_port, "https://www.acme.com/careers") is None |
| 762 | |
| 763 | |
| 764 | def test_high171_detect_html_parsers_resist_redos(): |
| 765 | cases = [ |
| 766 | ( |
| 767 | "detect jibe <link", |
| 768 | lambda: detect.detect_platform( |
| 769 | '<script src="https://assets.jibecdn.com/a.js"></script>' + ("<link " * 50_000), |
| 770 | "https://careers.amd.com/jobs", |
| 771 | ), |
| 772 | ("jibe", {"provider": "jibe", "board": "careers.amd.com", "jobs_path": "/jobs"}), |
| 773 | ), |
| 774 | ( |
| 775 | "detect oracle data-apibaseurl", |
| 776 | lambda: detect.detect_platform( |
| 777 | 'data-apibaseurl="https://jobs.acme.com" ' * 50_000, |
| 778 | "https://acme.com/careers", |
| 779 | ), |
| 780 | None, |
| 781 | ), |
| 782 | ( |
| 783 | "detect eightfoldCareerUrl", |
| 784 | lambda: detect.eightfold_career_url("eightFoldCareerUrl " * 50_000), |
| 785 | "", |
| 786 | ), |
| 787 | ( |
| 788 | "detect eightfoldCareerUrl unclosed tag spaces", |
| 789 | lambda: detect.eightfold_career_url("eightFoldCareerUrl <div" + (" " * 40_000)), |
| 790 | "", |
| 791 | ), |
| 792 | ( |
| 793 | "detect oracle unclosed tag spaces", |
| 794 | lambda: detect._oracle("data-apibaseurl data-sitenumber <div" + (" " * 40_000), "acme.com"), |
| 795 | None, |
| 796 | ), |
| 797 | ] |
| 798 | for label, fn, expected in cases: |
| 799 | cpu_start = time.process_time() |
| 800 | assert fn() == expected |
| 801 | cpu_elapsed = time.process_time() - cpu_start |
| 802 | assert cpu_elapsed < 0.5, f"{label} took {cpu_elapsed:.4f}s CPU (possible ReDoS)" |
| 803 | |
| 804 | # Reversed attribute order on <link rel="canonical"> works in _jibe. |
| 805 | jibe_rev = ( |
| 806 | '<link href="https://careers.amd.com/careers-home/jobs" rel="canonical">' |
| 807 | '<script src="https://assets.jibecdn.com/app.js"></script>' |
| 808 | ) |
| 809 | assert detect.detect_platform(jibe_rev, "https://careers.amd.com/") == ( |
| 810 | "jibe", {"provider": "jibe", "board": "careers.amd.com", "jobs_path": "/careers-home/jobs"}, |
| 811 | ) |
| 812 | |
| 813 | |
| 814 | # --------------------------------------------------------------------------- |
| 815 | # HIGH-173: Multicast/NAT64/6to4 blocking, bounded-TTL DNS cache, ports, job_urls |
| 816 | # --------------------------------------------------------------------------- |
| 817 | |
| 818 | |
| 819 | @pytest.mark.parametrize( |
| 820 | "bad_ip", |
| 821 | [ |
| 822 | "224.0.0.1", # IPv4 multicast (is_global=True in py3.12!) |
| 823 | "ff02::1", # IPv6 link-local multicast |
| 824 | "64:ff9b::127.0.0.1", # NAT64 loopback |
| 825 | "64:ff9b::169.254.169.254", # NAT64 AWS metadata |
| 826 | "64:ff9b::93.184.216.34", # NAT64 well-known prefix |
| 827 | "64:ff9b:1::127.0.0.1", # NAT64 local prefix |
| 828 | "2002:7f00:0001::", # 6to4 loopback |
| 829 | "2002:a9fe:a9fe::", # 6to4 metadata |
| 830 | "::ffff:127.0.0.1", # IPv4-mapped loopback |
| 831 | "100.64.0.1", # CGNAT |
| 832 | "0.0.0.0", # Unspecified IPv4 |
| 833 | "::", # Unspecified IPv6 |
| 834 | "169.254.169.254", # Link-local metadata |
| 835 | "fe80::1", # IPv6 link-local |
| 836 | "127.0.0.1", # Loopback |
| 837 | "::1", # IPv6 loopback |
| 838 | "10.0.0.1", # RFC1918 private |
| 839 | ], |
| 840 | ) |
| 841 | def test_high173_resolver_and_syntax_block_all_non_public_ip_classes(bad_ip: str, monkeypatch): |
| 842 | url_host = f"[{bad_ip}]" if ":" in bad_ip else bad_ip |
| 843 | assert detect.is_safe_public_url(f"http://{url_host}/sitemap.xml") is False |
| 844 | assert sitemap._public_url(f"http://{url_host}/sitemap.xml", url_host) is False |
| 845 | |
| 846 | # Also test when a domain resolves to [public, bad_ip]. |
| 847 | resolver = detect._BoundedPublicResolver(ttl_seconds=5.0) |
| 848 | monkeypatch.setattr( |
| 849 | socket, |
| 850 | "getaddrinfo", |
| 851 | lambda _name, *_a, **_k: [ |
| 852 | (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0)), |
| 853 | (socket.AF_INET6 if ":" in bad_ip else socket.AF_INET, socket.SOCK_STREAM, 6, "", (bad_ip, 0)), |
| 854 | ], |
| 855 | ) |
| 856 | assert resolver("mixed.example") is False |
| 857 | |
| 858 | |
| 859 | def test_high173_dns_cache_expires_by_ttl_and_is_thread_safe(monkeypatch): |
| 860 | now = [100.0] |
| 861 | monkeypatch.setattr(detect.time, "monotonic", lambda: now[0]) |
| 862 | answers = {"rebind.example": ["93.184.216.34"]} |
| 863 | lookups = [] |
| 864 | |
| 865 | def fake_getaddrinfo(name, *_args, **_kwargs): |
| 866 | lookups.append(name) |
| 867 | ips = answers.get(name, ["93.184.216.34"]) |
| 868 | return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 0)) for ip in ips] |
| 869 | |
| 870 | monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo) |
| 871 | resolver = detect._BoundedPublicResolver(maxsize=32, ttl_seconds=2.0) |
| 872 | |
| 873 | assert resolver("rebind.example") is True |
| 874 | assert len(lookups) == 1 |
| 875 | # Within TTL: cached hit without another lookup. |
| 876 | now[0] = 101.5 |
| 877 | assert resolver("rebind.example") is True |
| 878 | assert len(lookups) == 1 |
| 879 | # DNS rebinds to loopback and TTL expires -> fresh lookup refuses! |
| 880 | answers["rebind.example"] = ["127.0.0.1"] |
| 881 | now[0] = 102.1 |
| 882 | assert resolver("rebind.example") is False |
| 883 | assert len(lookups) == 2 |
| 884 | |
| 885 | # Concurrent calls must remain thread-safe and honor maxsize cap. |
| 886 | with ThreadPoolExecutor(max_workers=8) as pool: |
| 887 | results = list(pool.map(lambda i: resolver(f"h{i % 100}.example"), range(400))) |
| 888 | assert all(results) |
| 889 | assert len(resolver._cache) <= 32 |
| 890 | resolver.cache_clear() |
| 891 | assert len(resolver._cache) == 0 |
| 892 | |
| 893 | |
| 894 | def test_high173_dns_resolver_preserves_single_trailing_dot_and_rejects_double_dot(monkeypatch): |
| 895 | seen: list[str] = [] |
| 896 | |
| 897 | def fake_getaddrinfo(name, *_args, **_kwargs): |
| 898 | seen.append(name) |
| 899 | return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0))] |
| 900 | |
| 901 | monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo) |
| 902 | resolver = detect._BoundedPublicResolver(ttl_seconds=5.0) |
| 903 | assert resolver("example.com.") is True |
| 904 | assert seen == ["example.com."] |
| 905 | assert resolver("example.com..") is False |
| 906 | assert resolver(".example.com") is False |
| 907 | assert resolver("localhost.") is False |
| 908 | assert seen == ["example.com."] |
| 909 | |
| 910 | |
| 911 | def test_high173_sitemap_ports_guard_hostname_and_job_urls_host_validation(monkeypatch): |
| 912 | monkeypatch.setattr(sitemap, "_resolves_public", lambda name: "internal" not in name) |
| 913 | |
| 914 | # Arbitrary/mismatched ports and userinfo blocked. |
| 915 | for bad in ( |
| 916 | "http://jobs.example.com:6379/sitemap.xml", |
| 917 | "https://jobs.example.com:8443/sitemap.xml", |
| 918 | "https://jobs.example.com:80/sitemap.xml", |
| 919 | "http://jobs.example.com:443/sitemap.xml", |
| 920 | "https://user@jobs.example.com/sitemap.xml", |
| 921 | ): |
| 922 | assert sitemap._public_url(bad, "jobs.example.com") is False |
| 923 | |
| 924 | # Valid explicit :443 works in _public_url, _guard, and _on_site (fixes netloc vs hostname mismatch). |
| 925 | assert sitemap._public_url("https://jobs.example.com:443/sitemap.xml", "jobs.example.com") is True |
| 926 | guard = sitemap._guard("https://jobs.example.com:443/sitemap.xml") |
| 927 | assert guard("https://jobs.example.com/en/jobs/12345") is True |
| 928 | assert guard("https://jobs.example.com:8443/en/jobs/12345") is False |
| 929 | assert guard("http://169.254.169.254/latest/meta-data/") is False |
| 930 | assert guard("https://internal.jobs.example.com/en/jobs/1") is False |
| 931 | |
| 932 | assert sitemap._on_site( |
| 933 | "https://jobs.example.com:443/en/jobs/12345", |
| 934 | lambda landed: (landed.append("https://jobs.example.com/en/jobs/12345"), "ok")[1], |
| 935 | ) == "ok" |
| 936 | assert sitemap._on_site( |
| 937 | "https://jobs.example.com:443/en/jobs/12345", |
| 938 | lambda landed: (landed.append("https://jobs.example.com:8443/x"), "bad")[1], |
| 939 | ) is None |
| 940 | |
| 941 | # Unvalidated hosts in job_urls must NEVER reach robots.rules_for. |
| 942 | with patch.object(robots, "rules_for", side_effect=AssertionError("must not call rules_for")): |
| 943 | host, urls, missed = sitemap.job_urls( |
| 944 | [ |
| 945 | "169.254.169.254", |
| 946 | "127.0.0.1", |
| 947 | "localhost", |
| 948 | "evil.internal", |
| 949 | "jobs.example.com:6379", |
| 950 | "user@jobs.example.com", |
| 951 | "[64:ff9b::127.0.0.1]", |
| 952 | "224.0.0.1", |
| 953 | ], |
| 954 | deadline=time.monotonic() + 5, |
| 955 | ) |
| 956 | assert (host, urls, missed) == ("", [], False) |
| 957 | |
| 958 | |
| 959 | # --------------------------------------------------------------------------- |
| 960 | # HIGH-174: Sitemap XML / TalentBrew / Kula linear-time parsing & correctness |
| 961 | # --------------------------------------------------------------------------- |
| 962 | |
| 963 | |
| 964 | def test_high174_sitemap_talentbrew_kula_resist_redos_in_under_100ms(): |
| 965 | cases = [ |
| 966 | ("sitemap unclosed <url>", lambda: sitemap._parse_sitemap_xml("<url>" * 50_000)), |
| 967 | ("sitemap unclosed <loc>", lambda: sitemap._parse_sitemap_xml("<loc>" * 50_000)), |
| 968 | ("sitemap title jsonld", lambda: sitemap.title_from_page('"@type":"JobPosting"' * 50_000)), |
| 969 | ("sitemap title meta", lambda: sitemap.title_from_page("<meta " * 60_000)), |
| 970 | ("sitemap title <title>", lambda: sitemap.title_from_page("<title>" * 60_000)), |
| 971 | ("detect unclosed </script ", lambda: detect.extract_script_bodies("<script>" + ("</script " * 50_000))), |
| 972 | ("detect unclosed </title ", lambda: detect.extract_title_texts("<title>" + ("</title " * 50_000))), |
| 973 | ( |
| 974 | "talentbrew unclosed <li>", |
| 975 | lambda: talentbrew.parse_listing({"results": "<li>" * 50_000}, {"board": "jobs.example.com"}), |
| 976 | ), |
| 977 | ( |
| 978 | "talentbrew unclosed <li><a>", |
| 979 | lambda: talentbrew.parse_listing( |
| 980 | {"results": '<li><a href="/job/1">' * 50_000}, {"board": "jobs.example.com"}, |
| 981 | ), |
| 982 | ), |
| 983 | ( |
| 984 | "talentbrew unclosed <li><a> with trailing </a>", |
| 985 | lambda: talentbrew.parse_listing( |
| 986 | {"results": ('<li><a href="/job/1">' * 50_000) + "Role</a>"}, {"board": "jobs.example.com"}, |
| 987 | ), |
| 988 | ), |
| 989 | ( |
| 990 | "talentbrew unclosed <a>", |
| 991 | lambda: talentbrew.parse_listing({"results": '<a href="/job/1">' * 50_000}, {"board": "jobs.example.com"}), |
| 992 | ), |
| 993 | ( |
| 994 | "talentbrew unclosed <span>", |
| 995 | lambda: talentbrew.parse_listing( |
| 996 | {"results": '<li><a href="/job/1">Role</a>' + ('<span class="location">' * 50_000) + "</li>"}, |
| 997 | {"board": "jobs.example.com"}, |
| 998 | ), |
| 999 | ), |
| 1000 | ("kula unclosed push", lambda: kula._payload("self.__next_f.push([" * 50_000)), |
| 1001 | ( |
| 1002 | "kula escaped-quote push", |
| 1003 | lambda: kula._payload('<script>self.__next_f.push([1,"' + '\\"self.__next_f.push([1,"' * 5_000 + "</script>"), |
| 1004 | ), |
| 1005 | ("kula role_list escaped-quote", lambda: kula._role_list('"jobs":["' + '\\""jobs":["' * 5_000)), |
| 1006 | ( |
| 1007 | "kula role_list deep nested arrays 200", |
| 1008 | lambda: kula._role_list(('{"jobs":[1, ' * 200) + "1" + ("]}" * 200)), |
| 1009 | ), |
| 1010 | ( |
| 1011 | "kula role_list deep nested arrays 2000", |
| 1012 | lambda: kula._role_list(('{"jobs":[1, ' * 2000) + "1" + ("]}" * 2000)), |
| 1013 | ), |
| 1014 | ( |
| 1015 | "kula meta flood", |
| 1016 | lambda: kula.parse_listing( |
| 1017 | ("<meta " * 60_000) + '<script>self.__next_f.push([1,"{\\"jobs\\":[]}"])</script>', |
| 1018 | {"slug": "acme"}, |
| 1019 | ), |
| 1020 | ), |
| 1021 | ] |
| 1022 | for label, fn in cases: |
| 1023 | cpu_start = time.process_time() |
| 1024 | fn() |
| 1025 | cpu_elapsed = time.process_time() - cpu_start |
| 1026 | assert cpu_elapsed < 1.0, f"{label} took {cpu_elapsed:.4f}s CPU (possible ReDoS)" |
| 1027 | |
| 1028 | # Nested legitimate role list inside a non-dict outer "jobs" array still extracts. |
| 1029 | nested_valid = '{"jobs":[1, {"jobs":[{"id":7,"title":"Security Engineer"}]}]}' |
| 1030 | assert kula._role_list(nested_valid) == [{"id": 7, "title": "Security Engineer"}] |
| 1031 | |
| 1032 | |
| 1033 | def test_high174_sitemap_xml_rejects_dtd_entity_and_supports_namespaces_cdata(): |
| 1034 | xxe = ( |
| 1035 | '<?xml version="1.0"?>' |
| 1036 | '<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>' |
| 1037 | "<urlset><url><loc>https://jobs.example.com/jobs/12345-eng</loc></url></urlset>" |
| 1038 | ) |
| 1039 | assert sitemap._parse_sitemap_xml(xxe) == (None, []) |
| 1040 | |
| 1041 | cdata_xml = ( |
| 1042 | '<?xml version="1.0" encoding="UTF-8"?>' |
| 1043 | '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1044 | "<url><loc><![CDATA[https://jobs.example.com/jobs/12345-staff-engineer?a=1&b=2]]></loc>" |
| 1045 | "<lastmod>2026-11-14</lastmod></url></urlset>" |
| 1046 | ) |
| 1047 | kind, entries = sitemap._parse_sitemap_xml(cdata_xml) |
| 1048 | assert kind == "urlset" |
| 1049 | assert entries == [("https://jobs.example.com/jobs/12345-staff-engineer?a=1&b=2", "2026-11-14")] |
| 1050 | |
| 1051 | |
| 1052 | def test_high174_sitemap_title_parsing_fixes_and_single_call_per_page(monkeypatch): |
| 1053 | # "title" appearing BEFORE "@type": "JobPosting" must be extracted. |
| 1054 | title_first = ( |
| 1055 | '<script type="application/ld+json">' |
| 1056 | '{"title": "Principal Security Engineer", "@type": "JobPosting"}' |
| 1057 | "</script>" |
| 1058 | ) |
| 1059 | assert sitemap.title_from_page(title_first, "Acme") == "Principal Security Engineer" |
| 1060 | |
| 1061 | # JobPosting omitting "title" must NEVER cross </script> to steal an unrelated title. |
| 1062 | no_cross_script = ( |
| 1063 | '<script type="application/ld+json">{"@type": "JobPosting", "datePosted": "2026-11-01"}</script>' |
| 1064 | '<script type="application/json">{"title": "Cookie Banner Preferences"}</script>' |
| 1065 | '<meta content="Real Role Title - Acme Careers" property="og:title">' |
| 1066 | ) |
| 1067 | assert sitemap.title_from_page(no_cross_script, "Acme") == "Real Role Title" |
| 1068 | |
| 1069 | # _titles_from_pages computes title_from_page at most once per page. |
| 1070 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 1071 | calls = [] |
| 1072 | real_title = sitemap.title_from_page |
| 1073 | |
| 1074 | def spy_title(html: str, site_name: str = "") -> str: |
| 1075 | calls.append(html) |
| 1076 | return real_title(html, site_name) |
| 1077 | |
| 1078 | monkeypatch.setattr(sitemap, "title_from_page", spy_title) |
| 1079 | urls = [f"https://careers.acme.com/jobs/R-{100000 + i}" for i in range(10)] |
| 1080 | with patch.object(jobs.http, "get_text", side_effect=lambda u, **kw: f"<title>Role {u[-3:]}</title>"): |
| 1081 | result = sitemap._titles_from_pages(urls, "Acme", time.monotonic() + 10) |
| 1082 | assert len(result) == 10 |
| 1083 | assert len(calls) == 10 |
| 1084 | |
| 1085 | |
| 1086 | def test_high174_talentbrew_nested_li_and_kula_multi_push_parsing_fixes(): |
| 1087 | nested_html = ( |
| 1088 | '<section data-total-results="2"><ul>' |
| 1089 | "<li>" |
| 1090 | '<a href="/job/seattle/staff-engineer/1/100"><span>Staff Engineer</span></a>' |
| 1091 | '<ul class="badges"><li>Remote</li><li>Security</li></ul>' |
| 1092 | '<span class="search-results__job-info location">Seattle, WA</span>' |
| 1093 | '<span class="search-results__job-info date">11/13/2026</span>' |
| 1094 | "</li>" |
| 1095 | "</ul></section>" |
| 1096 | ) |
| 1097 | tb_items, total = talentbrew.parse_listing({"results": nested_html}, {"board": "jobs.acme.com"}) |
| 1098 | assert total == 2 and len(tb_items) == 1 |
| 1099 | assert tb_items[0]["title"] == "Staff Engineer" |
| 1100 | assert tb_items[0]["location"] == "Seattle, WA" |
| 1101 | assert tb_items[0]["date"] == "2026-11-13" |
| 1102 | |
| 1103 | # Multiple self.__next_f.push([...]) calls inside ONE <script> tag must all parse. |
| 1104 | multi_push_html = ( |
| 1105 | '<html><head><meta content="Acme Co" name="application-name"></head><body>' |
| 1106 | '<a href="/acme/101-platform-engineer">Platform Engineer</a>' |
| 1107 | '<script>self.__next_f.push([1, "prefix "]);' |
| 1108 | 'self.__next_f.push([1, "{\\"jobs\\":[{\\"id\\":101,\\"title\\":\\"Platform Engineer\\",' |
| 1109 | '\\"launch_at\\":\\"2026-11-10T00:00:00Z\\"}]}"]);</script>' |
| 1110 | "</body></html>" |
| 1111 | ) |
| 1112 | kula_items, kula_total = kula.parse_listing(multi_push_html, {"slug": "acme"}) |
| 1113 | assert kula_total == 1 and len(kula_items) == 1 |
| 1114 | assert kula_items[0]["title"] == "Platform Engineer" |
| 1115 | assert kula_items[0]["company_name"] == "Acme Co" |
| 1116 | assert kula_items[0]["url"] == "https://careers.kula.ai/acme/101-platform-engineer" |
| 1117 | |
| 1118 | |
| 1119 | def test_high174_response_byte_caps_passed_to_http_get_text(monkeypatch): |
| 1120 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 1121 | with patch.object(jobs.http, "get_text", return_value="<urlset></urlset>") as mock_get_text: |
| 1122 | sitemap._fetch("https://jobs.acme.com/sitemap.xml", time.monotonic() + 5) |
| 1123 | assert mock_get_text.call_args.kwargs.get("max_bytes") == sitemap.MAX_SITEMAP_BYTES |
| 1124 | |
| 1125 | with patch.object(jobs.http, "get_text", return_value="<html></html>") as mock_get_text: |
| 1126 | jobs._careers_fetch("https://acme.com/careers", "acme.com", guessed=False) |
| 1127 | assert mock_get_text.call_args.kwargs.get("max_bytes") == detect.MAX_HTML_BYTES |
| 1128 | assert mock_get_text.call_args.kwargs.get("public_only") is True |
| 1129 | assert callable(mock_get_text.call_args.kwargs.get("redirect_guard")) |
| 1130 | |
| 1131 | |
| 1132 | def test_high164_turkish_dotted_i_does_not_corrupt_html_extraction(): |
| 1133 | # U+0130 ("İ") expands to 2 codepoints ("i\u0307") under .lower(), shifting |
| 1134 | # offsets if code slices original HTML with indices from html.lower(). |
| 1135 | prefix = "<p>İstanbul Office — İstanbul, Türkiye — İstanbul Engineering</p>" |
| 1136 | |
| 1137 | jsonld_and_title = ( |
| 1138 | prefix |
| 1139 | + '<title>Principal Systems Engineer - Acme Careers</title>' |
| 1140 | + '<script type="application/ld+json">' |
| 1141 | + '{"@type":"JobPosting","title":"Staff Security Engineer","description":"Build secure systems."}' |
| 1142 | + "</script>" |
| 1143 | ) |
| 1144 | assert detect.extract_title_texts(jsonld_and_title) == ["Principal Systems Engineer - Acme Careers"] |
| 1145 | blocks = detect.extract_jsonld_blocks(jsonld_and_title) |
| 1146 | assert len(blocks) == 1 |
| 1147 | assert blocks[0] == '{"@type":"JobPosting","title":"Staff Security Engineer","description":"Build secure systems."}' |
| 1148 | found_jobs = jobs.extract_jsonld_jobs(jsonld_and_title, "https://acme.com/careers") |
| 1149 | assert len(found_jobs) == 1 and found_jobs[0]["title"] == "Staff Security Engineer" |
| 1150 | assert sitemap.title_from_page(prefix + "<title>Platform Architect - Acme Careers</title>", "Acme") == "Platform Architect" |
| 1151 | |
| 1152 | kula_html = ( |
| 1153 | prefix |
| 1154 | + '<head><meta name="application-name" content="Acme Co"></head>' |
| 1155 | + '<a href="/acme/77-backend-engineer">Backend Engineer</a>' |
| 1156 | + '<script>self.__next_f.push([1,"{\\"jobs\\":[{\\"id\\":77,\\"title\\":\\"Backend Engineer\\",' |
| 1157 | + '\\"launch_at\\":\\"2026-11-12T00:00:00Z\\"}]}"]);</script>' |
| 1158 | ) |
| 1159 | kula_items, kula_total = kula.parse_listing(kula_html, {"slug": "acme"}) |
| 1160 | assert kula_total == 1 and len(kula_items) == 1 |
| 1161 | assert kula_items[0]["title"] == "Backend Engineer" |
| 1162 | assert kula_items[0]["url"] == "https://careers.kula.ai/acme/77-backend-engineer" |
| 1163 | |
| 1164 | tb_html = ( |
| 1165 | prefix |
| 1166 | + '<section data-total-results="1"><ul><li>' |
| 1167 | + '<a href="/job/istanbul/security-engineer/1/55"><span>Security Engineer</span></a>' |
| 1168 | + '<span class="location">İstanbul, Turkey</span>' |
| 1169 | + '<span class="date">11/14/2026</span>' |
| 1170 | + "</li></ul></section>" |
| 1171 | ) |
| 1172 | tb_items, tb_total = talentbrew.parse_listing({"results": tb_html}, {"board": "jobs.acme.com"}) |
| 1173 | assert tb_total == 1 and len(tb_items) == 1 |
| 1174 | assert tb_items[0]["title"] == "Security Engineer" |
| 1175 | assert tb_items[0]["location"] == "İstanbul, Turkey" |
| 1176 | assert tb_items[0]["date"] == "2026-11-14" |
| 1177 | |
| 1178 | |
| 1179 | def test_high174_deep_nested_json_recursion_error_recovered(): |
| 1180 | deep_array = ("[" * 10_000) + ("]" * 10_000) |
| 1181 | html = ( |
| 1182 | f'<script type="application/ld+json">{deep_array}</script>' |
| 1183 | '<meta property="og:site_name" content="Acme Corp">' |
| 1184 | "<title>Staff Engineer - Acme Careers</title>" |
| 1185 | ) |
| 1186 | assert jobs._walk_jsonld(deep_array) == [] |
| 1187 | assert sitemap.title_from_page(html, "Acme") == "Staff Engineer" |
| 1188 | assert jobs._stated_names(html) == ["Acme Corp"] |
| 1189 | assert phenom.page_object(f"phApp.ddo = {{\"a\": {deep_array}}};") is None |
| 1190 | |
| 1191 | |
| 1192 | def test_high174_sitemap_missed_distinguishes_empty_urlset_from_rejected_or_malformed_xml(monkeypatch): |
| 1193 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 1194 | valid_jobs_xml = ( |
| 1195 | '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1196 | "<url><loc>https://jobs.acme.com/jobs/12345-staff-engineer</loc></url>" |
| 1197 | "</urlset>" |
| 1198 | ) |
| 1199 | empty_urlset_xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>' |
| 1200 | malformed_xml = "<urlset><url><loc>https://jobs.acme.com/jobs/99999-broken" |
| 1201 | doctype_xml = ( |
| 1202 | '<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>' |
| 1203 | + valid_jobs_xml |
| 1204 | ) |
| 1205 | |
| 1206 | def run_with(first_body: str) -> tuple[str, list[tuple[str, str]], bool]: |
| 1207 | fake_rules = robots.Rules( |
| 1208 | "Sitemap: https://jobs.acme.com/sitemap-1.xml\n" |
| 1209 | "Sitemap: https://jobs.acme.com/sitemap-2.xml\n" |
| 1210 | ) |
| 1211 | bodies = { |
| 1212 | "https://jobs.acme.com/sitemap-1.xml": first_body, |
| 1213 | "https://jobs.acme.com/sitemap-2.xml": valid_jobs_xml, |
| 1214 | } |
| 1215 | with patch.object(robots, "rules_for", return_value=fake_rules): |
| 1216 | with patch.object(jobs.http, "get_text", side_effect=lambda u, **_kw: bodies.get(u)): |
| 1217 | return sitemap.job_urls(["jobs.acme.com"], deadline=time.monotonic() + 5) |
| 1218 | |
| 1219 | host_empty, urls_empty, missed_empty = run_with(empty_urlset_xml) |
| 1220 | assert host_empty == "jobs.acme.com" and len(urls_empty) == 1 |
| 1221 | assert missed_empty is False |
| 1222 | |
| 1223 | host_bad, urls_bad, missed_bad = run_with(malformed_xml) |
| 1224 | assert host_bad == "jobs.acme.com" and len(urls_bad) == 1 |
| 1225 | assert missed_bad is True |
| 1226 | |
| 1227 | host_dtd, urls_dtd, missed_dtd = run_with(doctype_xml) |
| 1228 | assert host_dtd == "jobs.acme.com" and len(urls_dtd) == 1 |
| 1229 | assert missed_dtd is True |
| 1230 | |
| 1231 | |
| 1232 | def test_high174_sitemap_missed_uses_full_url_for_host_and_query_jobs_sitemaps(monkeypatch): |
| 1233 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 1234 | valid_jobs_xml = ( |
| 1235 | '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1236 | "<url><loc>https://acme.com/jobs/12345-staff-engineer</loc></url>" |
| 1237 | "</urlset>" |
| 1238 | ) |
| 1239 | empty_urlset_xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>' |
| 1240 | malformed_xml = "<urlset><url><loc>https://acme.com/jobs/99999-broken" |
| 1241 | doctype_xml = ( |
| 1242 | '<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>' |
| 1243 | + valid_jobs_xml |
| 1244 | ) |
| 1245 | |
| 1246 | for first_url in ( |
| 1247 | "https://acme.com/sitemap.xml?type=jobs", |
| 1248 | "https://jobs-cdn.acme.com/sitemap.xml", |
| 1249 | ): |
| 1250 | fake_rules = robots.Rules( |
| 1251 | f"Sitemap: {first_url}\n" |
| 1252 | "Sitemap: https://acme.com/jobs/sitemap-2.xml\n" |
| 1253 | ) |
| 1254 | |
| 1255 | def run_case(first_body: str | None) -> tuple[str, list[tuple[str, str]], bool]: |
| 1256 | bodies = { |
| 1257 | first_url: first_body, |
| 1258 | "https://acme.com/jobs/sitemap-2.xml": valid_jobs_xml, |
| 1259 | } |
| 1260 | with patch.object(robots, "rules_for", return_value=fake_rules): |
| 1261 | with patch.object(jobs.http, "get_text", side_effect=lambda u, **_kw: bodies.get(u)): |
| 1262 | return sitemap.job_urls(["acme.com"], deadline=time.monotonic() + 5) |
| 1263 | |
| 1264 | host_empty, urls_empty, missed_empty = run_case(empty_urlset_xml) |
| 1265 | assert host_empty == "acme.com" and len(urls_empty) == 1 |
| 1266 | assert missed_empty is False |
| 1267 | |
| 1268 | host_malformed, urls_malformed, missed_malformed = run_case(malformed_xml) |
| 1269 | assert host_malformed == "acme.com" and len(urls_malformed) == 1 |
| 1270 | assert missed_malformed is True |
| 1271 | |
| 1272 | host_dtd, urls_dtd, missed_dtd = run_case(doctype_xml) |
| 1273 | assert host_dtd == "acme.com" and len(urls_dtd) == 1 |
| 1274 | assert missed_dtd is True |
| 1275 | |
| 1276 | host_fetch_fail, urls_fetch_fail, missed_fetch_fail = run_case(None) |
| 1277 | assert host_fetch_fail == "acme.com" and len(urls_fetch_fail) == 1 |
| 1278 | assert missed_fetch_fail is True |
| 1279 | |
| 1280 | |
| 1281 | def test_high174_kula_empty_jobs_array_returns_zero_without_error(): |
| 1282 | for payload_json in ('{\\"jobs\\":[]}', '{\\"jobs\\": []}', '{\\"jobs\\": [ ]}'): |
| 1283 | html = f'<script>self.__next_f.push([1,"{payload_json}"])</script>' |
| 1284 | items, total = kula.parse_listing(html, {"slug": "acme"}) |
| 1285 | assert items == [] and total == 0 |
| 1286 | |
| 1287 | |
| 1288 | def test_high174_sitemap_child_priority_sorts_by_path_on_jobs_host(monkeypatch): |
| 1289 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 1290 | non_job_children = [f"https://jobs.sap.com/en/about-{i}.xml" for i in range(1, 7)] |
| 1291 | jobs_child = "https://jobs.sap.com/en/jobs-sitemap.xml" |
| 1292 | index_xml = ( |
| 1293 | '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1294 | + "".join(f"<sitemap><loc>{u}</loc></sitemap>" for u in [*non_job_children, jobs_child]) |
| 1295 | + "</sitemapindex>" |
| 1296 | ) |
| 1297 | jobs_xml = ( |
| 1298 | '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1299 | "<url><loc>https://jobs.sap.com/jobs/12345-principal-engineer</loc></url>" |
| 1300 | "</urlset>" |
| 1301 | ) |
| 1302 | empty_xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>' |
| 1303 | fake_rules = robots.Rules("Sitemap: https://jobs.sap.com/sitemap-index.xml\n") |
| 1304 | fetched: list[str] = [] |
| 1305 | |
| 1306 | def fake_get_text(url: str, **_kw): |
| 1307 | fetched.append(url) |
| 1308 | if url == "https://jobs.sap.com/sitemap-index.xml": |
| 1309 | return index_xml |
| 1310 | if url == jobs_child: |
| 1311 | return jobs_xml |
| 1312 | return empty_xml |
| 1313 | |
| 1314 | with patch.object(robots, "rules_for", return_value=fake_rules): |
| 1315 | with patch.object(jobs.http, "get_text", side_effect=fake_get_text): |
| 1316 | host, urls, missed = sitemap.job_urls(["jobs.sap.com"], deadline=time.monotonic() + 5) |
| 1317 | |
| 1318 | assert host == "jobs.sap.com" |
| 1319 | assert len(urls) == 1 and urls[0][0] == "https://jobs.sap.com/jobs/12345-principal-engineer" |
| 1320 | assert fetched[0] == "https://jobs.sap.com/sitemap-index.xml" |
| 1321 | assert fetched[1] == jobs_child |
| 1322 | assert len(fetched) == sitemap.SITEMAP_FILE_LIMIT |
| 1323 | assert missed is True |
| 1324 | |
| 1325 | |
| 1326 | def test_high174_talentbrew_supports_omitted_li_end_tags_and_nested_lists(): |
| 1327 | omitted_end_html = ( |
| 1328 | '<section data-total-results="2"><ul>' |
| 1329 | '<li><a href="/job/nyc/systems-engineer/1/10">Systems Engineer</a>' |
| 1330 | '<span class="location">New York, NY</span><span class="date">11/10/2026</span>' |
| 1331 | '<li><a href="/job/sf/security-engineer/1/20">Security Engineer</a>' |
| 1332 | '<ul class="badges"><li>Remote<li>Full-time</ul>' |
| 1333 | '<span class="location">San Francisco, CA</span><span class="date">11/12/2026</span>' |
| 1334 | "</ul></section>" |
| 1335 | ) |
| 1336 | items, total = talentbrew.parse_listing({"results": omitted_end_html}, {"board": "jobs.acme.com"}) |
| 1337 | assert total == 2 and len(items) == 2 |
| 1338 | assert items[0]["title"] == "Systems Engineer" |
| 1339 | assert items[0]["location"] == "New York, NY" |
| 1340 | assert items[0]["date"] == "2026-11-10" |
| 1341 | assert items[1]["title"] == "Security Engineer" |
| 1342 | assert items[1]["location"] == "San Francisco, CA" |
| 1343 | assert items[1]["date"] == "2026-11-12" |
| 1344 | |
| 1345 | |
| 1346 | def test_high174_kula_recovers_from_huge_integer_value_error(): |
| 1347 | huge_int = "9" * 5000 |
| 1348 | html = ( |
| 1349 | f"<script>self.__next_f.push([{huge_int}]);" |
| 1350 | 'self.__next_f.push([1,"{\\"jobs\\":[' + huge_int + ']}"]);' |
| 1351 | 'self.__next_f.push([1,"{\\"jobs\\":[{\\"id\\":42,\\"title\\":\\"Staff Engineer\\",' |
| 1352 | '\\"launch_at\\":\\"2026-11-14T00:00:00Z\\"}]}"]);</script>' |
| 1353 | ) |
| 1354 | items, total = kula.parse_listing(html, {"slug": "acme"}) |
| 1355 | assert total == 1 and len(items) == 1 |
| 1356 | assert items[0]["title"] == "Staff Engineer" |
| 1357 | assert items[0]["url"] == "https://careers.kula.ai/acme/42-staff-engineer" |
| 1358 | |
| 1359 | |
| 1360 | def test_high173_sitemap_guard_skips_live_dns_by_default_and_honors_custom_resolver(monkeypatch): |
| 1361 | def fail_dns(*_args, **_kwargs): |
| 1362 | raise AssertionError("sitemap._guard must not invoke live DNS by default") |
| 1363 | |
| 1364 | monkeypatch.setattr(socket, "getaddrinfo", fail_dns) |
| 1365 | detect.resolves_public.cache_clear() |
| 1366 | try: |
| 1367 | assert sitemap._resolves_public is detect.resolves_public |
| 1368 | guard = sitemap._guard("https://acme.com/sitemap.xml") |
| 1369 | assert guard("https://careers.acme.com/sitemap-jobs.xml") is True |
| 1370 | assert guard("https://evil.example/sitemap-jobs.xml") is False |
| 1371 | assert guard("http://careers.acme.com/sitemap-jobs.xml") is False |
| 1372 | |
| 1373 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: False) |
| 1374 | custom_guard = sitemap._guard("https://acme.com/sitemap.xml") |
| 1375 | assert custom_guard("https://careers.acme.com/sitemap-jobs.xml") is False |
| 1376 | finally: |
| 1377 | detect.resolves_public.cache_clear() |
| 1378 | |
| 1379 | |
| 1380 | def test_high174_sitemap_skips_malformed_loc_urls_before_urlparse(monkeypatch): |
| 1381 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 1382 | index_xml = ( |
| 1383 | '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1384 | "<sitemap><loc>https://[broken/</loc></sitemap>" |
| 1385 | "<sitemap><loc>https://jobs.acme.com/en/jobs-sitemap.xml</loc></sitemap>" |
| 1386 | "</sitemapindex>" |
| 1387 | ) |
| 1388 | jobs_xml = ( |
| 1389 | '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' |
| 1390 | "<url><loc>https://[also-broken/</loc></url>" |
| 1391 | "<url><loc>https://jobs.acme.com/jobs/12345-staff-engineer</loc></url>" |
| 1392 | "</urlset>" |
| 1393 | ) |
| 1394 | fake_rules = robots.Rules("Sitemap: https://jobs.acme.com/sitemap-index.xml\n") |
| 1395 | bodies = { |
| 1396 | "https://jobs.acme.com/sitemap-index.xml": index_xml, |
| 1397 | "https://jobs.acme.com/en/jobs-sitemap.xml": jobs_xml, |
| 1398 | } |
| 1399 | with patch.object(robots, "rules_for", return_value=fake_rules): |
| 1400 | with patch.object(jobs.http, "get_text", side_effect=lambda u, **_kw: bodies.get(u)): |
| 1401 | host, urls, missed = sitemap.job_urls(["jobs.acme.com"], deadline=time.monotonic() + 5) |
| 1402 | |
| 1403 | assert host == "jobs.acme.com" |
| 1404 | assert urls == [("https://jobs.acme.com/jobs/12345-staff-engineer", "")] |
| 1405 | assert missed is False |
| 1406 | |
| 1407 | |
| 1408 | def test_high173_is_same_site_public_url_and_default_guard_bypass_public_site_url(monkeypatch): |
| 1409 | assert detect.is_same_site_public_url("https://careers.acme.com/next", "acme.com", require_https=True) is True |
| 1410 | assert detect.is_same_site_public_url("http://careers.acme.com/next", "acme.com", require_https=True) is False |
| 1411 | assert detect.is_same_site_public_url("http://careers.acme.com/next", "acme.com", require_https=False) is True |
| 1412 | assert detect.is_same_site_public_url("https://evil.example/next", "acme.com", require_https=True) is False |
| 1413 | assert detect.is_same_site_public_url("https://careers.acme.com:8443/next", "acme.com", require_https=True) is False |
| 1414 | |
| 1415 | # Default same_site_redirect_guard must NEVER invoke public_site_url or resolves_public. |
| 1416 | monkeypatch.setattr( |
| 1417 | detect, "public_site_url", lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("unexpected public_site_url")), |
| 1418 | ) |
| 1419 | monkeypatch.setattr( |
| 1420 | detect, "resolves_public", lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("unexpected resolves_public")), |
| 1421 | ) |
| 1422 | guard = detect.same_site_redirect_guard("https://acme.com/careers") |
| 1423 | assert guard("https://careers.acme.com/openings") is True |
| 1424 | assert guard("http://careers.acme.com/openings") is False |
| 1425 | assert guard("https://evil.example/openings") is False |
| 1426 | |
| 1427 | |
| 1428 | def test_high173_sitemap_on_site_skips_post_download_dns_by_default_and_honors_custom_resolver(monkeypatch): |
| 1429 | def fail_dns(*_args, **_kwargs): |
| 1430 | raise socket.gaierror(-3, "Temporary failure in name resolution") |
| 1431 | |
| 1432 | monkeypatch.setattr(socket, "getaddrinfo", fail_dns) |
| 1433 | detect.resolves_public.cache_clear() |
| 1434 | try: |
| 1435 | assert sitemap._resolves_public is detect.resolves_public |
| 1436 | # Already-downloaded sitemap redirected to a same-site subdomain is NOT |
| 1437 | # discarded if DNS briefly fails after the public_only=True download. |
| 1438 | kept = sitemap._on_site( |
| 1439 | "https://acme.com/sitemap.xml", |
| 1440 | lambda landed: (landed.append("https://careers.acme.com/sitemap-jobs.xml"), "<urlset/>")[1], |
| 1441 | ) |
| 1442 | assert kept == "<urlset/>" |
| 1443 | |
| 1444 | # Off-site redirect, HTTPS->HTTP downgrade, and malformed final URL are still rejected. |
| 1445 | assert sitemap._on_site( |
| 1446 | "https://acme.com/sitemap.xml", |
| 1447 | lambda landed: (landed.append("https://evil.example/sitemap.xml"), "<urlset/>")[1], |
| 1448 | ) is None |
| 1449 | assert sitemap._on_site( |
| 1450 | "https://acme.com/sitemap.xml", |
| 1451 | lambda landed: (landed.append("http://careers.acme.com/sitemap.xml"), "<urlset/>")[1], |
| 1452 | ) is None |
| 1453 | assert sitemap._on_site( |
| 1454 | "https://acme.com/sitemap.xml", |
| 1455 | lambda landed: (landed.append("https://[broken/"), "<urlset/>")[1], |
| 1456 | ) is None |
| 1457 | |
| 1458 | # Monkeypatched sitemap._resolves_public is still honored. |
| 1459 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: False) |
| 1460 | assert sitemap._on_site( |
| 1461 | "https://acme.com/sitemap.xml", |
| 1462 | lambda landed: (landed.append("https://careers.acme.com/sitemap-jobs.xml"), "<urlset/>")[1], |
| 1463 | ) is None |
| 1464 | finally: |
| 1465 | detect.resolves_public.cache_clear() |
| 1466 |