mgmradar 0.36.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 (221) hide show
  1. mgmradar/__init__.py +8 -0
  2. mgmradar/access/__init__.py +1 -0
  3. mgmradar/access/auth.py +189 -0
  4. mgmradar/access/cache.py +179 -0
  5. mgmradar/access/key_issuance.py +230 -0
  6. mgmradar/access/ratelimit.py +120 -0
  7. mgmradar/alerts/__init__.py +23 -0
  8. mgmradar/alerts/evaluate.py +159 -0
  9. mgmradar/alerts/models.py +284 -0
  10. mgmradar/alerts/service.py +1254 -0
  11. mgmradar/alerts/signing.py +160 -0
  12. mgmradar/alerts/store.py +1194 -0
  13. mgmradar/alerts/validation.py +276 -0
  14. mgmradar/alerts/webhook.py +163 -0
  15. mgmradar/alerts/worker.py +157 -0
  16. mgmradar/api/__init__.py +1 -0
  17. mgmradar/api/alert_routes.py +608 -0
  18. mgmradar/api/app.py +315 -0
  19. mgmradar/api/billing_routes.py +319 -0
  20. mgmradar/api/deps.py +408 -0
  21. mgmradar/api/email_routes.py +157 -0
  22. mgmradar/api/errors.py +156 -0
  23. mgmradar/api/idempotency.py +163 -0
  24. mgmradar/api/llms.py +248 -0
  25. mgmradar/api/middleware.py +259 -0
  26. mgmradar/api/ops_routes.py +202 -0
  27. mgmradar/api/routes.py +2423 -0
  28. mgmradar/api/schemas.py +539 -0
  29. mgmradar/api/services.py +606 -0
  30. mgmradar/archive/__init__.py +1 -0
  31. mgmradar/archive/exports.py +591 -0
  32. mgmradar/archive/listing.py +149 -0
  33. mgmradar/archive/series.py +107 -0
  34. mgmradar/archive/signing.py +40 -0
  35. mgmradar/billing/__init__.py +247 -0
  36. mgmradar/billing/apply.py +189 -0
  37. mgmradar/billing/catalog.py +296 -0
  38. mgmradar/billing/checkout.py +144 -0
  39. mgmradar/billing/entitlements.py +227 -0
  40. mgmradar/billing/errors.py +36 -0
  41. mgmradar/billing/events.py +152 -0
  42. mgmradar/billing/health.py +147 -0
  43. mgmradar/billing/polar.py +831 -0
  44. mgmradar/billing/reconcile.py +679 -0
  45. mgmradar/billing/webhooks.py +406 -0
  46. mgmradar/billing/welcome.py +113 -0
  47. mgmradar/channels/__init__.py +25 -0
  48. mgmradar/channels/errors.py +32 -0
  49. mgmradar/channels/markdown.py +129 -0
  50. mgmradar/channels/reports.py +515 -0
  51. mgmradar/channels/taxonomy.py +115 -0
  52. mgmradar/channels/weeks.py +53 -0
  53. mgmradar/cli.py +1286 -0
  54. mgmradar/config.py +841 -0
  55. mgmradar/email/__init__.py +1 -0
  56. mgmradar/email/address.py +14 -0
  57. mgmradar/email/console.py +43 -0
  58. mgmradar/email/provider.py +40 -0
  59. mgmradar/email/render.py +50 -0
  60. mgmradar/email/resend.py +164 -0
  61. mgmradar/email/service.py +274 -0
  62. mgmradar/email/templates/cancellation.html +20 -0
  63. mgmradar/email/templates/cancellation.subject.txt +1 -0
  64. mgmradar/email/templates/cancellation.txt +14 -0
  65. mgmradar/email/templates/payment_failed.html +19 -0
  66. mgmradar/email/templates/payment_failed.subject.txt +1 -0
  67. mgmradar/email/templates/payment_failed.txt +15 -0
  68. mgmradar/email/templates/portal_login.html +14 -0
  69. mgmradar/email/templates/portal_login.subject.txt +1 -0
  70. mgmradar/email/templates/portal_login.txt +6 -0
  71. mgmradar/email/templates/quota_warning_100.html +16 -0
  72. mgmradar/email/templates/quota_warning_100.subject.txt +1 -0
  73. mgmradar/email/templates/quota_warning_100.txt +8 -0
  74. mgmradar/email/templates/quota_warning_80.html +21 -0
  75. mgmradar/email/templates/quota_warning_80.subject.txt +1 -0
  76. mgmradar/email/templates/quota_warning_80.txt +15 -0
  77. mgmradar/email/templates/signup_duplicate.html +15 -0
  78. mgmradar/email/templates/signup_duplicate.subject.txt +1 -0
  79. mgmradar/email/templates/signup_duplicate.txt +15 -0
  80. mgmradar/email/templates/signup_verification.html +14 -0
  81. mgmradar/email/templates/signup_verification.subject.txt +1 -0
  82. mgmradar/email/templates/signup_verification.txt +9 -0
  83. mgmradar/email/templates/test.html +11 -0
  84. mgmradar/email/templates/test.subject.txt +1 -0
  85. mgmradar/email/templates/test.txt +7 -0
  86. mgmradar/email/templates/welcome.html +16 -0
  87. mgmradar/email/templates/welcome.subject.txt +1 -0
  88. mgmradar/email/templates/welcome.txt +13 -0
  89. mgmradar/errors.py +169 -0
  90. mgmradar/ingest/__init__.py +1 -0
  91. mgmradar/ingest/lock.py +77 -0
  92. mgmradar/ingest/pipeline.py +419 -0
  93. mgmradar/ingest/poller.py +97 -0
  94. mgmradar/ingest/scan.py +71 -0
  95. mgmradar/ingest/source.py +175 -0
  96. mgmradar/internal.py +58 -0
  97. mgmradar/mcp/__init__.py +21 -0
  98. mgmradar/mcp/activity.py +526 -0
  99. mgmradar/mcp/auth.py +655 -0
  100. mgmradar/mcp/budget.py +114 -0
  101. mgmradar/mcp/client.py +205 -0
  102. mgmradar/mcp/constants.py +31 -0
  103. mgmradar/mcp/credentials.py +111 -0
  104. mgmradar/mcp/errors.py +218 -0
  105. mgmradar/mcp/freshness.py +53 -0
  106. mgmradar/mcp/http.py +238 -0
  107. mgmradar/mcp/interfaces.py +105 -0
  108. mgmradar/mcp/locations.py +115 -0
  109. mgmradar/mcp/registry.py +424 -0
  110. mgmradar/mcp/resolvers.py +86 -0
  111. mgmradar/mcp/results.py +185 -0
  112. mgmradar/mcp/server.py +169 -0
  113. mgmradar/mcp/stdio.py +174 -0
  114. mgmradar/mcp/tools.py +750 -0
  115. mgmradar/notifications/__init__.py +5 -0
  116. mgmradar/notifications/policy.py +83 -0
  117. mgmradar/notifications/service.py +713 -0
  118. mgmradar/notifications/unsubscribe.py +73 -0
  119. mgmradar/nowcast/__init__.py +7 -0
  120. mgmradar/nowcast/advect.py +100 -0
  121. mgmradar/nowcast/archive.py +92 -0
  122. mgmradar/nowcast/cases.py +289 -0
  123. mgmradar/nowcast/fields.py +93 -0
  124. mgmradar/nowcast/metrics.py +163 -0
  125. mgmradar/nowcast/motion.py +317 -0
  126. mgmradar/nowcast/regimes.py +67 -0
  127. mgmradar/nowcast/reporting.py +724 -0
  128. mgmradar/nowcast/runner.py +423 -0
  129. mgmradar/nowcast/stats.py +195 -0
  130. mgmradar/nowcast/verify.py +201 -0
  131. mgmradar/oauth/__init__.py +1 -0
  132. mgmradar/oauth/assertion.py +329 -0
  133. mgmradar/oauth/authorize.py +277 -0
  134. mgmradar/oauth/client_auth.py +222 -0
  135. mgmradar/oauth/client_secrets.py +42 -0
  136. mgmradar/oauth/codes.py +183 -0
  137. mgmradar/oauth/consent.py +499 -0
  138. mgmradar/oauth/constants.py +55 -0
  139. mgmradar/oauth/digests.py +18 -0
  140. mgmradar/oauth/metadata.py +138 -0
  141. mgmradar/oauth/metrics.py +93 -0
  142. mgmradar/oauth/redirects.py +28 -0
  143. mgmradar/oauth/registration.py +358 -0
  144. mgmradar/oauth/retention.py +75 -0
  145. mgmradar/oauth/revocation.py +153 -0
  146. mgmradar/oauth/tokens.py +357 -0
  147. mgmradar/oauth/verification.py +187 -0
  148. mgmradar/ops/__init__.py +1 -0
  149. mgmradar/ops/admin.py +812 -0
  150. mgmradar/ops/admin_routes.py +612 -0
  151. mgmradar/ops/alerts.py +119 -0
  152. mgmradar/ops/customers.py +685 -0
  153. mgmradar/ops/dashboard.py +1585 -0
  154. mgmradar/ops/guard.py +111 -0
  155. mgmradar/ops/health.py +57 -0
  156. mgmradar/ops/logging.py +98 -0
  157. mgmradar/ops/metrics.py +117 -0
  158. mgmradar/ops/metrics_server.py +59 -0
  159. mgmradar/ops/oauth.py +97 -0
  160. mgmradar/ops/pages.py +1002 -0
  161. mgmradar/ops/quarantine.py +38 -0
  162. mgmradar/ops/redaction.py +62 -0
  163. mgmradar/ops/status.py +86 -0
  164. mgmradar/places/__init__.py +58 -0
  165. mgmradar/places/data/tr_localities.json +1 -0
  166. mgmradar/places/data/tr_localities.manifest.json +33 -0
  167. mgmradar/places/data/tr_places.json +16897 -0
  168. mgmradar/places/data/tr_places.manifest.json +18 -0
  169. mgmradar/places/index.py +280 -0
  170. mgmradar/places/localities.py +262 -0
  171. mgmradar/places/models.py +69 -0
  172. mgmradar/places/normalize.py +59 -0
  173. mgmradar/places/resolve.py +457 -0
  174. mgmradar/plans.py +259 -0
  175. mgmradar/portal/__init__.py +1 -0
  176. mgmradar/portal/account.py +672 -0
  177. mgmradar/portal/cookies.py +71 -0
  178. mgmradar/portal/guard.py +198 -0
  179. mgmradar/portal/middleware.py +71 -0
  180. mgmradar/portal/pages.py +1579 -0
  181. mgmradar/portal/return_path.py +149 -0
  182. mgmradar/portal/routes.py +450 -0
  183. mgmradar/portal/service.py +306 -0
  184. mgmradar/portal/view.py +492 -0
  185. mgmradar/process/__init__.py +1 -0
  186. mgmradar/process/artifacts.py +54 -0
  187. mgmradar/process/calibration.py +315 -0
  188. mgmradar/process/classify.py +155 -0
  189. mgmradar/process/decode.py +47 -0
  190. mgmradar/process/legend.py +136 -0
  191. mgmradar/process/pipeline.py +405 -0
  192. mgmradar/process/rain.py +32 -0
  193. mgmradar/process/reader.py +104 -0
  194. mgmradar/process/render.py +212 -0
  195. mgmradar/process/route.py +855 -0
  196. mgmradar/process/sample.py +74 -0
  197. mgmradar/process/summary.py +91 -0
  198. mgmradar/process/validate.py +54 -0
  199. mgmradar/signup/__init__.py +1 -0
  200. mgmradar/signup/cookies.py +71 -0
  201. mgmradar/signup/pages.py +438 -0
  202. mgmradar/signup/routes.py +465 -0
  203. mgmradar/signup/service.py +578 -0
  204. mgmradar/store/__init__.py +1 -0
  205. mgmradar/store/db.py +5244 -0
  206. mgmradar/store/keys.py +47 -0
  207. mgmradar/store/models.py +987 -0
  208. mgmradar/store/objects.py +258 -0
  209. mgmradar/timeutil.py +112 -0
  210. mgmradar/web/__init__.py +11 -0
  211. mgmradar/web/components.py +400 -0
  212. mgmradar/web/html.py +37 -0
  213. mgmradar/web/layout.py +231 -0
  214. mgmradar/web/links.py +110 -0
  215. mgmradar/web/messages.py +117 -0
  216. mgmradar/web/panels.py +38 -0
  217. mgmradar/web/theme.py +319 -0
  218. mgmradar-0.36.0.dist-info/METADATA +258 -0
  219. mgmradar-0.36.0.dist-info/RECORD +221 -0
  220. mgmradar-0.36.0.dist-info/WHEEL +4 -0
  221. mgmradar-0.36.0.dist-info/entry_points.txt +2 -0
