Skip to content

Commit 5ccfa93

Browse files
committed
Add the framework middleware core
The framework-agnostic half of a web middleware, in internetdata.middleware: resolve a client address, look it up, decide whether to block. Each framework adapter ships separately and keeps only the parts that are framework-shaped, so the shared corpus, whose middleware cases this takes, is asserted once per language. A bare mount only attaches the visitor's answer to the request. A block_condition is a partial match in the shape of a Result, so it reaches any member: a country ({"location": {"country": ["CU", "IR"]}}), a network type ({"is_hosting": True}, {"asn": {"type": "hosting"}}), anonymity ({"is_vpn": True}), or the evidence behind a flag. An entry set to False or None is ignored, so a condition that constrains nothing would match every answer; that is refused at construction. Defaults suit a request path: 2.5 s, no retries, and fail open on every lookup failure. A condition naming a member the plan does not serve can never fire, so it warns once, a paid member inside an object every plan gets included: location.city on Unlimited is reported by its path. Guard judges the answer a middleware already attached, for an adapter's per-view check.
1 parent 185dee3 commit 5ccfa93

5 files changed

Lines changed: 6135 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""The framework-agnostic half of a web middleware.
2+
3+
What the framework adapters - internetdata-django, internetdata-flask,
4+
internetdata-fastapi - are built on. Using it directly is how you support a framework
5+
none of them cover.
6+
"""
7+
8+
from .condition import (
9+
BlockCondition,
10+
Conditions,
11+
constraint_count,
12+
matches,
13+
missing_members,
14+
validate,
15+
)
16+
from .core import (
17+
DEFAULT_RETRIES,
18+
DEFAULT_TIMEOUT,
19+
AsyncCore,
20+
Core,
21+
Guard,
22+
IpSelector,
23+
Lookup,
24+
MissingFieldAction,
25+
Options,
26+
RequestView,
27+
Selectors,
28+
bind_selectors,
29+
)
30+
31+
__all__ = [
32+
"DEFAULT_RETRIES",
33+
"DEFAULT_TIMEOUT",
34+
"AsyncCore",
35+
"BlockCondition",
36+
"Conditions",
37+
"Core",
38+
"Guard",
39+
"IpSelector",
40+
"Lookup",
41+
"MissingFieldAction",
42+
"Options",
43+
"RequestView",
44+
"Selectors",
45+
"bind_selectors",
46+
"constraint_count",
47+
"matches",
48+
"missing_members",
49+
"validate",
50+
]
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
"""Deciding whether an answer is worth blocking.
2+
3+
The condition is written in the shape of a `Result` and keyed by the same names the
4+
API uses, so what you write here reads like what you get back.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import dataclasses
10+
from typing import Any
11+
12+
__all__ = [
13+
"BlockCondition",
14+
"Conditions",
15+
"constraint_count",
16+
"matches",
17+
"missing_members",
18+
"validate",
19+
]
20+
21+
#: What makes a request worth blocking. Only the members you name are considered, and
22+
#: they must all hold.
23+
#:
24+
#: A value may be a scalar (equality, strings without regard to case), a list meaning
25+
#: any-of, a dict of ``gte``/``gt``/``lte``/``lt`` bounding a number, or a nested
26+
#: condition. A member set to ``False`` or ``None`` is ignored entirely - a condition
27+
#: states the positive signals you act on, so there is no way to write "block when this
28+
#: is false", which would otherwise read as blocking everybody::
29+
#:
30+
#: {"location": {"country": ["CU", "IR", "KP"]}}
31+
#: {"asn": {"type": "hosting"}}
32+
#: {"is_vpn": True, "vpn": {"provider": "nordvpn"}}
33+
#: {"is_resproxy": True, "resproxy": {"hits": {"gte": 5}}}
34+
BlockCondition = dict[str, Any]
35+
36+
#: One condition, or a list of them meaning any one blocking is enough.
37+
Conditions = BlockCondition | list[BlockCondition]
38+
39+
_BOUND_KEYS = frozenset({"gte", "gt", "lte", "lt"})
40+
41+
42+
def matches(condition: Conditions, result: Any) -> bool:
43+
"""Whether an answer satisfies the condition, and should therefore be blocked."""
44+
for one in _as_list(condition):
45+
if _matches_object(one, result):
46+
return True
47+
return False
48+
49+
50+
def missing_members(condition: Conditions, result: Any) -> list[str]:
51+
"""The members a condition names that this answer did not carry: a top-level member,
52+
or a paid one inside an object every plan gets, by its path (``location.city``).
53+
54+
A field your plan does not include is absent rather than false, so a condition
55+
naming one can never match and the block would silently never fire. A detail object
56+
present but empty (every field None) is a real answer meaning the flag above it is
57+
false, so nothing inside one is reported: ``vpn`` empty is not a plan gap. A
58+
populated object carries every member the plan includes, so a member missing there
59+
is one.
60+
61+
A locally answered bogon needs no special case: it is synthesized in the widest
62+
shape, so every member is present and nothing reads as missing.
63+
"""
64+
missing: list[str] = []
65+
for one in _as_list(condition):
66+
_collect_missing(one, result, "", missing)
67+
return missing
68+
69+
70+
def validate(condition: Conditions | None) -> None:
71+
"""Refuse a condition that constrains nothing.
72+
73+
Ignoring ``False`` means ``{"is_vpn": False}`` and ``{}`` have no terms left to
74+
satisfy, so they would match every answer and block all traffic. Nobody writes that
75+
on purpose, and failing when the middleware is built beats discovering it in
76+
production.
77+
"""
78+
if condition is None:
79+
return
80+
for one in _as_list(condition):
81+
if constraint_count(one) == 0:
82+
raise ValueError(
83+
f"internetdata: block condition {one!r} constrains nothing, which would "
84+
"block every request; a member set to False or None is ignored, so state "
85+
"the positive signals you act on"
86+
)
87+
88+
89+
def constraint_count(condition: Any) -> int:
90+
"""How many leaf constraints a condition actually carries."""
91+
if condition is None or condition is False:
92+
return 0
93+
if isinstance(condition, dict):
94+
if _is_bound(condition):
95+
return 1
96+
return sum(constraint_count(value) for value in condition.values())
97+
if isinstance(condition, (list, tuple, set, frozenset)):
98+
return sum(constraint_count(entry) for entry in condition)
99+
return 1
100+
101+
102+
def _as_list(condition: Conditions) -> list[BlockCondition]:
103+
if isinstance(condition, list):
104+
return condition
105+
return [condition]
106+
107+
108+
def _collect_missing(
109+
condition: BlockCondition, value: Any, prefix: str, missing: list[str]
110+
) -> None:
111+
for member, want in condition.items():
112+
if constraint_count(want) == 0:
113+
continue
114+
path = f"{prefix}{member}"
115+
got = getattr(value, member, None)
116+
if got is None:
117+
if path not in missing:
118+
missing.append(path)
119+
continue
120+
if isinstance(want, dict) and not _is_bound(want) and _populated(got):
121+
_collect_missing(want, got, f"{path}.", missing)
122+
123+
124+
def _populated(value: Any) -> bool:
125+
"""Whether a member is an object holding at least one field: an empty detail object
126+
is the answer under a false flag, never a plan gap."""
127+
if not dataclasses.is_dataclass(value) or isinstance(value, type):
128+
return False
129+
return any(getattr(value, field.name) is not None for field in dataclasses.fields(value))
130+
131+
132+
def _matches_object(condition: BlockCondition, value: Any) -> bool:
133+
for member, want in condition.items():
134+
if constraint_count(want) == 0:
135+
continue
136+
if not _matches_value(want, getattr(value, member, None)):
137+
return False
138+
return True
139+
140+
141+
def _matches_value(want: Any, got: Any) -> bool:
142+
"""Whether one value satisfies one want.
143+
144+
An ABSENT member arrives here as ``None``, which is exactly what "not in your plan"
145+
looks like. Every branch below must therefore reject it, which is what makes an
146+
unserved member fail a match rather than pass it. A new branch that does not would
147+
silently let a member nobody was served block a request.
148+
"""
149+
if isinstance(want, (list, tuple, set, frozenset)):
150+
return any(_matches_value(entry, got) for entry in want)
151+
if isinstance(want, dict):
152+
if _is_bound(want):
153+
return _matches_bound(want, got)
154+
return _matches_object(want, got)
155+
if isinstance(want, str) and isinstance(got, str):
156+
# Providers are lowercase slugs and countries uppercase codes on the wire, and a
157+
# caller should not have to know which, so a string compares without case.
158+
return want.casefold() == got.casefold()
159+
if isinstance(want, bool) or isinstance(got, bool):
160+
return want is got
161+
return bool(want == got)
162+
163+
164+
def _matches_bound(bound: dict[str, Any], got: Any) -> bool:
165+
if isinstance(got, bool) or not isinstance(got, (int, float)):
166+
return False
167+
if "gte" in bound and got < bound["gte"]:
168+
return False
169+
if "gt" in bound and got <= bound["gt"]:
170+
return False
171+
if "lte" in bound and got > bound["lte"]:
172+
return False
173+
return not ("lt" in bound and got >= bound["lt"])
174+
175+
176+
def _is_bound(value: dict[str, Any]) -> bool:
177+
return len(value) > 0 and _BOUND_KEYS.issuperset(value)

0 commit comments

Comments
 (0)