technicallyfit 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.
@@ -0,0 +1,49 @@
1
+ """The HTTP transport: the standard library's urllib, with redirects refused.
2
+
3
+ A transport is any callable ``(method, url, headers, body, timeout) -> HttpResponse``. Pass
4
+ your own to use another HTTP library, or a fake one in tests. A transport raises
5
+ ``OSError`` (or a subclass) when no answer arrives.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import urllib.error
11
+ import urllib.request
12
+ from collections.abc import Callable, Mapping
13
+ from dataclasses import dataclass, field
14
+
15
+
16
+ @dataclass
17
+ class HttpResponse:
18
+ status: int
19
+ headers: Mapping[str, str] = field(default_factory=dict)
20
+ body: bytes = b""
21
+
22
+ def header(self, name: str) -> str | None:
23
+ wanted = name.lower()
24
+ for key, value in self.headers.items():
25
+ if key.lower() == wanted:
26
+ return value
27
+ return None
28
+
29
+
30
+ Transport = Callable[[str, str, dict[str, str], "bytes | None", float], HttpResponse]
31
+
32
+
33
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
34
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
35
+ return None
36
+
37
+
38
+ _opener = urllib.request.build_opener(_NoRedirect)
39
+
40
+
41
+ def urllib_transport(method: str, url: str, headers: dict[str, str], body: bytes | None, timeout: float) -> HttpResponse:
42
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
43
+ try:
44
+ with _opener.open(request, timeout=timeout) as response:
45
+ return HttpResponse(response.status, dict(response.headers.items()), response.read())
46
+ except urllib.error.HTTPError as error:
47
+ # A 3xx lands here too, because the redirect handler refuses to follow it.
48
+ with error:
49
+ return HttpResponse(error.code, dict(error.headers.items()) if error.headers else {}, error.read())
@@ -0,0 +1,269 @@
1
+ """Offline Ed25519 verification for TechnicallyFit attestation statements (``attestation/1``).
2
+
3
+ Pure Python using only the standard library (``hashlib``, ``base64``, ``json``): no external
4
+ dependency. Implements RFC 8032 Section 5.1.7 Ed25519 signature verification and RFC 8785 (JCS)
5
+ canonical JSON serialization.
6
+
7
+ Offline verification proves signature authenticity only; it cannot see revocation or measurement
8
+ withdrawal. Call ``GET /v1/attestations/{attestation_id}/status`` for live status.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ from dataclasses import dataclass
15
+ import hashlib
16
+ import json
17
+ import math
18
+ from typing import Any, Literal, Mapping, Sequence
19
+
20
+ AttestationVerificationFailure = Literal[
21
+ "invalid_statement",
22
+ "unknown_key",
23
+ "signature_mismatch",
24
+ ]
25
+
26
+
27
+ class AttestationVerificationError(Exception):
28
+ """Raised when an attestation envelope fails offline verification."""
29
+
30
+ def __init__(self, reason: AttestationVerificationFailure, message: str) -> None:
31
+ super().__init__(message)
32
+ self.reason: AttestationVerificationFailure = reason
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class VerifiedAttestation:
37
+ """Result returned when an attestation signature verifies against a published key."""
38
+
39
+ key_id: str
40
+ key_status: str
41
+ mode: str
42
+ statement: dict[str, Any]
43
+
44
+
45
+ # --- RFC 8032 Ed25519 verify-only (pure Python, zero dependencies) -----------------------------
46
+
47
+ _P = 2**255 - 19
48
+ _L = 2**252 + 27742317777372353535851937790883648493
49
+ _D = (-121665 * pow(121666, _P - 2, _P)) % _P
50
+ _I = pow(2, (_P - 1) // 4, _P)
51
+ _B_Y = (4 * pow(5, _P - 2, _P)) % _P
52
+ _B_X = 15112221349535400772501151409588531511454012693041857206046113283949847762202
53
+ _BASE_POINT = (_B_X, _B_Y, 1, (_B_X * _B_Y) % _P)
54
+ _NEUTRAL_POINT = (0, 1, 1, 0)
55
+
56
+
57
+ def _point_add(
58
+ p: tuple[int, int, int, int], q: tuple[int, int, int, int]
59
+ ) -> tuple[int, int, int, int]:
60
+ x1, y1, z1, t1 = p
61
+ x2, y2, z2, t2 = q
62
+ a = ((y1 - x1) * (y2 - x2)) % _P
63
+ b = ((y1 + x1) * (y2 + x2)) % _P
64
+ c = (2 * t1 * t2 * _D) % _P
65
+ d = (2 * z1 * z2) % _P
66
+ e = (b - a) % _P
67
+ f = (d - c) % _P
68
+ g = (d + c) % _P
69
+ h = (b + a) % _P
70
+ return ((e * f) % _P, (g * h) % _P, (f * g) % _P, (e * h) % _P)
71
+
72
+
73
+ def _point_mul(s: int, p: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
74
+ q = _NEUTRAL_POINT
75
+ cur = p
76
+ while s > 0:
77
+ if s & 1:
78
+ q = _point_add(q, cur)
79
+ cur = _point_add(cur, cur)
80
+ s >>= 1
81
+ return q
82
+
83
+
84
+ def _point_equal(p: tuple[int, int, int, int], q: tuple[int, int, int, int]) -> bool:
85
+ x1, y1, z1, _ = p
86
+ x2, y2, z2, _ = q
87
+ return (x1 * z2 - x2 * z1) % _P == 0 and (y1 * z2 - y2 * z1) % _P == 0
88
+
89
+
90
+ def _decode_point(data: bytes) -> tuple[int, int, int, int] | None:
91
+ if len(data) != 32:
92
+ return None
93
+ y = int.from_bytes(data, "little")
94
+ sign = (y >> 255) & 1
95
+ y &= (1 << 255) - 1
96
+ if y >= _P:
97
+ return None
98
+ y2 = (y * y) % _P
99
+ u = (y2 - 1) % _P
100
+ v = (_D * y2 + 1) % _P
101
+ x = (u * pow(v, 3, _P) * pow((u * pow(v, 7, _P)) % _P, (_P - 5) // 8, _P)) % _P
102
+ vx2 = (v * x * x) % _P
103
+ if vx2 == u:
104
+ pass
105
+ elif vx2 == (-u) % _P:
106
+ x = (x * _I) % _P
107
+ else:
108
+ return None
109
+ if x == 0 and sign == 1:
110
+ return None
111
+ if (x & 1) != sign:
112
+ x = _P - x
113
+ return (x, y, 1, (x * y) % _P)
114
+
115
+
116
+ def verify_ed25519(public_key: bytes, message: bytes, signature: bytes) -> bool:
117
+ """Pure-Python RFC 8032 Section 5.1.7 Ed25519 signature verification."""
118
+ if len(public_key) != 32 or len(signature) != 64:
119
+ return False
120
+ a_point = _decode_point(public_key)
121
+ if a_point is None:
122
+ return False
123
+ r_bytes = signature[:32]
124
+ r_point = _decode_point(r_bytes)
125
+ if r_point is None:
126
+ return False
127
+ s = int.from_bytes(signature[32:], "little")
128
+ if s >= _L:
129
+ return False
130
+ h = int.from_bytes(hashlib.sha512(r_bytes + public_key + message).digest(), "little") % _L
131
+ lhs = _point_mul(s, _BASE_POINT)
132
+ rhs = _point_add(r_point, _point_mul(h, a_point))
133
+ return _point_equal(lhs, rhs)
134
+
135
+
136
+ # --- RFC 8785 (JCS) canonical JSON ------------------------------------------------------------
137
+
138
+
139
+ def _canonical_number(value: int | float) -> str:
140
+ if isinstance(value, bool):
141
+ return "true" if value else "false"
142
+ if isinstance(value, int):
143
+ return str(value)
144
+ if not math.isfinite(value):
145
+ raise AttestationVerificationError(
146
+ "invalid_statement", "Attestation statement contains a non-finite number."
147
+ )
148
+ if value == 0.0:
149
+ return "0"
150
+ if value.is_integer() and abs(value) < 1e21:
151
+ return str(int(value))
152
+ return json.dumps(value)
153
+
154
+
155
+ def canonicalize_json(value: Any) -> str:
156
+ """RFC 8785 (JCS) canonical JSON serialization for attestation statements."""
157
+ if value is None:
158
+ return "null"
159
+ if isinstance(value, bool):
160
+ return "true" if value else "false"
161
+ if isinstance(value, (int, float)):
162
+ return _canonical_number(value)
163
+ if isinstance(value, str):
164
+ return json.dumps(value, ensure_ascii=False)
165
+ if isinstance(value, (list, tuple)):
166
+ return "[" + ",".join(canonicalize_json(item) for item in value) + "]"
167
+ if isinstance(value, Mapping):
168
+ items = sorted(
169
+ ((str(k), v) for k, v in value.items()),
170
+ key=lambda kv: kv[0].encode("utf-16-be"),
171
+ )
172
+ return "{" + ",".join(
173
+ f"{json.dumps(k, ensure_ascii=False)}:{canonicalize_json(v)}" for k, v in items
174
+ ) + "}"
175
+ raise AttestationVerificationError(
176
+ "invalid_statement", "Attestation statement is not readable JSON."
177
+ )
178
+
179
+
180
+ def _decode_base64url(text: str) -> bytes:
181
+ if not isinstance(text, str) or not text:
182
+ raise AttestationVerificationError(
183
+ "invalid_statement", "Attestation contains invalid base64url encoding."
184
+ )
185
+ padded = text + "=" * ((4 - len(text) % 4) % 4)
186
+ try:
187
+ return base64.urlsafe_b64decode(padded.encode("ascii"))
188
+ except Exception as exc: # noqa: BLE001
189
+ raise AttestationVerificationError(
190
+ "invalid_statement", "Attestation contains invalid base64url encoding."
191
+ ) from exc
192
+
193
+
194
+ def verify_attestation(
195
+ attestation: Mapping[str, Any],
196
+ keys: Sequence[Mapping[str, Any]] | Mapping[str, Any],
197
+ ) -> VerifiedAttestation:
198
+ """Verifies an attestation envelope offline against the published public key list.
199
+
200
+ Returns ``VerifiedAttestation`` when valid; raises ``AttestationVerificationError`` with a
201
+ typed ``reason`` (``invalid_statement``, ``unknown_key``, or ``signature_mismatch``).
202
+ """
203
+ if not isinstance(attestation, Mapping):
204
+ raise AttestationVerificationError("invalid_statement", "Attestation must be an object.")
205
+ signature_b64 = attestation.get("signature")
206
+ key_id = attestation.get("key_id")
207
+ algorithm = attestation.get("algorithm")
208
+ statement = attestation.get("statement")
209
+ if (
210
+ not isinstance(signature_b64, str)
211
+ or not signature_b64
212
+ or not isinstance(key_id, str)
213
+ or not key_id
214
+ or algorithm != "Ed25519"
215
+ or not isinstance(statement, Mapping)
216
+ ):
217
+ raise AttestationVerificationError(
218
+ "invalid_statement",
219
+ "Attestation is missing signature, key_id, statement or Ed25519 algorithm.",
220
+ )
221
+ if statement.get("version") != "attestation/1" or statement.get("key_id") != key_id:
222
+ raise AttestationVerificationError(
223
+ "invalid_statement",
224
+ "Attestation statement version or key_id is invalid.",
225
+ )
226
+
227
+ key_list: Sequence[Mapping[str, Any]]
228
+ if isinstance(keys, Mapping):
229
+ raw_keys = keys.get("keys")
230
+ if not isinstance(raw_keys, Sequence):
231
+ raise AttestationVerificationError("invalid_statement", "Published key list is invalid.")
232
+ key_list = raw_keys
233
+ else:
234
+ key_list = keys
235
+
236
+ matched = next((item for item in key_list if item.get("key_id") == key_id), None)
237
+ if matched is None:
238
+ raise AttestationVerificationError(
239
+ "unknown_key", f'Key "{key_id}" is not in the published key list.'
240
+ )
241
+ if matched.get("algorithm") != "Ed25519":
242
+ raise AttestationVerificationError(
243
+ "invalid_statement", f'Key "{key_id}" uses an unsupported algorithm.'
244
+ )
245
+
246
+ signature_bytes = _decode_base64url(signature_b64)
247
+ if len(signature_bytes) != 64:
248
+ raise AttestationVerificationError(
249
+ "invalid_statement", "Ed25519 signature must be 64 bytes."
250
+ )
251
+ public_key_bytes = _decode_base64url(str(matched.get("public_key", "")))
252
+ if len(public_key_bytes) != 32:
253
+ raise AttestationVerificationError(
254
+ "invalid_statement", "Ed25519 public key must be 32 bytes."
255
+ )
256
+
257
+ canonical_bytes = canonicalize_json(statement).encode("utf-8")
258
+ if not verify_ed25519(public_key_bytes, canonical_bytes, signature_bytes):
259
+ raise AttestationVerificationError(
260
+ "signature_mismatch",
261
+ "Attestation signature does not match the statement and public key.",
262
+ )
263
+
264
+ return VerifiedAttestation(
265
+ key_id=str(matched["key_id"]),
266
+ key_status=str(matched.get("status", "active")),
267
+ mode=str(matched.get("mode", "live")),
268
+ statement=dict(statement),
269
+ )
@@ -0,0 +1,260 @@
1
+ """The client: typed operations generated from the public spec, sent with retries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import random as _random
7
+ import time
8
+ import urllib.parse
9
+ from collections.abc import Callable, Iterator
10
+ from dataclasses import replace
11
+ from typing import Any, Protocol, TypeVar, runtime_checkable
12
+
13
+ from ._generated.operations import Operations
14
+ from ._generated.spec import DEFAULT_BASE_URL
15
+ from ._generated.version import SDK_VERSION
16
+ from ._transport import HttpResponse, Transport, urllib_transport
17
+ from .errors import (
18
+ ConfigurationError,
19
+ ConnectionError,
20
+ RateLimitInfo,
21
+ RedirectRefusedError,
22
+ TechnicallyFitError,
23
+ error_for,
24
+ )
25
+ from .events import EventsApi
26
+ from .retry import RetryOptions, is_idempotent, is_retryable, parse_retry_after, retry_wait
27
+
28
+
29
+ @runtime_checkable
30
+ class TokenCredential(Protocol):
31
+ """A credential that refreshes itself, such as ``RefreshingTeammateCredential``.
32
+ It is always sent as ``Authorization: Bearer``."""
33
+
34
+ def get_token(self) -> str: ...
35
+
36
+ def on_unauthorized(self, token: str) -> bool: ...
37
+
38
+
39
+ Credential = str | Callable[[], str] | TokenCredential
40
+ """An organization key (``tf_test_...`` or ``tf_live_...``, sent in ``X-API-Key``), a teammate
41
+ access token (``tf_at_...``, sent as ``Authorization: Bearer``), a function that returns
42
+ either, or a refreshing token credential. Organization keys belong on your servers only."""
43
+
44
+ _TEAMMATE_TOKEN_PREFIX = "tf_at_"
45
+ _LOOPBACK = {"localhost", "127.0.0.1", "::1"}
46
+
47
+ T = TypeVar("T")
48
+
49
+
50
+ def checked_base_url(value: str, what: str) -> urllib.parse.SplitResult:
51
+ """https, or http on this machine only; no query, fragment or credentials."""
52
+ parts = urllib.parse.urlsplit(value)
53
+ if not parts.scheme or not parts.hostname:
54
+ raise ConfigurationError(f"{what} is not a valid URL.")
55
+ if parts.scheme != "https" and not (parts.scheme == "http" and parts.hostname in _LOOPBACK):
56
+ raise ConfigurationError(f"{what} must use https (plain http is allowed only for localhost).")
57
+ if parts.query or parts.fragment or parts.username or parts.password:
58
+ raise ConfigurationError(f"{what} must not hold a query, a fragment or credentials.")
59
+ return parts
60
+
61
+
62
+ def _credential_headers(value: str, bearer: bool) -> dict[str, str]:
63
+ if not value:
64
+ raise ConfigurationError("The credential is empty.")
65
+ if bearer or value.startswith(_TEAMMATE_TOKEN_PREFIX):
66
+ return {"Authorization": f"Bearer {value}"}
67
+ return {"X-API-Key": value}
68
+
69
+
70
+ def _int_header(response: HttpResponse, name: str) -> int | None:
71
+ value = response.header(name)
72
+ return int(value) if value is not None and value.strip().isdigit() else None
73
+
74
+
75
+ def _rate_limit(response: HttpResponse) -> RateLimitInfo | None:
76
+ info = RateLimitInfo(
77
+ limit=_int_header(response, "X-RateLimit-Limit"),
78
+ remaining=_int_header(response, "X-RateLimit-Remaining"),
79
+ reset=_int_header(response, "X-RateLimit-Reset"),
80
+ limit_day=_int_header(response, "X-RateLimit-Limit-Day"),
81
+ remaining_day=_int_header(response, "X-RateLimit-Remaining-Day"),
82
+ reset_day=_int_header(response, "X-RateLimit-Reset-Day"),
83
+ )
84
+ return info if any(value is not None for value in vars(info).values()) else None
85
+
86
+
87
+ def _query_value(value: Any) -> str:
88
+ if isinstance(value, bool):
89
+ return "true" if value else "false"
90
+ return str(value)
91
+
92
+
93
+ class Client(Operations):
94
+ """A client for the TechnicallyFit API. Every public operation is a method, such as
95
+ ``list_teammates`` or ``send_teammate_events``; ``events`` adds validation, keys and
96
+ chunking on top."""
97
+
98
+ def __init__(
99
+ self,
100
+ credential: Credential,
101
+ *,
102
+ base_url: str | None = None,
103
+ retry: RetryOptions | None = None,
104
+ timeout: float = 30.0,
105
+ transport: Transport | None = None,
106
+ on_rate_limit: Callable[[RateLimitInfo], None] | None = None,
107
+ sleep: Callable[[float], None] = time.sleep,
108
+ now: Callable[[], float] = time.time,
109
+ random: Callable[[], float] = _random.random,
110
+ ) -> None:
111
+ if not credential:
112
+ raise ConfigurationError("A credential is required: an organization key, a teammate token or a credential provider.")
113
+ parts = checked_base_url(base_url or DEFAULT_BASE_URL, "base_url")
114
+ self.base_url = urllib.parse.urlunsplit(parts).rstrip("/")
115
+ self._origin = (parts.scheme, parts.netloc)
116
+ self._credential = credential
117
+ self._retry = retry or RetryOptions()
118
+ self._timeout = timeout
119
+ self._transport = transport or urllib_transport
120
+ self._on_rate_limit = on_rate_limit
121
+ self._sleep = sleep
122
+ self._now = now
123
+ self._random = random
124
+ self.events = EventsApi(self)
125
+
126
+ def paginate(self, operation: Callable[..., Any], /, **params: Any) -> Iterator[Any]:
127
+ """Every item of a list operation, page after page, following ``next_cursor``::
128
+
129
+ for teammate in tf.paginate(tf.list_teammates, status="claimed"):
130
+ ...
131
+ """
132
+ cursor = None
133
+ while True:
134
+ page = operation(**params, cursor=cursor) if cursor is not None else operation(**params)
135
+ yield from page["data"]
136
+ cursor = page.get("next_cursor")
137
+ if cursor is None:
138
+ return
139
+
140
+ def _url(self, path: str, path_params: dict[str, str] | None, query: dict[str, Any] | None) -> str:
141
+ if not path.startswith("/v1/"):
142
+ raise ConfigurationError("The SDK calls public /v1 operations only.")
143
+ for name, value in (path_params or {}).items():
144
+ if value is None or value == "":
145
+ raise ConfigurationError(f"The path parameter {name} is required.")
146
+ path = path.replace("{" + name + "}", urllib.parse.quote(str(value), safe="@:"))
147
+ pairs: list[tuple[str, str]] = []
148
+ for key, value in (query or {}).items():
149
+ if value is None:
150
+ continue
151
+ for item in value if isinstance(value, (list, tuple)) else [value]:
152
+ pairs.append((key, _query_value(item)))
153
+ url = self.base_url + path + (("?" + urllib.parse.urlencode(pairs)) if pairs else "")
154
+ parts = urllib.parse.urlsplit(url)
155
+ if (parts.scheme, parts.netloc) != self._origin:
156
+ raise ConfigurationError("Refusing to send the credential to a host other than the configured one.")
157
+ return url
158
+
159
+ def _resolve_credential(self) -> tuple[dict[str, str], str, TokenCredential | None]:
160
+ source = self._credential
161
+ if isinstance(source, str):
162
+ return _credential_headers(source, False), source, None
163
+ if isinstance(source, TokenCredential):
164
+ token = source.get_token()
165
+ return _credential_headers(token, True), token, source
166
+ token = source()
167
+ return _credential_headers(token, False), token, None
168
+
169
+ def _request(
170
+ self,
171
+ method: str,
172
+ path: str,
173
+ *,
174
+ path_params: dict[str, str] | None,
175
+ query: dict[str, Any] | None,
176
+ body: Any,
177
+ retry: RetryOptions | bool | None,
178
+ ) -> Any:
179
+ options = self._retry
180
+ if retry is False:
181
+ options = replace(options, max_attempts=1)
182
+ elif isinstance(retry, RetryOptions):
183
+ options = retry
184
+ url = self._url(path, path_params, query)
185
+ # Serialized once: every attempt sends the same bytes.
186
+ data = None if body is None else json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
187
+ idempotent = is_idempotent(method, path)
188
+ refreshed = False
189
+ attempt = 1
190
+ while True:
191
+ credential_headers, token, refreshable = self._resolve_credential()
192
+ headers = {
193
+ "Accept": "application/json",
194
+ "User-Agent": f"technicallyfit-sdk-python/{SDK_VERSION}",
195
+ **credential_headers,
196
+ }
197
+ if data is not None:
198
+ headers["Content-Type"] = "application/json"
199
+ try:
200
+ response = self._transport(method, url, headers, data, self._timeout)
201
+ except OSError as error:
202
+ if attempt < options.max_attempts and is_retryable(None, idempotent):
203
+ wait = retry_wait(attempt=attempt, status=None, retry_after=None, rate_limit_reset=None, now=self._now(), options=options, random=self._random)
204
+ if wait is not None:
205
+ self._sleep(wait)
206
+ attempt += 1
207
+ continue
208
+ raise ConnectionError("The request did not get an answer.") from error
209
+
210
+ if 300 <= response.status < 400:
211
+ raise RedirectRefusedError(response.status)
212
+ rate_limit = _rate_limit(response)
213
+ if rate_limit and self._on_rate_limit:
214
+ self._on_rate_limit(rate_limit)
215
+ if 200 <= response.status < 300:
216
+ if response.status == 204 or not response.body:
217
+ return None
218
+ return json.loads(response.body)
219
+
220
+ if response.status == 401 and refreshable is not None and not refreshed:
221
+ refreshed = True
222
+ if refreshable.on_unauthorized(token):
223
+ continue
224
+
225
+ retry_after = parse_retry_after(response.header("Retry-After"), self._now())
226
+ error = self._error(response, rate_limit, retry_after)
227
+ if attempt < options.max_attempts and is_retryable(response.status, idempotent):
228
+ wait = retry_wait(
229
+ attempt=attempt,
230
+ status=response.status,
231
+ retry_after=retry_after,
232
+ rate_limit_reset=rate_limit.reset if rate_limit else None,
233
+ now=self._now(),
234
+ options=options,
235
+ random=self._random,
236
+ )
237
+ if wait is not None:
238
+ self._sleep(wait)
239
+ attempt += 1
240
+ continue
241
+ raise error
242
+
243
+ @staticmethod
244
+ def _error(response: HttpResponse, rate_limit: RateLimitInfo | None, retry_after: float | None) -> TechnicallyFitError:
245
+ try:
246
+ parsed = json.loads(response.body or b"null")
247
+ except ValueError:
248
+ parsed = None
249
+ body = parsed.get("error") if isinstance(parsed, dict) and isinstance(parsed.get("error"), dict) else {}
250
+ details = body.get("details") if isinstance(body.get("details"), dict) else {}
251
+ detail_retry = details.get("retry_after_seconds")
252
+ return error_for(
253
+ code=body.get("code") if isinstance(body.get("code"), str) else f"http_{response.status}",
254
+ message=body.get("message") if isinstance(body.get("message"), str) else f"The API answered with status {response.status}.",
255
+ status=response.status,
256
+ request_id=body.get("request_id") if isinstance(body.get("request_id"), str) else response.header("X-Request-ID"),
257
+ details=details,
258
+ rate_limit=rate_limit,
259
+ retry_after_seconds=retry_after if retry_after is not None else (detail_retry if isinstance(detail_retry, (int, float)) else None),
260
+ )