gravitywell 0.1.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 (53) hide show
  1. gravitywell/__init__.py +28 -0
  2. gravitywell/_auth.py +134 -0
  3. gravitywell/_client.py +323 -0
  4. gravitywell/_insights.py +223 -0
  5. gravitywell/_resources/__init__.py +1 -0
  6. gravitywell/_resources/action.py +150 -0
  7. gravitywell/_resources/auth.py +82 -0
  8. gravitywell/_resources/clients.py +270 -0
  9. gravitywell/_resources/config.py +989 -0
  10. gravitywell/_resources/dhcp.py +61 -0
  11. gravitywell/_resources/dns.py +88 -0
  12. gravitywell/_resources/domains.py +348 -0
  13. gravitywell/_resources/groups.py +332 -0
  14. gravitywell/_resources/history.py +153 -0
  15. gravitywell/_resources/info.py +249 -0
  16. gravitywell/_resources/lists.py +272 -0
  17. gravitywell/_resources/logs.py +167 -0
  18. gravitywell/_resources/network.py +139 -0
  19. gravitywell/_resources/padd.py +50 -0
  20. gravitywell/_resources/queries.py +178 -0
  21. gravitywell/_resources/search.py +73 -0
  22. gravitywell/_resources/stats.py +421 -0
  23. gravitywell/_resources/teleporter.py +126 -0
  24. gravitywell/_version.py +18 -0
  25. gravitywell/mcp.py +232 -0
  26. gravitywell/models/__init__.py +364 -0
  27. gravitywell/models/_action.py +16 -0
  28. gravitywell/models/_auth.py +55 -0
  29. gravitywell/models/_base.py +67 -0
  30. gravitywell/models/_clients.py +83 -0
  31. gravitywell/models/_config.py +124 -0
  32. gravitywell/models/_dhcp.py +26 -0
  33. gravitywell/models/_dns.py +16 -0
  34. gravitywell/models/_domains.py +58 -0
  35. gravitywell/models/_groups.py +43 -0
  36. gravitywell/models/_history.py +98 -0
  37. gravitywell/models/_info.py +381 -0
  38. gravitywell/models/_insights.py +81 -0
  39. gravitywell/models/_lists.py +64 -0
  40. gravitywell/models/_logs.py +39 -0
  41. gravitywell/models/_network.py +133 -0
  42. gravitywell/models/_padd.py +94 -0
  43. gravitywell/models/_queries.py +172 -0
  44. gravitywell/models/_search.py +62 -0
  45. gravitywell/models/_stats.py +219 -0
  46. gravitywell/models/_teleporter.py +34 -0
  47. gravitywell/models/_time.py +50 -0
  48. gravitywell/py.typed +0 -0
  49. gravitywell-0.1.0.dist-info/METADATA +165 -0
  50. gravitywell-0.1.0.dist-info/RECORD +53 -0
  51. gravitywell-0.1.0.dist-info/WHEEL +4 -0
  52. gravitywell-0.1.0.dist-info/entry_points.txt +3 -0
  53. gravitywell-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,28 @@
