omnirank 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,289 @@
1
+ """One public, read-only scan: the same audit engine as ``omnirank sweep``, behind a
2
+ paranoid fetch layer.
3
+
4
+ * Target: an http(s) URL of a public site, given by DNS name (no IP literals), port 80 or
5
+ 443 only. Validation is ``omnirank.netguard`` (strict URL parsing; every address the
6
+ name resolves to must be public; connect-time DNS pinning).
7
+ * robots.txt is fetched first and RESPECTED for OmniRank's scanner user-agent: a site
8
+ that disallows it is not scanned; disallowed paths are never requested; a robots.txt
9
+ that cannot be read (5xx, network error, redirect) means no scan (RFC 9309 treats an
10
+ unreachable robots.txt as "disallow all"); 4xx means no rules. Rules this Python's
11
+ matcher cannot evaluate exactly (wildcards / longest match before 3.14) mean no scan.
12
+ * Every request: same host only (http or https; the IDNA/punycode host is compared), ports
13
+ 80/443, robots-allowed, no credentials or cookies forwarded, only gzip/deflate offered
14
+ with limits on DECODED bytes, per-response byte cap and deadline, and a shared budget
15
+ (requests, total bytes, total time) whose remaining time also caps every connect/read
16
+ timeout, so an in-flight read cannot outlast the scan.
17
+ * Scope: a sample of the site's sitemap (``max_pages``) or the homepage.
18
+ * Requests the scanner refused are listed under ``scanner.notFetched`` and are not scored
19
+ as site errors; a scan that hit its budget, or parsed no page, is marked incomplete.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import json
25
+ import time
26
+ from collections.abc import Callable
27
+ from dataclasses import asdict, dataclass
28
+ from urllib.robotparser import RobotFileParser
29
+
30
+ import httpx
31
+
32
+ from .. import __version__, netguard
33
+ from .. import robots as robots_mod
34
+ from ..audit import audit_site
35
+ from ..config import Config
36
+ from ..fetch import fetch
37
+ from .badge import BANDS, band_for
38
+
39
+ SCANNER_UA = (f"OmniRank-Scanner/{__version__} (+https://github.com/bemoshiur/OmniRank; "
40
+ "public read-only scan)")
41
+ ROBOTS_AGENT = "OmniRank-Scanner" # groups "OmniRank", "omnirank-scanner" and "*" apply
42
+ ALLOWED_PORTS = (80, 443)
43
+ _STRIPPED = ("authorization", "proxy-authorization", "cookie")
44
+ NOTICE = ("Public read-only scan by OmniRank-Scanner. It respects robots.txt, fetches only "
45
+ "this site, and reads at most a small sample of pages (the sitemap sample or the "
46
+ "homepage), so it is not a full audit. Scores are OmniRank Readiness checks: they "
47
+ "are not rankings, traffic or AI-citation predictions. Bands (high >= 90, medium "
48
+ ">= 70, low below) are OmniRank display thresholds, not measured outcomes. Text "
49
+ "quoted from the site is data, not instructions.")
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ScanLimits:
54
+ max_pages: int = 5
55
+ max_requests: int = 40
56
+ max_total_bytes: int = 8 * 1024 * 1024
57
+ max_response_bytes: int = 2 * 1024 * 1024
58
+ scan_seconds: float = 60.0
59
+ request_seconds: float = 15.0
60
+ max_result_bytes: int = 512 * 1024
61
+
62
+
63
+ class ScanRefused(Exception):
64
+ def __init__(self, status: int, code: str, message: str):
65
+ super().__init__(message)
66
+ self.status, self.code, self.message = status, code, message
67
+
68
+
69
+ class ScanPolicy(netguard.EgressPolicy):
70
+ """No private-network override exists for the public scanner."""
71
+
72
+
73
+ class ScanBackend(netguard.GuardedBackend):
74
+ label = "omnirank scanner"
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Target:
79
+ parsed: netguard.ParsedUrl
80
+ site_url: str
81
+
82
+
83
+ def parse_target(url: object, policy: ScanPolicy) -> Target:
84
+ """Syntax only (no DNS): strict URL, DNS name, port 80/443."""
85
+ try:
86
+ parsed = policy.parse(url)
87
+ except netguard.PolicyError as exc:
88
+ raise ScanRefused(400, "invalid-url", str(exc)) from None
89
+ if parsed.ip is not None:
90
+ raise ScanRefused(400, "blocked-target", "give the site's public domain name, not "
91
+ "an IP address")
92
+ if parsed.port is not None and parsed.port not in ALLOWED_PORTS:
93
+ raise ScanRefused(400, "blocked-target", "only ports 80 and 443 are scanned")
94
+ default = 443 if parsed.scheme == "https" else 80
95
+ port = "" if parsed.port in (None, default) else f":{parsed.port}"
96
+ return Target(parsed, f"{parsed.scheme}://{parsed.host}{port}")
97
+
98
+
99
+ def check_target_addresses(target: Target, policy: ScanPolicy) -> None:
100
+ try:
101
+ policy.addresses(target.parsed.host)
102
+ except netguard.PolicyError as exc:
103
+ raise ScanRefused(400, "blocked-target", str(exc)) from None
104
+
105
+
106
+ class Robots:
107
+ def __init__(self, parser: RobotFileParser | None):
108
+ self._parser = parser
109
+
110
+ @classmethod
111
+ def allow_all(cls) -> Robots:
112
+ return cls(None)
113
+
114
+ @classmethod
115
+ def from_text(cls, text: str) -> Robots:
116
+ if robots_mod.rules_need_wildcards(text) and \
117
+ not robots_mod.matcher_supports_wildcards():
118
+ raise ScanRefused(403, "robots-unsupported", "robots.txt uses wildcard rules this "
119
+ "Python cannot evaluate exactly; not scanning (conservative)")
120
+ if robots_mod.rules_need_longest_match(text) and \
121
+ not robots_mod.matcher_supports_longest_match():
122
+ raise ScanRefused(403, "robots-unsupported", "robots.txt has overlapping "
123
+ "Allow/Disallow rules this Python cannot evaluate exactly; "
124
+ "not scanning (conservative)")
125
+ parser = RobotFileParser()
126
+ parser.parse(text.splitlines())
127
+ return cls(parser)
128
+
129
+ def allows(self, url: str) -> bool:
130
+ return self._parser is None or self._parser.can_fetch(ROBOTS_AGENT, url)
131
+
132
+
133
+ class ScanTransport(netguard.GuardedTransport):
134
+ label = "omnirank scanner"
135
+ backend_cls = ScanBackend
136
+ cancel_reason = "the scan was stopped"
137
+
138
+ def __init__(self, policy: ScanPolicy, *, budget: netguard.Budget, target:
139
+ netguard.ParsedUrl, robots: Robots):
140
+ super().__init__(policy, budget=budget)
141
+ self.target, self.robots = target, robots
142
+ self.not_fetched: list[dict] = []
143
+
144
+ def _refuse(self, url: str, reason: str, message: str):
145
+ entry = {"url": url, "reason": reason}
146
+ if entry not in self.not_fetched and len(self.not_fetched) < 200:
147
+ self.not_fetched.append(entry)
148
+ raise netguard.PolicyError(message)
149
+
150
+ def check_request(self, request: httpx.Request) -> None:
151
+ for name in _STRIPPED:
152
+ request.headers.pop(name, None)
153
+ url = str(request.url)
154
+ # httpx's ``host`` is the Unicode form ("münchen.de"); the target is the ASCII/IDNA
155
+ # form, so compare the raw (punycode) host, case- and trailing-dot-insensitively.
156
+ host = request.url.raw_host.decode("ascii", "replace").lower().removesuffix(".")
157
+ if host != self.target.host or request.url.scheme not in ("http", "https"):
158
+ self._refuse(url, "other-host", "request to another host refused: the public "
159
+ "scanner only fetches the target site")
160
+ if request.url.port not in (None, *ALLOWED_PORTS):
161
+ self._refuse(url, "port", "only ports 80 and 443 are fetched")
162
+ if request.url.path != "/robots.txt" and not self.robots.allows(url):
163
+ self._refuse(url, "robots", "robots.txt disallows this path for OmniRank-Scanner")
164
+
165
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
166
+ # The whole scan has ONE wall-clock budget: no connect/read/write/pool wait of this
167
+ # request may outlast what is left of it (an in-flight read included).
168
+ remaining = max(0.001, self._budget.deadline - self._budget.now())
169
+ timeouts = dict(request.extensions.get("timeout") or {})
170
+ for key in ("connect", "read", "write", "pool"):
171
+ value = timeouts.get(key)
172
+ timeouts[key] = remaining if value is None else min(value, remaining)
173
+ request.extensions = {**request.extensions, "timeout": timeouts}
174
+ try:
175
+ return super().handle_request(request)
176
+ except netguard.BudgetExceeded:
177
+ entry = {"url": str(request.url), "reason": "budget"}
178
+ if entry not in self.not_fetched and len(self.not_fetched) < 200:
179
+ self.not_fetched.append(entry)
180
+ raise
181
+
182
+
183
+ def _read_robots(client: httpx.Client, site_url: str) -> Robots:
184
+ got = fetch(client, f"{site_url}/robots.txt")
185
+ if 200 <= got.status < 300:
186
+ return Robots.from_text(got.text)
187
+ if 400 <= got.status < 500:
188
+ return Robots.allow_all()
189
+ if 300 <= got.status < 400:
190
+ detail = "redirects (the scanner follows no redirects; scan the final site URL)"
191
+ else:
192
+ detail = "could not be read" if got.status == 0 else f"answered HTTP {got.status}"
193
+ raise ScanRefused(403, "robots-unavailable", f"robots.txt {detail}; an unreadable "
194
+ "robots.txt is treated as disallow-all, so the site was not scanned")
195
+
196
+
197
+ def _dumps(value: object) -> bytes:
198
+ return json.dumps(value, ensure_ascii=True, separators=(",", ":"),
199
+ allow_nan=False).encode("ascii")
200
+
201
+
202
+ def finalise(result: dict, max_bytes: int) -> tuple[bytes, str]:
203
+ """Cap the size (dropping findings from the end first), then give the result its
204
+ content-hash id. Returns (bytes, id)."""
205
+ scanner = result["scanner"]
206
+ scanner["id"] = "0" * 32
207
+ data = _dumps(result)
208
+ findings = result.get("findings", [])
209
+ def _policy_detail() -> bool:
210
+ cp = result.get("crawlerPolicy")
211
+ return isinstance(cp, dict) and bool(cp.get("categories") or cp.get("reference"))
212
+
213
+ while len(data) > max_bytes and (findings or result.get("notEvaluated")
214
+ or _policy_detail() or scanner.get("notFetched")):
215
+ scanner["truncated"] = True
216
+ if findings:
217
+ keep = len(findings) // 2
218
+ scanner["findingsOmitted"] = scanner.get("findingsOmitted", 0) + \
219
+ len(findings) - keep
220
+ del findings[keep:]
221
+ elif result.get("notEvaluated"):
222
+ result["notEvaluated"] = []
223
+ elif _policy_detail():
224
+ # keep the roll-up (checkedOn, verified flag, disclaimer, mismatches); drop the
225
+ # per-crawler detail, and say so
226
+ result["crawlerPolicy"]["categories"] = []
227
+ result["crawlerPolicy"]["reference"] = []
228
+ scanner["crawlerPolicyDetailOmitted"] = True
229
+ else:
230
+ scanner["notFetched"] = []
231
+ data = _dumps(result)
232
+ scanner["id"] = ""
233
+ rid = hashlib.sha256(_dumps(result)).hexdigest()[:32]
234
+ scanner["id"] = rid
235
+ data = _dumps(result)
236
+ if len(data) > max_bytes: # never expected with sane limits; refuse, don't stream
237
+ raise ScanRefused(500, "result-too-large", "the result exceeded the size limit")
238
+ return data, rid
239
+
240
+
241
+ def run_scan(url: object, *, limits: ScanLimits = ScanLimits(),
242
+ resolver: Callable[[str], list[str]] | None = None,
243
+ clock: Callable[[], float] = time.monotonic) -> dict:
244
+ policy = ScanPolicy(resolver=resolver, max_response_bytes=limits.max_response_bytes,
245
+ fetch_deadline=limits.request_seconds)
246
+ target = parse_target(url, policy)
247
+ check_target_addresses(target, policy)
248
+ budget = netguard.Budget(max_requests=limits.max_requests,
249
+ max_total_bytes=limits.max_total_bytes,
250
+ seconds=limits.scan_seconds, clock=clock)
251
+ transport = ScanTransport(policy, budget=budget, target=target.parsed,
252
+ robots=Robots.allow_all())
253
+ with httpx.Client(transport=transport, follow_redirects=False, trust_env=False,
254
+ timeout=httpx.Timeout(limits.request_seconds),
255
+ headers={"User-Agent": SCANNER_UA}) as client:
256
+ transport.robots = _read_robots(client, target.site_url)
257
+ if not transport.robots.allows(target.site_url + "/"):
258
+ raise ScanRefused(403, "robots-disallowed", "robots.txt disallows "
259
+ "OmniRank-Scanner for this site; it was not scanned")
260
+ config = Config({"site": {"name": target.parsed.host, "url": target.site_url,
261
+ "entityType": "Organization"},
262
+ "audit": {"sampleSize": limits.max_pages}})
263
+ report = audit_site(config, client)
264
+
265
+ skipped = {n["url"] for n in transport.not_fetched}
266
+ report.findings = [f for f in report.findings if f.url not in skipped]
267
+ out = report.to_dict()
268
+ out["notEvaluated"] = [
269
+ {**e, "reason": "not-fetched-by-scanner"} if e.get("url") in skipped else e
270
+ for e in out["notEvaluated"]]
271
+ overall = out["score"]["overall"]
272
+ complete = not budget.exhausted and "aeo" in report.layers_run
273
+ out["scanner"] = {
274
+ "publicReadOnlyScan": True,
275
+ "userAgent": SCANNER_UA,
276
+ "robots": "respected",
277
+ "complete": complete,
278
+ "readiness": {"score": overall,
279
+ "band": band_for(overall) if complete else "incomplete",
280
+ "bands": {name: floor for floor, name, _ in BANDS},
281
+ "bandsAre": "OmniRank display thresholds, not measured outcomes"},
282
+ "limits": asdict(limits),
283
+ "budget": {"requests": budget.requests, "bytes": budget.bytes_read,
284
+ "exhausted": budget.exhausted},
285
+ "notFetched": list(transport.not_fetched),
286
+ "truncated": False,
287
+ "notice": NOTICE,
288
+ }
289
+ return out
@@ -0,0 +1,98 @@
1
+ """Rate limiting for the public scanner: token buckets with an injectable clock."""
2
+ from __future__ import annotations
3
+
4
+ import ipaddress
5
+ import threading
6
+ import time
7
+ from collections import OrderedDict
8
+ from collections.abc import Callable
9
+
10
+
11
+ def client_key(ip: str) -> str:
12
+ """The unit a client is limited by: an IPv4 address (IPv4-mapped IPv6 unwrapped), or
13
+ an IPv6 /64 -- one subscriber usually holds a whole /64, so counting /128s would give
14
+ a single client 2**64 separate buckets."""
15
+ try:
16
+ addr = ipaddress.ip_address(ip.split("%", 1)[0])
17
+ except ValueError:
18
+ return ip
19
+ if isinstance(addr, ipaddress.IPv6Address):
20
+ if addr.ipv4_mapped is not None:
21
+ return str(addr.ipv4_mapped)
22
+ return str(ipaddress.IPv6Network((addr, 64), strict=False))
23
+ return str(addr)
24
+
25
+
26
+ class TokenBucket:
27
+ """``capacity`` tokens, refilled continuously at ``refill_per_second``."""
28
+
29
+ def __init__(self, capacity: float, refill_per_second: float,
30
+ clock: Callable[[], float] = time.monotonic):
31
+ self.capacity = float(capacity)
32
+ self.rate = float(refill_per_second)
33
+ self._clock = clock
34
+ self._tokens = float(capacity)
35
+ self._at = clock()
36
+
37
+ def _refill(self) -> None:
38
+ now = self._clock()
39
+ if now > self._at:
40
+ self._tokens = min(self.capacity, self._tokens + (now - self._at) * self.rate)
41
+ self._at = now
42
+
43
+ def peek(self, n: float = 1.0) -> bool:
44
+ self._refill()
45
+ return self._tokens >= n
46
+
47
+ def take(self, n: float = 1.0) -> bool:
48
+ self._refill()
49
+ if self._tokens >= n:
50
+ self._tokens -= n
51
+ return True
52
+ return False
53
+
54
+ def retry_after(self, n: float = 1.0) -> float:
55
+ """Seconds until ``n`` tokens are available (inf if the bucket never refills)."""
56
+ self._refill()
57
+ missing = n - self._tokens
58
+ if missing <= 0:
59
+ return 0.0
60
+ if self.rate <= 0:
61
+ return float("inf")
62
+ return missing / self.rate
63
+
64
+
65
+ class RateLimiter:
66
+ """A per-client-IP bucket and one global bucket. The per-IP bucket is checked first
67
+ and the global one is only charged for a request the IP may make, so one client being
68
+ refused cannot drain everyone's budget. At most ``max_tracked`` IPs are remembered
69
+ (least recently seen evicted); the global bucket bounds what eviction could give."""
70
+
71
+ def __init__(self, *, per_ip_capacity: float, per_ip_refill: float,
72
+ global_capacity: float, global_refill: float,
73
+ clock: Callable[[], float] = time.monotonic, max_tracked: int = 10_000):
74
+ self._per_ip = (per_ip_capacity, per_ip_refill)
75
+ self._clock = clock
76
+ self._global = TokenBucket(global_capacity, global_refill, clock)
77
+ self._buckets: OrderedDict[str, TokenBucket] = OrderedDict()
78
+ self._max_tracked = max_tracked
79
+ self._lock = threading.Lock()
80
+
81
+ def allow(self, ip: str) -> tuple[bool, float]:
82
+ """(allowed, seconds to wait before retrying)."""
83
+ ip = client_key(ip)
84
+ with self._lock:
85
+ bucket = self._buckets.get(ip)
86
+ if bucket is None:
87
+ bucket = TokenBucket(*self._per_ip, self._clock)
88
+ self._buckets[ip] = bucket
89
+ while len(self._buckets) > self._max_tracked:
90
+ self._buckets.popitem(last=False)
91
+ else:
92
+ self._buckets.move_to_end(ip)
93
+ if not bucket.peek():
94
+ return False, bucket.retry_after()
95
+ if not self._global.take():
96
+ return False, self._global.retry_after()
97
+ bucket.take()
98
+ return True, 0.0
@@ -0,0 +1,143 @@
1
+ """A tiny stdlib HTTP server around ``ScannerService.handle_request`` (local use; see
2
+ docs/scanner.md for putting it behind a worker or reverse proxy -- NOT DEPLOYED)."""
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import threading
7
+ import time
8
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+
10
+ from .limits import client_key
11
+ from .service import ScannerService
12
+
13
+ MAX_BODY = 1024 # GET/HEAD carry no body; anything declared above this is refused
14
+ MAX_CONNECTIONS = 32 # open connections, whole server
15
+ MAX_PER_IP = 4 # open connections per client (IPv4 address or IPv6 /64)
16
+ SOCKET_TIMEOUT = 10 # seconds per socket operation
17
+ HEADER_DEADLINE = 10.0 # seconds for the WHOLE request (line, headers, body) to arrive
18
+
19
+
20
+ class _DeadlineSocketIO(io.RawIOBase):
21
+ """Raw reads from the client socket under one total deadline: each recv waits at most
22
+ the time left, and a read after the deadline raises TimeoutError (the stdlib handler
23
+ then drops the connection without answering). A per-operation timeout alone lets a
24
+ slow-loris client keep a thread for ever by sending one byte every few seconds."""
25
+
26
+ def __init__(self, sock, deadline: float, clock, per_op: float):
27
+ super().__init__()
28
+ self._sock, self._deadline, self._clock, self._per_op = sock, deadline, clock, \
29
+ per_op
30
+
31
+ def readable(self) -> bool:
32
+ return True
33
+
34
+ def readinto(self, buffer) -> int:
35
+ remaining = self._deadline - self._clock()
36
+ if remaining <= 0:
37
+ raise TimeoutError("request not received within the deadline")
38
+ self._sock.settimeout(min(self._per_op, remaining))
39
+ return self._sock.recv_into(buffer)
40
+
41
+
42
+ class Handler(BaseHTTPRequestHandler):
43
+ server_version = "OmniRank-Scanner"
44
+ sys_version = ""
45
+ protocol_version = "HTTP/1.0"
46
+ timeout = SOCKET_TIMEOUT
47
+
48
+ def setup(self) -> None:
49
+ super().setup()
50
+ clock = getattr(self.server, "clock", time.monotonic)
51
+ limit = getattr(self.server, "header_deadline", HEADER_DEADLINE)
52
+ self.rfile = io.BufferedReader(_DeadlineSocketIO(
53
+ self.connection, clock() + limit, clock, SOCKET_TIMEOUT))
54
+
55
+ def version_string(self) -> str:
56
+ return self.server_version
57
+
58
+ def log_message(self, format, *args) -> None:
59
+ """No access log: the scanner keeps no record of who asked for what."""
60
+
61
+ def _send(self, status: int, headers, body: bytes) -> None:
62
+ self.send_response(status)
63
+ for name, value in headers:
64
+ self.send_header(name, value)
65
+ self.end_headers()
66
+ if self.command != "HEAD" and body:
67
+ self.wfile.write(body)
68
+
69
+ def _handle(self) -> None:
70
+ service: ScannerService = self.server.service # type: ignore[attr-defined]
71
+ length = self.headers.get("Content-Length")
72
+ if self.headers.get("Transfer-Encoding") or (
73
+ length is not None and (not length.isdigit() or int(length) > MAX_BODY)):
74
+ status, headers, body = service.handle_request(
75
+ "GET", "/", "", {}, b"x", client_ip=self.client_address[0])
76
+ self.close_connection = True
77
+ self._send(status, headers, body)
78
+ return
79
+ body = self.rfile.read(int(length)) if length else b""
80
+ path, _, query = self.path.partition("?")
81
+ status, headers, out = service.handle_request(
82
+ self.command, path, query, self.headers, body, client_ip=self.client_address[0])
83
+ self._send(status, headers, out)
84
+
85
+ do_GET = do_HEAD = do_POST = do_PUT = do_DELETE = do_PATCH = do_OPTIONS = _handle
86
+
87
+
88
+ class ScannerHTTPServer(ThreadingHTTPServer):
89
+ daemon_threads = True
90
+ clock = staticmethod(time.monotonic)
91
+ header_deadline = HEADER_DEADLINE
92
+
93
+ def __init__(self, address, service: ScannerService, max_connections: int =
94
+ MAX_CONNECTIONS, *, bind_and_activate: bool = True):
95
+ self.service = service
96
+ self._connections = threading.BoundedSemaphore(max_connections)
97
+ self._per_ip: dict[str, int] = {}
98
+ self._per_ip_lock = threading.Lock()
99
+ super().__init__(address, Handler, bind_and_activate)
100
+
101
+ def _admit(self, ip: str) -> bool:
102
+ key = client_key(ip)
103
+ with self._per_ip_lock:
104
+ if self._per_ip.get(key, 0) >= MAX_PER_IP:
105
+ return False
106
+ self._per_ip[key] = self._per_ip.get(key, 0) + 1
107
+ return True
108
+
109
+ def _release(self, ip: str) -> None:
110
+ key = client_key(ip)
111
+ with self._per_ip_lock:
112
+ left = self._per_ip.get(key, 0) - 1
113
+ if left > 0:
114
+ self._per_ip[key] = left
115
+ else:
116
+ self._per_ip.pop(key, None)
117
+
118
+ def process_request(self, request, client_address):
119
+ ip = str(client_address[0])
120
+ if not self._admit(ip):
121
+ self.shutdown_request(request) # over the per-client cap: drop
122
+ return
123
+ if not self._connections.acquire(blocking=False):
124
+ self._release(ip)
125
+ self.shutdown_request(request) # over the connection cap: drop
126
+ return
127
+ try:
128
+ super().process_request(request, client_address)
129
+ except Exception:
130
+ self._connections.release()
131
+ self._release(ip)
132
+ raise
133
+
134
+ def process_request_thread(self, request, client_address):
135
+ try:
136
+ super().process_request_thread(request, client_address)
137
+ finally:
138
+ self._connections.release()
139
+ self._release(str(client_address[0]))
140
+
141
+
142
+ def make_server(service: ScannerService, host: str, port: int) -> ScannerHTTPServer:
143
+ return ScannerHTTPServer((host, port), service)