mgmradar/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """MGM Radar: calibrated MGM radar composite API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.36.0"
6
+
7
+ CALIBRATION_VERSION = "mgm-eq-1+legend-1"
8
+ PROCESSING_VERSION = "classify-1+zr-mp-1"
@@ -0,0 +1 @@
1
+ """Access control, plans, rate limiting, and metering."""
@@ -0,0 +1,189 @@
1
+ """Credential validation for first-party API keys.
2
+
3
+ Every unusable credential — missing, unknown, revoked, expired, or belonging to
4
+ a subscription that does not grant access — fails with one uniform ``AuthError``
5
+ so the response is not an oracle for key state.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ipaddress
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass
13
+ from datetime import datetime
14
+ from typing import Final, Literal
15
+
16
+ from mgmradar.access.cache import CredentialCache, LastUsedTracker
17
+ from mgmradar.billing.entitlements import subscription_grants_access
18
+ from mgmradar.errors import AuthError, ForbiddenError
19
+ from mgmradar.ops.metrics import MetricsRegistry
20
+ from mgmradar.plans import (
21
+ Plan,
22
+ PlansConfig,
23
+ hash_secret,
24
+ is_well_formed_secret,
25
+ key_mode,
26
+ require_plan,
27
+ )
28
+ from mgmradar.store.db import ApiKeyStore, CustomerAccessStore, ResolvedCredential
29
+ from mgmradar.timeutil import try_parse_time, utcnow
30
+
31
+ CREDENTIAL_TYPE_API_KEY: Final = "api_key"
32
+ CREDENTIAL_TYPE_OAUTH: Final = "oauth"
33
+
34
+ CredentialType = Literal["api_key", "oauth"]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class KeyContext:
39
+ key_id: str
40
+ subscription_id: str
41
+ customer_id: str
42
+ plan: Plan
43
+ subscription_status: str
44
+ ip: str | None
45
+ key_prefix: str = ""
46
+ credential_type: CredentialType = CREDENTIAL_TYPE_API_KEY
47
+ credential_id: str | None = None
48
+
49
+
50
+ def client_ip(*, forwarded_for: str | None, peer: str | None, trust_forwarded: bool) -> str | None:
51
+ if trust_forwarded and forwarded_for:
52
+ first = forwarded_for.split(",", 1)[0].strip()
53
+ if first:
54
+ return first
55
+ return peer
56
+
57
+
58
+ def anonymous_identity(ip: str | None) -> str:
59
+ """Return the rate-limit bucket identity for an anonymous caller.
60
+
61
+ IPv4 callers share nothing. IPv6 callers are grouped by ``/64`` because a
62
+ single client commonly controls the whole prefix, and per-address buckets
63
+ would be trivial to rotate around. Callers without a resolvable address
64
+ share the ``unknown`` bucket.
65
+ """
66
+ if not ip:
67
+ return "unknown"
68
+ try:
69
+ address = ipaddress.ip_address(ip)
70
+ except ValueError:
71
+ return "unknown"
72
+ if address.version == 6:
73
+ mapped = address.ipv4_mapped
74
+ if mapped is not None:
75
+ return str(mapped)
76
+ return str(ipaddress.ip_network(f"{address}/64", strict=False))
77
+ return str(address)
78
+
79
+
80
+ class Authenticator:
81
+ """Resolve a presented secret to a key context, gating on account state."""
82
+
83
+ def __init__(
84
+ self,
85
+ plans: PlansConfig,
86
+ api_keys: ApiKeyStore,
87
+ access: CustomerAccessStore,
88
+ *,
89
+ environment: str,
90
+ cache: CredentialCache | None = None,
91
+ metrics: MetricsRegistry | None = None,
92
+ tracker: LastUsedTracker | None = None,
93
+ clock: Callable[[], datetime] = utcnow,
94
+ ) -> None:
95
+ self.plans = plans
96
+ self._environment = environment
97
+ self.api_keys = api_keys
98
+ self.access = access
99
+ self._cache = cache
100
+ self._metrics = metrics
101
+ self._tracker = tracker
102
+ self._clock = clock
103
+
104
+ def authenticate(self, *, direct_key: str | None, ip: str | None) -> KeyContext:
105
+ if not direct_key:
106
+ raise AuthError()
107
+ # Shape validation happens before hashing, so malformed input never
108
+ # reaches the credential store.
109
+ if not is_well_formed_secret(direct_key):
110
+ self._record("rejected", "malformed")
111
+ raise AuthError()
112
+ # A staging database can outlive the deploy that promotes the host to
113
+ # production. Enforce the mode tag here, not only when a key is issued,
114
+ # so a test key cannot survive that cutover.
115
+ if self._environment == "production" and key_mode(direct_key) == "test":
116
+ self._record("rejected", "test_mode")
117
+ raise AuthError(security_reason="api_key_test_mode_in_production")
118
+
119
+ digest = hash_secret(direct_key)
120
+ cache_label = "disabled"
121
+ credential: ResolvedCredential | None
122
+ if self._cache is not None and self._cache.enabled:
123
+ hit, credential = self._cache.get(digest)
124
+ if hit:
125
+ cache_label = "hit"
126
+ else:
127
+ cache_label = "miss"
128
+ credential = self.api_keys.resolve(digest)
129
+ self._cache.set(digest, credential)
130
+ else:
131
+ credential = self.api_keys.resolve(digest)
132
+
133
+ now = self._clock()
134
+ if credential is None:
135
+ self._record("rejected", cache_label)
136
+ raise AuthError()
137
+ rejection = self._rejection(credential, now)
138
+ if rejection is not None:
139
+ self._record("rejected", cache_label)
140
+ if rejection == "revoked":
141
+ # The public contract stays the generic 401; the internal
142
+ # metadata lets the access dependency record the security event.
143
+ raise AuthError(
144
+ security_reason="api_key_revoked",
145
+ key_id=credential.key_id,
146
+ subscription_id=credential.subscription.id,
147
+ )
148
+ raise AuthError()
149
+ # The activation gate runs before any metering so a disabled customer
150
+ # is refused without consuming usage or quota. A missing access row
151
+ # means active.
152
+ if not self.access.is_active(credential.subscription.customer_id):
153
+ raise ForbiddenError(
154
+ "customer_disabled",
155
+ "This customer account is disabled.",
156
+ )
157
+
158
+ # The credential is valid; the blocklist check happens outside this
159
+ # layer, so an unknown plan is a distinct 403 rather than a 401.
160
+ plan = require_plan(self.plans, credential.subscription.plan_id)
161
+ self._record("ok", cache_label)
162
+ if self._tracker is not None:
163
+ self._tracker.record(credential.key_id, now)
164
+ return KeyContext(
165
+ key_id=credential.key_id,
166
+ subscription_id=credential.subscription.id,
167
+ customer_id=credential.subscription.customer_id,
168
+ plan=plan,
169
+ subscription_status=credential.subscription.status,
170
+ ip=ip,
171
+ key_prefix=credential.key_prefix,
172
+ credential_type=CREDENTIAL_TYPE_API_KEY,
173
+ credential_id=credential.key_id,
174
+ )
175
+
176
+ @staticmethod
177
+ def _rejection(credential: ResolvedCredential, now: datetime) -> str | None:
178
+ if credential.key_status != "active" or credential.revoked_at is not None:
179
+ return "revoked"
180
+ expires_at = try_parse_time(credential.expires_at)
181
+ if expires_at is not None and expires_at <= now:
182
+ return "expired"
183
+ if not subscription_grants_access(credential.subscription, now=now):
184
+ return "subscription_gated"
185
+ return None
186
+
187
+ def _record(self, outcome: str, cache: str) -> None:
188
+ if self._metrics is not None:
189
+ self._metrics.inc("mgmradar_auth_total", {"outcome": outcome, "cache": cache})
@@ -0,0 +1,179 @@
1
+ """Per-process credential cache and throttled last-used tracking.
2
+
3
+ The cache exists so a credential lookup costs one indexed read per miss and
4
+ zero per hit. It is deliberately process-local: invalidation is immediate in the
5
+ writing process and bounded by the TTL everywhere else.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ import time
12
+ from collections import OrderedDict
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass
15
+ from datetime import datetime
16
+
17
+ from mgmradar.store.db import ResolvedCredential
18
+ from mgmradar.timeutil import utcnow
19
+
20
+ DEFAULT_MAX_ENTRIES = 4096
21
+ LAST_USED_WRITE_INTERVAL_SECONDS = 300.0
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class _Entry:
26
+ expires_at: float
27
+ credential: ResolvedCredential | None
28
+
29
+
30
+ class CredentialCache:
31
+ """Bounded LRU cache of resolved credentials with positive and negative entries.
32
+
33
+ A ``None`` value is a negative entry: the digest was unknown. It shares the
34
+ lifetime of a positive entry so a key-guessing client cannot force a read on
35
+ every request. A TTL of zero disables the cache entirely.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ ttl_seconds: int,
41
+ *,
42
+ max_entries: int = DEFAULT_MAX_ENTRIES,
43
+ clock: Callable[[], float] = time.monotonic,
44
+ ) -> None:
45
+ self._ttl = max(0, int(ttl_seconds))
46
+ self._max_entries = max(1, max_entries)
47
+ self._clock = clock
48
+ self._entries: OrderedDict[str, _Entry] = OrderedDict()
49
+ self._by_subscription: dict[str, set[str]] = {}
50
+ self._by_customer: dict[str, set[str]] = {}
51
+ self._lock = threading.Lock()
52
+
53
+ @property
54
+ def ttl_seconds(self) -> int:
55
+ return self._ttl
56
+
57
+ @property
58
+ def enabled(self) -> bool:
59
+ return self._ttl > 0
60
+
61
+ def __len__(self) -> int:
62
+ with self._lock:
63
+ return len(self._entries)
64
+
65
+ def get(self, digest: str) -> tuple[bool, ResolvedCredential | None]:
66
+ """Return ``(hit, credential)``. A negative hit returns ``None``."""
67
+ if not self.enabled:
68
+ return (False, None)
69
+ now = self._clock()
70
+ with self._lock:
71
+ entry = self._entries.get(digest)
72
+ if entry is None:
73
+ return (False, None)
74
+ if entry.expires_at <= now:
75
+ self._remove(digest)
76
+ return (False, None)
77
+ self._entries.move_to_end(digest)
78
+ return (True, entry.credential)
79
+
80
+ def set(self, digest: str, credential: ResolvedCredential | None) -> None:
81
+ if not self.enabled:
82
+ return
83
+ with self._lock:
84
+ previous = self._entries.pop(digest, None)
85
+ if previous is not None:
86
+ self._unindex(digest, previous)
87
+ entry = _Entry(expires_at=self._clock() + self._ttl, credential=credential)
88
+ self._entries[digest] = entry
89
+ self._entries.move_to_end(digest)
90
+ if credential is not None:
91
+ self._by_subscription.setdefault(credential.subscription.id, set()).add(digest)
92
+ self._by_customer.setdefault(credential.subscription.customer_id, set()).add(digest)
93
+ while len(self._entries) > self._max_entries:
94
+ evicted_digest, evicted = self._entries.popitem(last=False)
95
+ self._unindex(evicted_digest, evicted)
96
+
97
+ def invalidate(self, digest: str) -> None:
98
+ with self._lock:
99
+ self._remove(digest)
100
+
101
+ def invalidate_subscription(self, subscription_id: str) -> None:
102
+ with self._lock:
103
+ for digest in list(self._by_subscription.get(subscription_id, ())):
104
+ self._remove(digest)
105
+
106
+ def invalidate_customer(self, customer_id: str) -> None:
107
+ with self._lock:
108
+ for digest in list(self._by_customer.get(customer_id, ())):
109
+ self._remove(digest)
110
+
111
+ def clear(self) -> None:
112
+ with self._lock:
113
+ self._entries.clear()
114
+ self._by_subscription.clear()
115
+ self._by_customer.clear()
116
+
117
+ # Callers hold the lock.
118
+ def _remove(self, digest: str) -> None:
119
+ entry = self._entries.pop(digest, None)
120
+ if entry is not None:
121
+ self._unindex(digest, entry)
122
+
123
+ def _unindex(self, digest: str, entry: _Entry) -> None:
124
+ if entry.credential is None:
125
+ return
126
+ subscription = entry.credential.subscription
127
+ for index, key in (
128
+ (self._by_subscription, subscription.id),
129
+ (self._by_customer, subscription.customer_id),
130
+ ):
131
+ digests = index.get(key)
132
+ if digests is None:
133
+ continue
134
+ digests.discard(digest)
135
+ if not digests:
136
+ index.pop(key, None)
137
+
138
+
139
+ @dataclass
140
+ class _Use:
141
+ used_at: datetime
142
+
143
+
144
+ class LastUsedTracker:
145
+ """Remember key use in memory and flush it at most once per key per interval.
146
+
147
+ The request path only calls :meth:`record`; no database write happens there.
148
+ """
149
+
150
+ def __init__(
151
+ self,
152
+ *,
153
+ min_interval_seconds: float = LAST_USED_WRITE_INTERVAL_SECONDS,
154
+ clock: Callable[[], float] = time.monotonic,
155
+ ) -> None:
156
+ self._interval = min_interval_seconds
157
+ self._clock = clock
158
+ self._pending: dict[str, _Use] = {}
159
+ self._flushed_at: dict[str, float] = {}
160
+ self._lock = threading.Lock()
161
+
162
+ def record(self, key_id: str, used_at: datetime | None = None) -> None:
163
+ stamp = used_at or utcnow()
164
+ with self._lock:
165
+ self._pending[key_id] = _Use(used_at=stamp)
166
+
167
+ def flush(self, *, force: bool = False) -> list[tuple[str, datetime]]:
168
+ """Return ``(key_id, latest_used_at)`` for keys whose window has elapsed."""
169
+ now = self._clock()
170
+ flushed: list[tuple[str, datetime]] = []
171
+ with self._lock:
172
+ for key_id in list(self._pending):
173
+ last = self._flushed_at.get(key_id)
174
+ if not force and last is not None and now - last < self._interval:
175
+ continue
176
+ use = self._pending.pop(key_id)
177
+ self._flushed_at[key_id] = now
178
+ flushed.append((key_id, use.used_at))
179
+ return flushed
@@ -0,0 +1,230 @@
1
+ """Create, rotate, and audit API keys for every portal surface.
2
+
3
+ The plaintext key exists only in the returned :class:`IssuedKey` and the
4
+ show-once response that renders it. It is never written to the database, an
5
+ audit row, an email, or a log.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import socket
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass
13
+ from datetime import datetime
14
+ from uuid import uuid4
15
+
16
+ from sqlalchemy.orm import Session
17
+
18
+ from mgmradar.billing.entitlements import subscription_grants_access
19
+ from mgmradar.config import Settings
20
+ from mgmradar.plans import generate_secret, hash_secret, key_mode
21
+ from mgmradar.store.db import (
22
+ ApiKeyStore,
23
+ KeyNotLiveError,
24
+ LiveKeyExistsError,
25
+ OpsAuditStore,
26
+ )
27
+ from mgmradar.store.models import ApiKey, Subscription
28
+ from mgmradar.timeutil import utcnow
29
+
30
+
31
+ class KeyIssuanceError(Exception):
32
+ """A refused issuance with a stable machine-readable code."""
33
+
34
+ def __init__(self, code: str) -> None:
35
+ super().__init__(code)
36
+ self.code = code
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class IssuedKey:
41
+ """A newly created or rotated key and its one-shot plaintext.
42
+
43
+ The plaintext is returned to the caller for the show-once response. It is
44
+ never written to the database, an audit row, an email, or a log.
45
+ """
46
+
47
+ key: ApiKey
48
+ plaintext: str
49
+
50
+ @property
51
+ def mode(self) -> str:
52
+ return key_mode(self.plaintext) or "unknown"
53
+
54
+
55
+ class KeyIssuer:
56
+ """One issuance path for operator pages, CLI, signup, and portal."""
57
+
58
+ def __init__(
59
+ self,
60
+ *,
61
+ settings: Settings,
62
+ api_keys: ApiKeyStore,
63
+ audit: OpsAuditStore,
64
+ host: str | None = None,
65
+ clock: Callable[[], datetime] = utcnow,
66
+ ) -> None:
67
+ self.settings = settings
68
+ self.api_keys = api_keys
69
+ self.audit = audit
70
+ self.host = host or socket.gethostname()
71
+ self._clock = clock
72
+
73
+ def create(
74
+ self,
75
+ *,
76
+ subscription: Subscription,
77
+ mode: str | None = None,
78
+ now: datetime | None = None,
79
+ session: Session | None = None,
80
+ ) -> IssuedKey:
81
+ """Insert one key row inside a caller-owned transaction."""
82
+ self._require_access(subscription, now=now)
83
+ secret = self._new_secret(mode)
84
+ key = self.api_keys.create(
85
+ key_id=f"key-{uuid4().hex}",
86
+ subscription_id=subscription.id,
87
+ digest=hash_secret(secret),
88
+ prefix=secret[:12],
89
+ last_four=secret[-4:],
90
+ now=now or self._clock(),
91
+ session=session,
92
+ )
93
+ return IssuedKey(key=key, plaintext=secret)
94
+
95
+ def issue(
96
+ self,
97
+ *,
98
+ actor: str,
99
+ subscription: Subscription,
100
+ mode: str | None = None,
101
+ ip: str | None = None,
102
+ ) -> IssuedKey:
103
+ """Create the subscription's first key. Refuses when one is live."""
104
+ self._require_access(subscription)
105
+ secret = self._new_secret(mode)
106
+ try:
107
+ key = self.api_keys.create(
108
+ key_id=f"key-{uuid4().hex}",
109
+ subscription_id=subscription.id,
110
+ digest=hash_secret(secret),
111
+ prefix=secret[:12],
112
+ last_four=secret[-4:],
113
+ now=self._clock(),
114
+ )
115
+ except LiveKeyExistsError as exc:
116
+ raise KeyIssuanceError("live_key_exists") from exc
117
+
118
+ self._audit(actor, "key_created", key, subscription.id, ip=ip, secret=secret)
119
+ return IssuedKey(key=key, plaintext=secret)
120
+
121
+ def rotate(
122
+ self,
123
+ *,
124
+ actor: str,
125
+ subscription: Subscription,
126
+ old_key: ApiKey,
127
+ mode: str | None = None,
128
+ ip: str | None = None,
129
+ ) -> IssuedKey:
130
+ """Replace one live key in a single transaction."""
131
+ self._require_access(subscription)
132
+ if old_key.subscription_id != subscription.id:
133
+ raise KeyIssuanceError("unknown_key")
134
+ if old_key.revoked_at is not None or old_key.status != "active":
135
+ raise KeyIssuanceError("key_not_live")
136
+
137
+ secret = self._new_secret(mode)
138
+ self.api_keys.invalidate_digest(old_key.digest)
139
+ try:
140
+ key = self.api_keys.rotate(
141
+ old_key_id=old_key.id,
142
+ new_key_id=f"key-{uuid4().hex}",
143
+ digest=hash_secret(secret),
144
+ prefix=secret[:12],
145
+ last_four=secret[-4:],
146
+ reason="rotated",
147
+ now=self._clock(),
148
+ )
149
+ except KeyNotLiveError as exc:
150
+ raise KeyIssuanceError("key_not_live") from exc
151
+ except LiveKeyExistsError as exc:
152
+ raise KeyIssuanceError("live_key_exists") from exc
153
+ self.api_keys.invalidate_digest(old_key.digest)
154
+
155
+ self._audit(
156
+ actor,
157
+ "key_rotated",
158
+ key,
159
+ subscription.id,
160
+ ip=ip,
161
+ secret=secret,
162
+ previous_key_id=old_key.id,
163
+ )
164
+ return IssuedKey(key=key, plaintext=secret)
165
+
166
+ def rotate_or_issue(
167
+ self,
168
+ *,
169
+ actor: str,
170
+ subscription: Subscription,
171
+ mode: str | None = None,
172
+ ip: str | None = None,
173
+ ) -> IssuedKey:
174
+ """Replace the live key, or create the first one when none exists."""
175
+ old_key = self.api_keys.live_for_subscription(subscription.id)
176
+ if old_key is None:
177
+ return self.issue(
178
+ actor=actor,
179
+ subscription=subscription,
180
+ mode=mode,
181
+ ip=ip,
182
+ )
183
+ return self.rotate(
184
+ actor=actor,
185
+ subscription=subscription,
186
+ old_key=old_key,
187
+ mode=mode,
188
+ ip=ip,
189
+ )
190
+
191
+ def _require_access(self, subscription: Subscription, *, now: datetime | None = None) -> None:
192
+ if not subscription_grants_access(subscription, now=now or self._clock()):
193
+ raise KeyIssuanceError("subscription_inactive")
194
+
195
+ def _new_secret(self, mode: str | None) -> str:
196
+ try:
197
+ return generate_secret(mode, environment=self.settings.environment)
198
+ except ValueError as exc:
199
+ if "production" in str(exc):
200
+ raise KeyIssuanceError("test_mode_forbidden") from exc
201
+ raise KeyIssuanceError("invalid_key_mode") from exc
202
+
203
+ def _audit(
204
+ self,
205
+ actor: str,
206
+ action: str,
207
+ key: ApiKey,
208
+ subscription_id: str,
209
+ *,
210
+ ip: str | None,
211
+ secret: str,
212
+ previous_key_id: str | None = None,
213
+ ) -> None:
214
+ detail: dict[str, object] = {"mode": key_mode(secret) or "unknown"}
215
+ if previous_key_id is not None:
216
+ detail["previous_key_id"] = previous_key_id
217
+ self.audit.record(
218
+ actor=actor,
219
+ action=action,
220
+ target_type="api_key",
221
+ target_id=key.id,
222
+ ip=ip,
223
+ subscription_id=subscription_id,
224
+ key_id=key.id,
225
+ detail=detail,
226
+ source="web",
227
+ host=self.host,
228
+ outcome="applied",
229
+ now=self._clock(),
230
+ )