Debian Codegraph @

cookidoo_api/well_known.py

raw
1 """Discovery of Cookidoo API endpoints via the ``.well-known/home`` HAL documents.
2
3 Cookidoo's backend exposes a `HAL <https://en.wikipedia.org/wiki/Hypertext_Application_Language>`_
4 ``.well-known/home`` document per microservice (e.g. ``shopping``, ``planning``,
5 ``organize``), listing the live relative paths ("rels") of its endpoints. This
6 module resolves the live path template for every rel this library depends on.
7 There is no hardcoded fallback: a rel that can't be resolved (network error,
8 or a shape too different to reconcile) fails the request instead of silently
9 serving a possibly-stale path.
10
11 Only the services/rels actually consumed by this library are fetched (see
12 :data:`ENDPOINT_RELS`), not a full recursive crawl. This mapping is also the
13 single source of truth for narrowing the CI drift-check in
14 ``scripts/well-known-discovery.py`` to the endpoints we actually use.
15 """
16
17 from __future__ import annotations
18
19 import asyncio
20 import logging
21 import re
22 from typing import Final
23
24 from aiohttp import ClientError, ClientSession
25 from yarl import URL
26
27 from cookidoo_api.const import (
28 ADD_ADDITIONAL_ITEMS_PATH,
29 ADD_INGREDIENT_ITEMS_FOR_RECIPES_PATH,
30 ADD_RECIPES_TO_CALENDER_PATH,
31 COMMUNITY_PROFILE_PATH,
32 CUSTOM_COLLECTIONS_PATH,
33 CUSTOM_RECIPE_PATH,
34 CUSTOM_RECIPES_PATH,
35 DEFAULT_API_HEADERS,
36 DEVICES_PATH,
37 EDIT_ADDITIONAL_ITEMS_PATH,
38 EDIT_OWNERSHIP_ADDITIONAL_ITEMS_PATH,
39 EDIT_OWNERSHIP_INGREDIENT_ITEMS_PATH,
40 LOGIN_HEADERS,
41 MANAGED_COLLECTIONS_PATH,
42 RECIPE_PATH,
43 RECIPES_IN_CALENDAR_WEEK_PATH,
44 REMOVE_ADDITIONAL_ITEMS_PATH,
45 REMOVE_CUSTOM_COLLECTION_PATH,
46 REMOVE_INGREDIENT_ITEMS_FOR_RECIPES_PATH,
47 REMOVE_MANAGED_COLLECTION_PATH,
48 REMOVE_RECIPE_FROM_CALENDER_PATH,
49 REMOVE_RECIPE_FROM_CUSTOM_COLLECTION_PATH,
50 SEARCH_PATH,
51 SHOPPING_LIST_RECIPES_PATH,
52 SUBSCRIPTIONS_PATH,
53 )
54 from cookidoo_api.exceptions import CookidooParseException, CookidooRequestException
55
56 _LOGGER = logging.getLogger(__name__)
57
58 WELL_KNOWN_HOME_PATH: Final = ".well-known/home"
59
60 # Sent with every discovery request. The login flow's own Cloudflare-bot
61 # hazard (see LOGIN_HEADERS/const.py, issue #230) applies just as much
62 # here: these are unauthenticated GETs against the same cookidoo.* domain,
63 # and since there is no hardcoded fallback, a 403 here is a total outage
64 # for every method of the client, not just degraded behaviour.
65 _DISCOVERY_HEADERS: Final = {**DEFAULT_API_HEADERS, **LOGIN_HEADERS}
66
67
68 # Maps each well-known "rel" this library depends on to the HAL service
69 # document exposing it and the shape (placeholder names, matching our
70 # `.format(language=..., id=...)` call sites) a discovered href is
71 # normalized against. The rel itself is the lookup key everywhere else
72 # (Cookidoo._path(rel)), so a rel backing more than one call site (e.g.
73 # ``pantry:home`` is shared by the shopping list, ingredient items, and
74 # additional items screens) is declared once here, not once per caller.
75 #
76 # Only rels actually resolved via _path() belong here: resolve_endpoint_paths()
77 # is all-or-nothing, so an extra unused rel would make every API call
78 # depend on a service/rel the library never calls (e.g. ``fint:login``,
79 # which login() never uses since auth goes through the OAuth2/CIAM flow,
80 # not this HAL document -- that one is instead watched separately by
81 # scripts/well-known-discovery.py's drift-check, since we still want a
82 # heads-up if it disappears, without it being a hard runtime dependency).
83 # Keep this in sync with scripts/well-known-discovery.py's own allow-list.
84 ENDPOINT_RELS: Final[dict[str, tuple[str, str]]] = {
85 "recipe:details": ("recipes/recipe", RECIPE_PATH),
86 "customer-recipes:recipe-create": ("created-recipes", CUSTOM_RECIPES_PATH),
87 "customer-recipes:recipe-details": ("created-recipes", CUSTOM_RECIPE_PATH),
88 "community-profile:user-private-profile": (
89 "community/profile",
90 COMMUNITY_PROFILE_PATH,
91 ),
92 "ownership:subscriptions": ("ownership", SUBSCRIPTIONS_PATH),
93 "pantry:home": ("shopping", SHOPPING_LIST_RECIPES_PATH),
94 "pantry:edit-ingredients-ownership": (
95 "shopping",
96 EDIT_OWNERSHIP_INGREDIENT_ITEMS_PATH,
97 ),
98 "pantry:recipe-ingredients": ("shopping", ADD_INGREDIENT_ITEMS_FOR_RECIPES_PATH),
99 "pantry:remove-recipe": ("shopping", REMOVE_INGREDIENT_ITEMS_FOR_RECIPES_PATH),
100 "pantry:add-additional-items-v2": ("shopping", ADD_ADDITIONAL_ITEMS_PATH),
101 "pantry:edit-additional-items": ("shopping", EDIT_ADDITIONAL_ITEMS_PATH),
102 "pantry:edit-additional-items-ownership": (
103 "shopping",
104 EDIT_OWNERSHIP_ADDITIONAL_ITEMS_PATH,
105 ),
106 "pantry:remove-additional-items": ("shopping", REMOVE_ADDITIONAL_ITEMS_PATH),
107 "organize:api-custom-list": ("organize", CUSTOM_COLLECTIONS_PATH),
108 "organize:api-custom-list-modify": ("organize", REMOVE_CUSTOM_COLLECTION_PATH),
109 "organize:api-custom-list-recipe": (
110 "organize",
111 REMOVE_RECIPE_FROM_CUSTOM_COLLECTION_PATH,
112 ),
113 "organize:api-managed-list": ("organize", MANAGED_COLLECTIONS_PATH),
114 "organize:api-managed-list-single": ("organize", REMOVE_MANAGED_COLLECTION_PATH),
115 "planning:api-my-week-from-date": ("planning", RECIPES_IN_CALENDAR_WEEK_PATH),
116 "planning:api-my-day": ("planning", ADD_RECIPES_TO_CALENDER_PATH),
117 "planning:api-my-day-recipes": ("planning", REMOVE_RECIPE_FROM_CALENDER_PATH),
118 "customer-devices:thermomix-versions": ("customer-devices", DEVICES_PATH),
119 "search:home": ("search", SEARCH_PATH),
120 }
121
122 _DOMAIN_PREFIX_RE = re.compile(r"^https?://[^/]+")
123 _QUERY_SUFFIX_RE = re.compile(r"\{[?&].*$")
124 _TOKEN_RE = re.compile(r"(\{/?)([A-Za-z0-9_]+)(\})")
125
126 # Cookidoo's own token names, as observed live, mapped to the set of our
127 # names they may legitimately stand for (``lang`` backs both our
128 # ``language`` and, for the search endpoint, ``locale``). A discovered
129 # token whose name is in here MUST line up (at its position) with one of
130 # these our-names, or normalization fails -- this catches a silent
131 # reordering (e.g. two same-shaped placeholders swapped) that a purely
132 # positional substitution would otherwise wave through. A discovered token
133 # whose name we don't recognize at all falls back to positional
134 # substitution, on the assumption it's simply a token Cookidoo hasn't
135 # renamed since we last looked.
136 _KNOWN_TOKEN_ALIASES: Final[dict[str, frozenset[str]]] = {
137 "lang": frozenset({"language", "locale"}),
138 "id": frozenset({"id"}),
139 "dayKey": frozenset({"day"}),
140 "recipeId": frozenset({"recipe"}),
141 }
142
143
144 def _normalize_href(href: str, shape_template: str) -> str | None:
145 """Normalize a discovered HAL href into our own template shape.
146
147 The discovered ``href`` may be absolute (with scheme/host), may carry a
148 trailing RFC 6570 query template (``{?a,b}``), and uses variable names
149 that differ from ours (e.g. ``{lang}``/``{dayKey}`` instead of
150 ``{language}``/``{day}``). We keep the *literal* path segments from the
151 live document (so a renamed segment is picked up automatically) but
152 always substitute our own variable names, so existing
153 ``.format(language=..., id=...)`` call sites elsewhere keep working
154 unchanged. A token we recognize (see :data:`_KNOWN_TOKEN_ALIASES`) must
155 line up with one of our expected names at that position; an unknown
156 token name falls back to positional substitution.
157
158 Returns ``None`` if the number of variables doesn't match, or a known
159 token's position doesn't match one of its expected names, since that
160 indicates a shape/order change too significant to reconcile
161 automatically.
162 """
163 path = _DOMAIN_PREFIX_RE.sub("", href)
164 path = _QUERY_SUFFIX_RE.sub("", path)
165
166 our_tokens = [m.group(2) for m in _TOKEN_RE.finditer(shape_template)]
167 discovered_tokens = [m.group(2) for m in _TOKEN_RE.finditer(path)]
168 if len(our_tokens) != len(discovered_tokens):
169 return None
170
171 for discovered_name, our_name in zip(discovered_tokens, our_tokens, strict=True):
172 expected = _KNOWN_TOKEN_ALIASES.get(discovered_name)
173 if expected is not None and our_name not in expected:
174 return None
175
176 it = iter(our_tokens)
177
178 def _replace(match: re.Match[str]) -> str:
179 prefix = "/" if match.group(1) == "{/" else ""
180 return f"{prefix}{{{next(it)}}}"
181
182 normalized = _TOKEN_RE.sub(_replace, path)
183 return normalized.lstrip("/")
184
185
186 async def _fetch_service_links(
187 session: ClientSession, service_url: URL
188 ) -> dict[str, str] | None:
189 """Fetch a single ``.well-known/home`` HAL document's rel -> href links."""
190 try:
191 async with session.get(service_url, headers=_DISCOVERY_HEADERS) as resp:
192 if resp.status != 200:
193 _LOGGER.debug(
194 "Well-known discovery: %s returned status %s, skipping.",
195 service_url,
196 resp.status,
197 )
198 return None
199 doc = await resp.json(content_type=None)
200 except (ClientError, TimeoutError, ValueError) as e:
201 _LOGGER.debug("Well-known discovery failed for %s: %s", service_url, e)
202 return None
203
204 links = doc.get("_links") if isinstance(doc, dict) else None
205 if not isinstance(links, dict):
206 return None
207
208 result: dict[str, str] = {}
209 for rel, value in links.items():
210 href: object = None
211 if isinstance(value, dict):
212 href = value.get("href")
213 elif isinstance(value, list) and value and isinstance(value[0], dict):
214 href = value[0].get("href")
215 if isinstance(href, str):
216 result[rel] = href
217 return result
218
219
220 async def resolve_endpoint_paths(
221 session: ClientSession, api_endpoint: URL
222 ) -> dict[str, str]:
223 """Resolve live endpoint path templates via ``.well-known/home`` discovery.
224
225 Fetches only the services referenced in :data:`ENDPOINT_RELS` (not a full
226 recursive crawl, and concurrently rather than one at a time), extracts
227 only the rels we use, and normalizes them into our template shape.
228
229 Parameters
230 ----------
231 session
232 The client session for aiohttp requests.
233 api_endpoint
234 The Cookidoo domain root (e.g. ``https://cookidoo.ch``) to resolve
235 service discovery documents against.
236
237 Returns
238 -------
239 dict[str, str]
240 A mapping of rel -> discovered path template, for every rel in
241 :data:`ENDPOINT_RELS`. Only returned once every single one resolved
242 successfully; otherwise this function raises instead (there is no
243 partial/hardcoded fallback).
244
245 Raises
246 ------
247 CookidooRequestException
248 If a service's ``.well-known/home`` document could not be reached.
249 CookidooParseException
250 If a rel is missing from its service document, or its discovered
251 href's shape can't be reconciled with ours.
252
253 """
254 services = sorted({service for service, _shape in ENDPOINT_RELS.values()})
255 fetched = await asyncio.gather(
256 *(
257 _fetch_service_links(session, api_endpoint / service / WELL_KNOWN_HOME_PATH)
258 for service in services
259 )
260 )
261 service_links: dict[str, dict[str, str] | None] = dict(
262 zip(services, fetched, strict=True)
263 )
264
265 overrides: dict[str, str] = {}
266 for rel, (service, shape_template) in ENDPOINT_RELS.items():
267 links = service_links.get(service)
268 if links is None:
269 raise CookidooRequestException(
270 f"Endpoint discovery failed: could not reach the '{service}' "
271 f"service's .well-known/home document (needed to resolve "
272 f"'{rel}')."
273 )
274 if rel not in links:
275 raise CookidooParseException(
276 f"Endpoint discovery failed: the '{service}' service's "
277 f".well-known/home document no longer exposes the '{rel}' "
278 f"relation."
279 )
280 normalized = _normalize_href(links[rel], shape_template)
281 if normalized is None:
282 raise CookidooParseException(
283 f"Endpoint discovery failed: the '{rel}' relation on the "
284 f"'{service}' service changed shape unexpectedly."
285 )
286 overrides[rel] = normalized
287 return overrides