keepup-admin 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.

Potentially problematic release.


This version of keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,338 @@
1
+ """The request mask a plugin route declares (task keepup-16).
2
+
3
+ A plugin route is data, and so is what it accepts: alongside ``path`` and
4
+ ``handler`` a route may declare ``params`` -- per parameter a type, whether it
5
+ is required, where it arrives from and what its value may be.
6
+
7
+ Before this, the source of truth was the handler's signature
8
+ (``registry.accepted_params``), with two consequences. Every argument with a
9
+ default was public, so a plugin author could not keep one internal -- the
10
+ decision was made for them by how they wrote the function. And nothing outside
11
+ the process could know what a route accepts, so a wrong request had to travel
12
+ all the way into the application to be refused.
13
+
14
+ This module is deliberately free of FastAPI, of the request object and of the
15
+ database: dictionaries in, dictionaries and a list of complaints out. Turning
16
+ the complaints into a refusal is ``registry.py``'s job. The point is that the
17
+ deciding part can be tested by calling it, rather than by starting a server --
18
+ the same reason ``mock/gpu_partitioning.py`` is shaped that way.
19
+
20
+ A route that declares no mask behaves exactly as it did before. That is not
21
+ caution, it is the condition of the change: some four hundred routes are
22
+ converted by the applications' own tasks, and a framework that changed the
23
+ default would have turned all of them into refusals at once.
24
+
25
+ See doc/keepup.md.
26
+ """
27
+
28
+ import inspect
29
+ import re
30
+ from typing import Any, Dict, List, Optional, Tuple
31
+
32
+ #: The field a route declares its mask under.
33
+ MASK_FIELD = "params"
34
+
35
+ #: Where a parameter arrives from. A path parameter is what the route matched
36
+ #: on, so it is always required and never optional.
37
+ IN_PATH = "path"
38
+ IN_QUERY = "query"
39
+ IN_ANY = "any"
40
+ SOURCES = (IN_PATH, IN_QUERY, IN_ANY)
41
+
42
+ #: What a declaration may say about one parameter.
43
+ DECLARATION_FIELDS = frozenset({
44
+ "type", "required", "in", "choices", "min", "max", "max_length", "pattern",
45
+ "description",
46
+ })
47
+
48
+ #: Spellings of a false flag. ``bool("false")`` is true, which is how a query
49
+ #: string turns "no" into "yes" -- every flag goes through here instead.
50
+ FALSE_SPELLINGS = frozenset({"", "0", "false", "no", "off"})
51
+
52
+ #: Supplied by the framework, never by the caller.
53
+ FRAMEWORK_SUPPLIED = frozenset({"current_user", "request"})
54
+
55
+
56
+ class MaskError(Exception):
57
+ """The declaration itself is wrong -- the plugin author's mistake.
58
+
59
+ Raised while registering a route, never while answering a request: a mask
60
+ naming a parameter the handler does not take is a typo, and finding it on a
61
+ request would mean hearing about it from a user.
62
+ """
63
+
64
+
65
+ def _as_bool(value: Any) -> bool:
66
+ if isinstance(value, bool):
67
+ return value
68
+ return str(value).strip().lower() not in FALSE_SPELLINGS
69
+
70
+
71
+ def _to_str(value: Any) -> str:
72
+ return value if isinstance(value, str) else str(value)
73
+
74
+
75
+ def _to_int(value: Any) -> int:
76
+ if isinstance(value, bool):
77
+ # A flag is not a number, however willing Python is to make it one.
78
+ raise ValueError("not an integer")
79
+ return int(str(value).strip())
80
+
81
+
82
+ def _to_float(value: Any) -> float:
83
+ if isinstance(value, bool):
84
+ raise ValueError("not a number")
85
+ return float(str(value).strip())
86
+
87
+
88
+ #: The types a mask may declare, and how each converts a string from the query.
89
+ TYPES = {
90
+ "str": _to_str,
91
+ "int": _to_int,
92
+ "float": _to_float,
93
+ "bool": _as_bool,
94
+ }
95
+
96
+ #: Types a numeric bound applies to.
97
+ NUMERIC = frozenset({"int", "float"})
98
+
99
+
100
+ class Parameter:
101
+ """One parameter of a mask: what it is and what it may be."""
102
+
103
+ def __init__(self, name: str, declaration: Dict[str, Any], path_names):
104
+ unknown = set(declaration) - DECLARATION_FIELDS
105
+ if unknown:
106
+ raise MaskError(
107
+ f"parameter {name}: unknown declaration fields: "
108
+ f"{', '.join(sorted(unknown))}")
109
+
110
+ self.name = name
111
+ self.type = declaration.get("type", "str")
112
+ if self.type not in TYPES:
113
+ raise MaskError(
114
+ f"parameter {name}: unknown type {self.type!r}; "
115
+ f"allowed: {', '.join(sorted(TYPES))}")
116
+
117
+ self.source = declaration.get("in", IN_PATH if name in path_names else IN_ANY)
118
+ if self.source not in SOURCES:
119
+ raise MaskError(
120
+ f"parameter {name}: unknown source {self.source!r}; "
121
+ f"allowed: {', '.join(SOURCES)}")
122
+
123
+ if name in path_names and self.source != IN_PATH:
124
+ raise MaskError(
125
+ f"parameter {name} stands in the route's path, so its source is "
126
+ f"{IN_PATH!r}, not the declared {self.source!r}")
127
+
128
+ # A path parameter is what the route matched on: it cannot be absent,
129
+ # and declaring it optional would describe a request that cannot exist.
130
+ self.required = True if self.source == IN_PATH else bool(declaration.get("required", False))
131
+
132
+ self.choices = declaration.get("choices")
133
+ self.min = declaration.get("min")
134
+ self.max = declaration.get("max")
135
+ self.max_length = declaration.get("max_length")
136
+ self.pattern = declaration.get("pattern")
137
+ self.description = declaration.get("description", "")
138
+
139
+ self._check_constraints()
140
+
141
+ def _check_constraints(self) -> None:
142
+ """A constraint that does not fit the declared type is a typo, not a rule."""
143
+ if self.choices is not None:
144
+ if not isinstance(self.choices, (list, tuple)) or not self.choices:
145
+ raise MaskError(f"parameter {self.name}: choices must be a non-empty list")
146
+ for value in self.choices:
147
+ try:
148
+ TYPES[self.type](value)
149
+ except (TypeError, ValueError):
150
+ raise MaskError(
151
+ f"parameter {self.name}: the choice {value!r} does not "
152
+ f"convert to the declared type {self.type}")
153
+
154
+ for bound in ("min", "max"):
155
+ if getattr(self, bound) is not None and self.type not in NUMERIC:
156
+ raise MaskError(
157
+ f"parameter {self.name}: {bound} applies to a number, "
158
+ f"and the declared type is {self.type}")
159
+ if self.min is not None and self.max is not None and self.min > self.max:
160
+ raise MaskError(f"parameter {self.name}: min is greater than max")
161
+
162
+ if self.max_length is not None:
163
+ if self.type != "str":
164
+ raise MaskError(
165
+ f"parameter {self.name}: max_length applies to a string, "
166
+ f"and the declared type is {self.type}")
167
+ if not isinstance(self.max_length, int) or self.max_length <= 0:
168
+ raise MaskError(
169
+ f"parameter {self.name}: max_length must be a positive integer")
170
+
171
+ if self.pattern is not None:
172
+ if self.type != "str":
173
+ raise MaskError(
174
+ f"parameter {self.name}: pattern applies to a string, "
175
+ f"and the declared type is {self.type}")
176
+ try:
177
+ self._compiled = re.compile(self.pattern)
178
+ except re.error as error:
179
+ raise MaskError(f"parameter {self.name}: unusable pattern: {error}")
180
+ else:
181
+ self._compiled = None
182
+
183
+ def admit(self, value: Any) -> Tuple[Any, Optional[str]]:
184
+ """Convert and check one value; answers the value or the complaint."""
185
+ try:
186
+ converted = TYPES[self.type](value)
187
+ except (TypeError, ValueError):
188
+ return None, f"{self.name}: expected {self.type}"
189
+
190
+ if self.choices is not None:
191
+ allowed = [TYPES[self.type](choice) for choice in self.choices]
192
+ if converted not in allowed:
193
+ return None, (f"{self.name}: must be one of "
194
+ f"{', '.join(str(a) for a in allowed)}")
195
+
196
+ if self.min is not None and converted < self.min:
197
+ return None, f"{self.name}: less than {self.min}"
198
+ if self.max is not None and converted > self.max:
199
+ return None, f"{self.name}: greater than {self.max}"
200
+ if self.max_length is not None and len(converted) > self.max_length:
201
+ return None, f"{self.name}: longer than {self.max_length} characters"
202
+ # Whole-string on purpose: a pattern that matches a substring is the
203
+ # classic way to declare a restriction and not get one.
204
+ if self._compiled is not None and not self._compiled.fullmatch(converted):
205
+ return None, f"{self.name}: does not match the pattern"
206
+
207
+ return converted, None
208
+
209
+ def describe(self) -> Dict[str, Any]:
210
+ """What a proxy needs to refuse this parameter before the application."""
211
+ described = {"type": self.type, "required": self.required, "in": self.source}
212
+ for field in ("choices", "min", "max", "max_length", "pattern", "description"):
213
+ value = getattr(self, field)
214
+ if value is not None and value != "":
215
+ described[field] = list(value) if field == "choices" else value
216
+ return described
217
+
218
+
219
+ class Mask:
220
+ """What one route accepts."""
221
+
222
+ def __init__(self, parameters: Dict[str, Parameter]):
223
+ self.parameters = parameters
224
+
225
+ def admit(self, params: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]:
226
+ """Check a request against the mask.
227
+
228
+ Every complaint is collected rather than the first one raised: a client
229
+ told one problem per request fixes its call as many times as it has
230
+ mistakes, and the list costs nothing.
231
+ """
232
+ complaints: List[str] = []
233
+
234
+ unknown = set(params) - set(self.parameters) - FRAMEWORK_SUPPLIED
235
+ for name in sorted(unknown):
236
+ complaints.append(f"{name}: the route does not take this parameter")
237
+
238
+ values: Dict[str, Any] = {}
239
+ for name, parameter in self.parameters.items():
240
+ if name not in params:
241
+ if parameter.required:
242
+ complaints.append(f"{name}: required parameter is missing")
243
+ continue
244
+ value, complaint = parameter.admit(params[name])
245
+ if complaint:
246
+ complaints.append(complaint)
247
+ else:
248
+ values[name] = value
249
+
250
+ return values, complaints
251
+
252
+ def describe(self) -> Dict[str, Any]:
253
+ return {name: parameter.describe() for name, parameter in self.parameters.items()}
254
+
255
+
256
+ def path_parameters(path: str) -> List[str]:
257
+ """The names standing in the route's own path."""
258
+ return re.findall(r"\{([^{}/]+)\}", path or "")
259
+
260
+
261
+ def parse(declaration: Optional[Dict[str, Any]], path: str = "") -> Optional[Mask]:
262
+ """Build a mask from a route's ``params``; ``None`` when it declares none."""
263
+ if declaration is None:
264
+ return None
265
+ if not isinstance(declaration, dict):
266
+ raise MaskError(f"the mask of route {path} must be a name-to-declaration mapping")
267
+
268
+ names = path_parameters(path)
269
+ parameters = {}
270
+ for name, item in declaration.items():
271
+ if not isinstance(item, dict):
272
+ raise MaskError(f"parameter {name}: the declaration must be a mapping")
273
+ parameters[name] = Parameter(name, item, names)
274
+
275
+ missing = [name for name in names if name not in parameters]
276
+ if missing:
277
+ raise MaskError(
278
+ f"the mask of route {path} does not declare the parameters of its "
279
+ f"own path: {', '.join(missing)}")
280
+ return Mask(parameters)
281
+
282
+
283
+ def check_signature(handler, mask: Optional[Mask]) -> None:
284
+ """Refuse a mask naming a parameter the handler does not take.
285
+
286
+ A handler declared with ``**kwargs`` is asking for everything and gets it,
287
+ as it already does without a mask; there is nothing to check against.
288
+ """
289
+ if mask is None:
290
+ return
291
+ try:
292
+ signature = inspect.signature(handler)
293
+ except (TypeError, ValueError):
294
+ # A callable that cannot be inspected is left alone, as elsewhere:
295
+ # refusing it would break a plugin over introspection.
296
+ return
297
+
298
+ parameters = list(signature.parameters.values())
299
+ if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters):
300
+ return
301
+
302
+ accepted = {p.name for p in parameters
303
+ if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
304
+ inspect.Parameter.KEYWORD_ONLY)}
305
+ unknown = set(mask.parameters) - accepted
306
+ if unknown:
307
+ raise MaskError(
308
+ f"the mask names parameters the handler does not take: "
309
+ f"{', '.join(sorted(unknown))}")
310
+
311
+
312
+ def describe_routes(routes) -> List[Dict[str, Any]]:
313
+ """The masks of every registered route, for a gateway or a proxy.
314
+
315
+ A route that declared no mask is listed as having declared none rather than
316
+ given an invented one: "we do not know" and "anything goes" are different
317
+ answers, and a proxy built on the second would let through what the first
318
+ only failed to describe.
319
+ """
320
+ described = []
321
+ for route in routes or []:
322
+ path = route.get("path", "")
323
+ try:
324
+ mask = parse(route.get(MASK_FIELD), path)
325
+ except MaskError:
326
+ # Registration refuses such a route, so this is only reachable for
327
+ # a route that never registered; say so rather than guess.
328
+ mask = None
329
+ declared = False
330
+ else:
331
+ declared = mask is not None
332
+ described.append({
333
+ "path": path,
334
+ "methods": list(route.get("methods", [])),
335
+ "declared": declared,
336
+ "params": mask.describe() if mask else {},
337
+ })
338
+ return described