1
+ """A third-party, typed client for the Pi-hole v6 REST API.
2
+
3
+ The models of request and response bodies are in `gravitywell.models`.
4
+
5
+ Example:
6
+ import os
7
+
8
+ from gravitywell import PiHole, PiHoleAuth
9
+
10
+ auth = PiHoleAuth(os.environ["PIHOLE_PASSWORD"])
11
+ with PiHole("http://pi.hole", auth=auth) as api:
12
+ print(api.info.version().version.ftl.local.version)
13
+ """
14
+
15
+ from gravitywell._auth import PiHoleAuth
16
+ from gravitywell._client import AsyncPiHole, PiHole
17
+ from gravitywell._version import PIHOLE_VERSIONS, __version__
18
+
19
+ __all__ = [
20
+ # gravitywell._version
21
+ "PIHOLE_VERSIONS",
22
+ "__version__",
23
+ # gravitywell._auth
24
+ "PiHoleAuth",
25
+ # gravitywell._client
26
+ "AsyncPiHole",
27
+ "PiHole",
28
+ ]
gravitywell/_auth.py ADDED
@@ -0,0 +1,134 @@
1
+ """Session authentication for a Pi-hole."""
2
+
3
+ import threading
4
+ from collections.abc import AsyncGenerator, Callable, Generator
5
+ from contextlib import suppress
6
+ from dataclasses import dataclass
7
+
8
+ import anyio
9
+ import httpx2
10
+
11
+ from gravitywell.models import Session, SessionResponse
12
+
13
+ _SID_HEADER = "X-FTL-SID"
14
+ # A request is sent once, and once more after a 401 with a new login.
15
+ _ATTEMPTS = 2
16
+ _AUTH_PATH = "/api/auth"
17
+
18
+ type PasswordProvider = Callable[[], str]
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class _Login:
23
+ """A session, with the URL that issued it, where logging out goes."""
24
+
25
+ session: Session
26
+ url: httpx2.URL
27
+
28
+
29
+ class PiHoleAuth(httpx2.Auth):
30
+ """Log in to a Pi-hole with a password, and send its session on requests.
31
+
32
+ Pass it as a client's `auth=`:
33
+
34
+ with PiHole("http://pi.hole", auth=PiHoleAuth(password)) as api:
35
+ api.info.version()
36
+
37
+ It logs in before the first request (`POST /api/auth`), sends the session in
38
+ the `X-FTL-SID` header, and logs in again once if a request gets a 401.
39
+ Concurrent requests share one login, since a Pi-hole allows only a few
40
+ sessions at a time. A failed login raises `httpx2.HTTPStatusError` with
41
+ the login's response. The clients log out when they close.
42
+
43
+ Use an application password, which Pi-hole's settings create. Two-factor
44
+ authentication isn't supported. To read the password at each login, such
45
+ as from a secret file that's replaced when it changes, pass a function
46
+ that returns it: `PiHoleAuth(lambda: path.read_text().strip())`. Async
47
+ clients call it in the event loop, so it should be quick.
48
+ """
49
+
50
+ def __init__(self, password: str | PasswordProvider) -> None:
51
+ self._password = password
52
+ # None until logged in. A session whose sid is None means the Pi-hole
53
+ # has no password, so no header is sent.
54
+ self._login: _Login | None = None
55
+ self._sync_lock = threading.Lock()
56
+ self._async_lock = anyio.Lock()
57
+
58
+ def sync_auth_flow(self, request: httpx2.Request) -> Generator[httpx2.Request, httpx2.Response, None]:
59
+ rejected: _Login | None = None
60
+ for _ in range(_ATTEMPTS):
61
+ with self._sync_lock:
62
+ # Log in if there's no session, or if this request's session
63
+ # was rejected and no other request has logged in again since.
64
+ if self._login is None or self._login is rejected:
65
+ login_response = yield self._login_request(request)
66
+ login_response.read()
67
+ self._login = _login_from(login_response)
68
+ login = self._login
69
+ _send_session(request, login.session)
70
+ response = yield request
71
+ if response.status_code != 401:
72
+ return
73
+ rejected = login
74
+
75
+ async def async_auth_flow(self, request: httpx2.Request) -> AsyncGenerator[httpx2.Request, httpx2.Response]:
76
+ rejected: _Login | None = None
77
+ for _ in range(_ATTEMPTS):
78
+ async with self._async_lock:
79
+ # Log in if there's no session, or if this request's session
80
+ # was rejected and no other request has logged in again since.
81
+ if self._login is None or self._login is rejected:
82
+ login_response = yield self._login_request(request)
83
+ await login_response.aread()
84
+ self._login = _login_from(login_response)
85
+ login = self._login
86
+ _send_session(request, login.session)
87
+ response = yield request
88
+ if response.status_code != 401:
89
+ return
90
+ rejected = login
91
+
92
+ def log_out(self, client: httpx2.Client) -> None:
93
+ """Log out of the session through `client`, if there is one.
94
+
95
+ The clients call it when they close. A failed logout is ignored: the
96
+ session expires on its own.
97
+ """
98
+ login, self._login = self._login, None
99
+ if login is not None and login.session.sid is not None:
100
+ with suppress(httpx2.HTTPError):
101
+ client.delete(login.url, headers={_SID_HEADER: login.session.sid}, auth=httpx2.Auth())
102
+
103
+ async def alog_out(self, client: httpx2.AsyncClient) -> None:
104
+ """Log out of the session through `client`, if there is one.
105
+
106
+ The async clients call it when they close. A failed logout is ignored:
107
+ the session expires on its own.
108
+ """
109
+ login, self._login = self._login, None
110
+ if login is not None and login.session.sid is not None:
111
+ with suppress(httpx2.HTTPError):
112
+ await client.delete(login.url, headers={_SID_HEADER: login.session.sid}, auth=httpx2.Auth())
113
+
114
+ def _login_request(self, request: httpx2.Request) -> httpx2.Request:
115
+ # Requests made in an auth flow skip the client's default headers.
116
+ user_agent = request.headers.get("User-Agent")
117
+ headers = {"User-Agent": user_agent} if user_agent is not None else None
118
+ login_url = request.url.copy_with(path=_AUTH_PATH)
119
+ password = self._password if isinstance(self._password, str) else self._password()
120
+ return httpx2.Request("POST", login_url, json={"password": password}, headers=headers)
121
+
122
+
123
+ def _login_from(response: httpx2.Response) -> _Login:
124
+ """Read the session, raising `httpx2.HTTPStatusError` for a failed login."""
125
+ response.raise_for_status()
126
+ body = SessionResponse.model_validate_json(response.content)
127
+ return _Login(body.session, response.request.url)
128
+
129
+
130
+ def _send_session(request: httpx2.Request, session: Session) -> None:
131
+ if session.sid is None:
132
+ request.headers.pop(_SID_HEADER, None)
133
+ else:
134
+ request.headers[_SID_HEADER] = session.sid
gravitywell/_client.py ADDED
@@ -0,0 +1,323 @@
1
+ """The Pi-hole clients."""
2
+
3
+ import ssl
4
+ from types import TracebackType
5
+ from typing import Annotated, Any, cast
6
+
7
+ from clientx import AsyncClientX, ClientX
8
+ from clientx.tools import tool
9
+ from httpx2 import URL, AsyncBaseTransport, BaseTransport
10
+ from pydantic import Field
11
+
12
+ from gravitywell import _insights
13
+ from gravitywell._auth import PiHoleAuth
14
+ from gravitywell._resources.action import Action, AsyncAction
15
+ from gravitywell._resources.auth import AsyncSessions, Sessions
16
+ from gravitywell._resources.clients import AsyncClients, Clients
17
+ from gravitywell._resources.config import AsyncConfig, Config
18
+ from gravitywell._resources.dhcp import AsyncDhcp, Dhcp
19
+ from gravitywell._resources.dns import AsyncDns, Dns
20
+ from gravitywell._resources.domains import AsyncDomains, Domains
21
+ from gravitywell._resources.groups import AsyncGroups, Groups
22
+ from gravitywell._resources.history import AsyncHistory, History
23
+ from gravitywell._resources.info import AsyncInfo, Info
24
+ from gravitywell._resources.lists import AsyncLists, Lists
25
+ from gravitywell._resources.logs import AsyncLogs, Logs
26
+ from gravitywell._resources.network import AsyncNetwork, Network
27
+ from gravitywell._resources.padd import AsyncPadd, Padd
28
+ from gravitywell._resources.queries import AsyncQueries, Queries
29
+ from gravitywell._resources.search import AsyncSearch, Search
30
+ from gravitywell._resources.stats import AsyncStats, Stats
31
+ from gravitywell._resources.teleporter import AsyncTeleporter, Teleporter
32
+ from gravitywell._version import __version__
33
+ from gravitywell.models import ClientExplanation, DomainExplanation, HealthReport
34
+
35
+ # httpx2's `__exit__` doesn't call `close()`, nor `__aexit__` `aclose()`, so
36
+ # the clients override all four to log out of a `PiHoleAuth` session.
37
+
38
+
39
+ # How many of a domain's or client's newest queries the explain tools include.
40
+ _Recent = Annotated[int, Field(ge=1, le=100)]
41
+
42
+
43
+ class _BasePiHole[TransportT: BaseTransport | AsyncBaseTransport]:
44
+ """The constructor `PiHole` and `AsyncPiHole` share, which requires `auth`.
45
+
46
+ `TransportT` is the client's kind of transport, sync or async.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ base_url: URL | str,
52
+ *,
53
+ auth: PiHoleAuth,
54
+ verify: ssl.SSLContext | bool = True,
55
+ transport: TransportT | None = None,
56
+ ) -> None:
57
+ """Create a client for the Pi-hole at `base_url`.
58
+
59
+ A client sends requests to the Pi-hole's REST API and turns the
60
+ replies into Pydantic models. Its attributes group the endpoints by
61
+ API area, such as `api.info`, and each endpoint returns a model of its
62
+ whole response body, from `gravitywell.models`. A 4xx or 5xx response
63
+ raises `httpx2.HTTPStatusError`.
64
+
65
+ It's an `httpx2.Client`, or an `httpx2.AsyncClient` for `AsyncPiHole`,
66
+ built with ClientX. It logs in on its first request and reuses that
67
+ session. Close it when you're done, by leaving its `with` block or
68
+ calling `close()` (`aclose()` when async), to log out: a Pi-hole
69
+ allows only a few sessions at a time.
70
+
71
+ Args:
72
+ base_url: The Pi-hole's URL, such as `http://pi.hole`. The client
73
+ sets its path to `/api`, where the REST API is, so
74
+ `http://pi.hole/api` works too, and any other path is
75
+ replaced.
76
+ auth: Logs in to the Pi-hole and sends its session on requests.
77
+ Closing the client logs out.
78
+ verify: How to check the Pi-hole's HTTPS certificate: an
79
+ `ssl.SSLContext` that trusts Pi-hole's self-signed one, or
80
+ `False` to skip the check.
81
+ transport: Sends the requests in place of the network, such as an
82
+ `httpx2.MockTransport` in tests. `AsyncPiHole` takes an async
83
+ one.
84
+ """
85
+ base_url = URL(base_url).copy_with(path="/api")
86
+ # `super()` is `ClientX` or `AsyncClientX`, next in the subclass's MRO,
87
+ # which pyright can't see from this class.
88
+ cast("Any", super()).__init__(base_url, auth=auth, verify=verify, transport=transport)
89
+
90
+
91
+ class PiHole(_BasePiHole[BaseTransport], ClientX, user_agent=f"gravitywell/{__version__}"):
92
+ """A client for a Pi-hole's v6 REST API.
93
+
94
+ Closing the client logs out of its session.
95
+ """
96
+
97
+ domains = Domains()
98
+ action = Action()
99
+ clients = Clients()
100
+ config = Config()
101
+ dhcp = Dhcp()
102
+ dns = Dns()
103
+ groups = Groups()
104
+ history = History()
105
+ info = Info()
106
+ lists = Lists()
107
+ logs = Logs()
108
+ network = Network()
109
+ padd = Padd()
110
+ queries = Queries()
111
+ search = Search()
112
+ sessions = Sessions()
113
+ stats = Stats()
114
+ teleporter = Teleporter()
115
+
116
+ @tool(read_only=True, idempotent=True, tags=["insights"])
117
+ def explain_domain(self, domain: str, recent: _Recent = 10) -> DomainExplanation:
118
+ """Explain what the Pi-hole does with a domain, and why, in one call.
119
+
120
+ It gathers the blocking status, the allow and deny rules and the lists
121
+ that match the domain, the names of their groups, and its newest
122
+ queries, whose status says what the Pi-hole did. Use it to answer why a
123
+ domain is blocked or allowed, rather than calling the search, groups and
124
+ query log endpoints in turn. For each client, Pi-hole decides in this
125
+ order, using only the rules and lists of the client's groups: an allow
126
+ rule, exact or regex, lets the domain through; else an exact deny rule
127
+ blocks it; else an allowlist lets it through; else a blocklist blocks
128
+ it; else a regex deny rule blocks it. It changes nothing.
129
+
130
+ Args:
131
+ domain: The domain, such as `ads.example.com`.
132
+ recent: How many of its newest queries to include, 1 to 100.
133
+ """
134
+ return _insights.explain_domain(
135
+ domain,
136
+ self.dns.blocking(),
137
+ self.search.lists(domain),
138
+ self.groups.list(),
139
+ self.queries.log(domain=domain, count=recent),
140
+ )
141
+
142
+ @tool(read_only=True, idempotent=True, tags=["insights"])
143
+ def explain_client(self, address: str, recent: _Recent = 10) -> ClientExplanation:
144
+ """Explain who a client is, which groups it's in, and what it asked for.
145
+
146
+ It gathers the device with the IP address from the Pi-hole's network
147
+ table (its MAC address, maker, hostnames and activity), the client
148
+ records that match it, the names of their groups, and its newest
149
+ queries. Use it to identify a device seen in the query log or the top
150
+ clients. A device's groups come from the first kind of client record
151
+ that matches it, in this order: IP address or subnet, MAC address,
152
+ hostname, interface; with none, it's in the Default group only. An
153
+ address that isn't an IP address is refused. It changes nothing.
154
+
155
+ Args:
156
+ address: The client's IP address, such as `192.168.1.235`.
157
+ recent: How many of its newest queries to include, 1 to 100.
158
+ """
159
+ _insights.check_address(address)
160
+ return _insights.explain_client(
161
+ address,
162
+ self.network.devices(max_devices=_insights.MAX_DEVICES, max_addresses=_insights.MAX_ADDRESSES),
163
+ self.clients.list(),
164
+ self.groups.list(),
165
+ self.queries.log(client_ip=address, count=recent),
166
+ )
167
+
168
+ @tool(read_only=True, idempotent=True, tags=["insights"])
169
+ def check_health(self) -> HealthReport:
170
+ """Check the Pi-hole's health in one call, and list what's wrong.
171
+
172
+ Its `findings` name the problems in plain words, the most urgent first,
173
+ and are empty when all is well: DNS not running, blocking off, empty or
174
+ failed blocklists, problems the Pi-hole reported, an overheating CPU,
175
+ high memory use or load, lists not downloaded yet, and updates
176
+ available. The other fields hold the details. Use it to answer whether
177
+ the Pi-hole is all right; the PADD summary shows activity rather than
178
+ problems. It changes nothing.
179
+ """
180
+ return _insights.check_health(
181
+ self.dns.blocking(),
182
+ self.info.messages(),
183
+ self.info.version(),
184
+ self.lists.list(),
185
+ self.padd.summary(),
186
+ )
187
+
188
+ def close(self) -> None:
189
+ try:
190
+ self._log_out()
191
+ finally:
192
+ super().close()
193
+
194
+ def __exit__(
195
+ self,
196
+ exc_type: type[BaseException] | None = None,
197
+ exc_value: BaseException | None = None,
198
+ traceback: TracebackType | None = None,
199
+ ) -> None:
200
+ try:
201
+ self._log_out()
202
+ finally:
203
+ super().__exit__(exc_type, exc_value, traceback)
204
+
205
+ def _log_out(self) -> None:
206
+ if isinstance(self.auth, PiHoleAuth):
207
+ self.auth.log_out(self)
208
+
209
+
210
+ class AsyncPiHole(_BasePiHole[AsyncBaseTransport], AsyncClientX, user_agent=f"gravitywell/{__version__}"):
211
+ """The async version of `PiHole`."""
212
+
213
+ domains = AsyncDomains()
214
+ action = AsyncAction()
215
+ clients = AsyncClients()
216
+ config = AsyncConfig()
217
+ dhcp = AsyncDhcp()
218
+ dns = AsyncDns()
219
+ groups = AsyncGroups()
220
+ history = AsyncHistory()
221
+ info = AsyncInfo()
222
+ lists = AsyncLists()
223
+ logs = AsyncLogs()
224
+ network = AsyncNetwork()
225
+ padd = AsyncPadd()
226
+ queries = AsyncQueries()
227
+ search = AsyncSearch()
228
+ sessions = AsyncSessions()
229
+ stats = AsyncStats()
230
+ teleporter = AsyncTeleporter()
231
+
232
+ @tool(read_only=True, idempotent=True, tags=["insights"])
233
+ async def explain_domain(self, domain: str, recent: _Recent = 10) -> DomainExplanation:
234
+ """Explain what the Pi-hole does with a domain, and why, in one call.
235
+
236
+ It gathers the blocking status, the allow and deny rules and the lists
237
+ that match the domain, the names of their groups, and its newest
238
+ queries, whose status says what the Pi-hole did. Use it to answer why a
239
+ domain is blocked or allowed, rather than calling the search, groups and
240
+ query log endpoints in turn. For each client, Pi-hole decides in this
241
+ order, using only the rules and lists of the client's groups: an allow
242
+ rule, exact or regex, lets the domain through; else an exact deny rule
243
+ blocks it; else an allowlist lets it through; else a blocklist blocks
244
+ it; else a regex deny rule blocks it. It changes nothing.
245
+
246
+ Args:
247
+ domain: The domain, such as `ads.example.com`.
248
+ recent: How many of its newest queries to include, 1 to 100.
249
+ """
250
+ return _insights.explain_domain(
251
+ domain,
252
+ await self.dns.blocking(),
253
+ await self.search.lists(domain),
254
+ await self.groups.list(),
255
+ await self.queries.log(domain=domain, count=recent),
256
+ )
257
+
258
+ @tool(read_only=True, idempotent=True, tags=["insights"])
259
+ async def explain_client(self, address: str, recent: _Recent = 10) -> ClientExplanation:
260
+ """Explain who a client is, which groups it's in, and what it asked for.
261
+
262
+ It gathers the device with the IP address from the Pi-hole's network
263
+ table (its MAC address, maker, hostnames and activity), the client
264
+ records that match it, the names of their groups, and its newest
265
+ queries. Use it to identify a device seen in the query log or the top
266
+ clients. A device's groups come from the first kind of client record
267
+ that matches it, in this order: IP address or subnet, MAC address,
268
+ hostname, interface; with none, it's in the Default group only. An
269
+ address that isn't an IP address is refused. It changes nothing.
270
+
271
+ Args:
272
+ address: The client's IP address, such as `192.168.1.235`.
273
+ recent: How many of its newest queries to include, 1 to 100.
274
+ """
275
+ _insights.check_address(address)
276
+ return _insights.explain_client(
277
+ address,
278
+ await self.network.devices(max_devices=_insights.MAX_DEVICES, max_addresses=_insights.MAX_ADDRESSES),
279
+ await self.clients.list(),
280
+ await self.groups.list(),
281
+ await self.queries.log(client_ip=address, count=recent),
282
+ )
283
+
284
+ @tool(read_only=True, idempotent=True, tags=["insights"])
285
+ async def check_health(self) -> HealthReport:
286
+ """Check the Pi-hole's health in one call, and list what's wrong.
287
+
288
+ Its `findings` name the problems in plain words, the most urgent first,
289
+ and are empty when all is well: DNS not running, blocking off, empty or
290
+ failed blocklists, problems the Pi-hole reported, an overheating CPU,
291
+ high memory use or load, lists not downloaded yet, and updates
292
+ available. The other fields hold the details. Use it to answer whether
293
+ the Pi-hole is all right; the PADD summary shows activity rather than
294
+ problems. It changes nothing.
295
+ """
296
+ return _insights.check_health(
297
+ await self.dns.blocking(),
298
+ await self.info.messages(),
299
+ await self.info.version(),
300
+ await self.lists.list(),
301
+ await self.padd.summary(),
302
+ )
303
+
304
+ async def aclose(self) -> None:
305
+ try:
306
+ await self._log_out()
307
+ finally:
308
+ await super().aclose()
309
+
310
+ async def __aexit__(
311
+ self,
312
+ exc_type: type[BaseException] | None = None,
313
+ exc_value: BaseException | None = None,
314
+ traceback: TracebackType | None = None,
315
+ ) -> None:
316
+ try:
317
+ await self._log_out()
318
+ finally:
319
+ await super().__aexit__(exc_type, exc_value, traceback)
320
+
321
+ async def _log_out(self) -> None:
322
+ if isinstance(self.auth, PiHoleAuth):
323
+ await self.auth.alog_out(self)