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,376 @@
1
+ """How a declared route becomes an endpoint of the application.
2
+
3
+ A plugin's routes are data -- a path, a set of methods, a handler and a few
4
+ flags -- and this module is the single place where that data turns into
5
+ something FastAPI will call. The wrapper it builds signs the caller in, unpacks
6
+ the path and the query into the handler's arguments, parses a body when the
7
+ method carries one, and writes the call to the incoming request audit.
8
+
9
+ Single is the point. There used to be eight nearly identical wrappers here,
10
+ one per shape of route, and every change had to be made in all of them: the
11
+ request mask added a hundred and fifty lines by being added eight times, and
12
+ two of the eight had drifted apart from the rest without anybody noticing
13
+ (keepup-21). Every route of every plugin of every application is born here, so
14
+ what this module does once, it does to all of them.
15
+ """
16
+
17
+ import inspect
18
+ import logging
19
+
20
+ from fastapi import Depends, HTTPException, Request
21
+
22
+ from keepup.audit import IncomingRequestLogger, log_api_request
23
+ from keepup.auth.dependencies import get_panel_user
24
+ from keepup.auth.websocket import authenticate_websocket
25
+ from keepup.plugins import route_mask
26
+
27
+ #: What an application may import from this module. Everything else is
28
+ #: internal and may change without notice -- see doc/keepup.md.
29
+ __all__ = [
30
+ "accepted_params",
31
+ "raw_request_wrapper",
32
+ "register_plugin_routes",
33
+ ]
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ def raw_request_wrapper(handler):
39
+ """A route whose handler takes the request as it is and answers as it likes.
40
+
41
+ For surfaces with a wire format of their own -- the OpenAI-compatible gateway
42
+ answers errors in OpenAI's shape and streams server-sent events. The handler
43
+ authenticates the caller itself, and the body is not written to the incoming
44
+ request log: it carries users' prompts.
45
+ """
46
+ async def wrapper_raw(request: Request):
47
+ return await handler(request=request)
48
+
49
+ return wrapper_raw
50
+
51
+
52
+ def accepted_params(handler, params):
53
+ """The parameters this handler declares, refusing the ones it does not.
54
+
55
+ A plugin route is data, so the framework unpacks what arrived into keyword
56
+ arguments -- and an argument the handler never heard of used to raise
57
+ TypeError, which left the client with a 500 and the audit table with a row.
58
+ Sending `?nosuch=1` in a loop was a cheap way to fill the database and the
59
+ log at once, and on a route with `require_auth: False` anybody could.
60
+
61
+ A handler that takes **kwargs is asking for everything and gets it.
62
+
63
+ Args:
64
+ handler: the plugin's callable.
65
+ params: what arrived in the path and the query.
66
+
67
+ Returns:
68
+ The parameters to pass.
69
+
70
+ Raises:
71
+ HTTPException: 400, naming the parameters the route does not take.
72
+ """
73
+ try:
74
+ signature = inspect.signature(handler)
75
+ except (TypeError, ValueError):
76
+ # A callable that cannot be inspected (a builtin, a C extension) is
77
+ # left alone: refusing it would break a plugin over introspection.
78
+ return params
79
+
80
+ parameters = signature.parameters.values()
81
+ if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters):
82
+ return params
83
+
84
+ declared = {p.name for p in parameters
85
+ if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
86
+ inspect.Parameter.KEYWORD_ONLY)}
87
+ # Supplied by the framework, never by the caller: a client sending
88
+ # ?current_user=1 used to get a 500 out of the duplicate argument.
89
+ supplied = params.keys() - declared - {"current_user"}
90
+ if supplied:
91
+ raise HTTPException(
92
+ status_code=400,
93
+ detail=f"Unknown parameter(s): {', '.join(sorted(supplied))}")
94
+ return {name: value for name, value in params.items() if name != "current_user"}
95
+
96
+
97
+ def admit_params(handler, mask, params):
98
+ """What reaches the handler: the mask decides, or the signature still does.
99
+
100
+ A route that declared a mask is checked against it -- names, types,
101
+ required, allowed values -- and the values arrive converted. A route
102
+ without one keeps the previous behaviour exactly, which is the condition of
103
+ the change: the applications convert their routes by their own tasks, and a
104
+ framework that changed the default would have turned every route of every
105
+ application into a refusal at once. See doc/keepup.md.
106
+
107
+ Args:
108
+ handler: the plugin's callable.
109
+ mask: the route's parsed mask, or None.
110
+ params: what arrived in the path and the query.
111
+
112
+ Returns:
113
+ The parameters to pass.
114
+
115
+ Raises:
116
+ HTTPException: 400, naming everything the request got wrong.
117
+ """
118
+ if mask is None:
119
+ return accepted_params(handler, params)
120
+
121
+ values, complaints = mask.admit(params)
122
+ if complaints:
123
+ raise HTTPException(status_code=400, detail="; ".join(complaints))
124
+ return values
125
+
126
+
127
+ #: What the runtime does with a route, decided by the methods it declares.
128
+ #: A route is one of three shapes: a read, a write (which carries a body) and
129
+ #: a deletion.
130
+ KIND_READ = "read"
131
+ KIND_WRITE = "write"
132
+ KIND_DELETE = "delete"
133
+
134
+ #: The methods that carry a body. PUT and PATCH go the way POST goes.
135
+ WRITE_METHODS = ("POST", "PUT", "PATCH")
136
+
137
+
138
+ def route_kind(methods):
139
+ """The shape of a route, and the method name its calls are recorded under.
140
+
141
+ The order of the checks is the order the eight wrappers used to be written
142
+ in, and it is what decides a tie: a route declaring ["POST", "GET"] is a
143
+ read and is recorded as GET, not as the first method it named.
144
+
145
+ Args:
146
+ methods: the methods the route declares.
147
+
148
+ Returns:
149
+ A (kind, method name) pair, or (None, None) for a set of methods the
150
+ runtime has no wrapper for.
151
+ """
152
+ if "GET" in methods:
153
+ return KIND_READ, "GET"
154
+ if any(method in WRITE_METHODS for method in methods):
155
+ return KIND_WRITE, methods[0]
156
+ if "DELETE" in methods:
157
+ return KIND_DELETE, "DELETE"
158
+ return None, None
159
+
160
+
161
+ async def json_body(request: Request):
162
+ """The body of a write, parsed, or an empty one.
163
+
164
+ The content type decides, not the bytes: a handler written for a dictionary
165
+ would otherwise be handed a string the first time somebody posted a form.
166
+ A body that claims to be JSON and is not becomes empty rather than a
167
+ refusal -- the plugin is handed {} and decides for itself, because a
168
+ handler that needs a field says so by missing it.
169
+ """
170
+ if request.headers.get("content-type") != "application/json":
171
+ return {}
172
+ try:
173
+ return await request.json()
174
+ except Exception:
175
+ # Not a bare except, which used to be here: CancelledError does not
176
+ # inherit from Exception, and swallowing it turned a cancelled request
177
+ # into an empty body and a handler that ran on anyway.
178
+ return {}
179
+
180
+
181
+ def create_wrapper(handler, path, methods, require_auth: bool = True,
182
+ is_upload: bool = False, mask=None):
183
+ """Build the endpoint FastAPI will call for one declared route.
184
+
185
+ One implementation rather than one per shape. It used to be eight nearly
186
+ identical copies -- three shapes x a path parameter x authentication -- and
187
+ two of them had quietly drifted apart from the rest (keepup-21).
188
+
189
+ Two signatures remain, and only because FastAPI builds an endpoint out of
190
+ one: a route that is signed in has to declare the dependency, and a public
191
+ route must not.
192
+
193
+ Args:
194
+ handler: the plugin's callable.
195
+ path: the route's path as declared, parameters and all.
196
+ methods: the methods the route declares.
197
+ require_auth: whether the framework signs the caller in.
198
+ is_upload: whether the handler is handed the request instead of a body.
199
+ mask: the route's parsed mask, or None.
200
+
201
+ Returns:
202
+ An async endpoint to hand to app.add_api_route().
203
+ """
204
+ kind, method_name = route_kind(methods)
205
+ if kind is None:
206
+ logger.warning(f"No matching wrapper found for {path} with methods {methods}")
207
+
208
+ # It takes nothing on purpose. Written as (*args, **kwargs) it never
209
+ # answered 501 at all: FastAPI reads a signature to build the endpoint,
210
+ # so those two became required query parameters and the route answered
211
+ # 422 "args, kwargs: field required" (keepup-20).
212
+ async def fallback_wrapper():
213
+ raise HTTPException(status_code=501,
214
+ detail=f"Not implemented for methods {methods}")
215
+
216
+ return fallback_wrapper
217
+
218
+ has_path_params = any('{' in part and '}' in part for part in path.split('/'))
219
+
220
+ async def call(request: Request, current_user):
221
+ """One call of a plugin route, from the audit's first row to its last."""
222
+ request_data = {
223
+ 'user_id': current_user.get('id') if current_user else None,
224
+ 'username': current_user.get('username') if current_user else 'anonymous',
225
+ }
226
+ if has_path_params:
227
+ request_data['path_params'] = dict(request.path_params)
228
+ request_data['query_params'] = dict(request.query_params)
229
+ if kind == KIND_WRITE:
230
+ request_data['is_upload'] = is_upload
231
+
232
+ async with log_api_request(
233
+ method=method_name,
234
+ endpoint=path,
235
+ host='plugin_api',
236
+ request_data=request_data
237
+ ) as request_id:
238
+ try:
239
+ params = {}
240
+ # The query first and the path over it: a value taken from the
241
+ # address is what the route matched on, and a client that sends
242
+ # ?id=99 to /api/x/5 used to reach the handler with 99 while
243
+ # every log and every rule built on the path still said 5.
244
+ params.update(request.query_params)
245
+ params.update(request.path_params)
246
+ params = admit_params(handler, mask, params)
247
+
248
+ if current_user is not None:
249
+ params['current_user'] = current_user
250
+ if kind == KIND_WRITE:
251
+ # An upload is handed the request itself: reading a file
252
+ # into memory to pass it as a value is what such a route
253
+ # exists to avoid.
254
+ params['request'] = request if is_upload else await json_body(request)
255
+
256
+ response = await handler(**params)
257
+
258
+ await IncomingRequestLogger.end_request(
259
+ request_id=request_id,
260
+ http_status=200,
261
+ response_data=response if isinstance(response, dict) else {"data": response}
262
+ )
263
+
264
+ return response
265
+ except HTTPException as e:
266
+ await IncomingRequestLogger.end_request(
267
+ request_id=request_id,
268
+ http_status=e.status_code,
269
+ error_message=e.detail
270
+ )
271
+ raise
272
+ except Exception as e:
273
+ await IncomingRequestLogger.end_request(
274
+ request_id=request_id,
275
+ http_status=500,
276
+ error_message=str(e)
277
+ )
278
+ raise
279
+
280
+ if require_auth:
281
+ async def wrapper_signed_in(request: Request,
282
+ current_user: dict = Depends(get_panel_user)):
283
+ return await call(request, current_user)
284
+
285
+ return wrapper_signed_in
286
+
287
+ async def wrapper_public(request: Request):
288
+ return await call(request, None)
289
+
290
+ return wrapper_public
291
+
292
+
293
+ async def register_plugin_routes(app, manager):
294
+ """Register every plugin's API routes on the FastAPI application."""
295
+
296
+ routes = manager.get_all_api_routes()
297
+ logger.info(f"Found {len(routes)} plugin routes to register")
298
+
299
+ for route in routes:
300
+ handler = route['handler']
301
+ path = route['path']
302
+ methods = route['methods']
303
+ require_auth = route.get('require_auth', True)
304
+ is_upload = route.get('is_upload', False)
305
+
306
+ logger.info(
307
+ f"Registering route {path} - methods: {methods}, auth: {require_auth}, upload: {is_upload}")
308
+
309
+ try:
310
+ mask = route_mask.parse(route.get(route_mask.MASK_FIELD), path)
311
+ route_mask.check_signature(handler, mask)
312
+ except route_mask.MaskError as error:
313
+ # The same loudness as the raw_request check below: a mask naming a
314
+ # parameter the handler does not take is a typo, and finding it on
315
+ # a request would mean hearing about it from a user.
316
+ raise ValueError(f"{path}: {error}")
317
+
318
+ if route.get('raw_request'):
319
+ # A raw route authenticates inside the handler -- it is handed the
320
+ # Request and nothing else. Declaring require_auth on it therefore
321
+ # promises a check the framework does not make, and the start-up
322
+ # line used to print auth=True over an open route (keepup-12).
323
+ if route.get('require_auth') is True:
324
+ raise ValueError(
325
+ f"{path}: a raw_request route cannot also declare "
326
+ "require_auth -- the handler receives the Request and "
327
+ "authenticates itself. Drop one of the two.")
328
+ require_auth = False
329
+ wrapper = raw_request_wrapper(handler)
330
+ else:
331
+ wrapper = create_wrapper(handler, path, methods, require_auth, is_upload, mask)
332
+
333
+ app.add_api_route(
334
+ path,
335
+ wrapper,
336
+ methods=methods,
337
+ include_in_schema=route.get('include_in_schema', True)
338
+ )
339
+
340
+ logger.info(
341
+ f"Registered plugin route: {path} - {methods} (auth={require_auth}, upload={is_upload})")
342
+
343
+ websocket_routes = manager.get_all_websocket_routes()
344
+ logger.info(f"Found {len(websocket_routes)} WebSocket plugin routes to register")
345
+
346
+ for ws_route in websocket_routes:
347
+ path = ws_route['path']
348
+ handler = ws_route['handler']
349
+ # Off by default, unlike HTTP routes: sockets of agents and guests carry
350
+ # tokens of their own and would be refused by the panel's sign-in rule.
351
+ if ws_route.get('require_auth', False):
352
+ handler = signed_in_websocket(handler)
353
+ app.add_websocket_route(path, handler)
354
+ logger.info(f"Registered WebSocket plugin route: {path} "
355
+ f"(auth={bool(ws_route.get('require_auth', False))})")
356
+
357
+
358
+ def signed_in_websocket(handler):
359
+ """Wrap a socket handler so it runs only for a signed-in user, who is passed in.
360
+
361
+ Refusal closes the socket with 1008 before the handler sees it.
362
+ """
363
+ async def wrapper(websocket):
364
+ user = await authenticate_websocket(websocket)
365
+ if user is None:
366
+ return
367
+ await handler(websocket, current_user=user)
368
+
369
+ return wrapper
370
+
371
+
372
+ # --- Post-construct and the administrative surface ----------------------------
373
+ #
374
+ # post_construct runs after the server is up, for the self-checks that need a
375
+ # live HTTP server; the endpoints below are what an administrator sees of the
376
+ # runtime -- which plugins are declared, which are running, and why one is not.
keepup/roles.py ADDED
@@ -0,0 +1,17 @@
1
+ """The two roles the framework itself distinguishes.
2
+
3
+ Anything finer -- who may see which section, which permissions a group maps to
4
+ -- belongs to the application and to ``keepup.auth.permissions``. The framework
5
+ only needs to tell an administrator from an ordinary user, because that is the
6
+ distinction its own endpoints are guarded by.
7
+ """
8
+
9
+ #: What an application may import from this module. Everything else is
10
+ #: internal and may change without notice -- see doc/keepup.md.
11
+ __all__ = [
12
+ "ROLE_ADMIN",
13
+ "ROLE_CLIENT",
14
+ ]
15
+
16
+ ROLE_ADMIN = "ADMIN"
17
+ ROLE_CLIENT = "CLIENT"
keepup/scheduler.py ADDED
@@ -0,0 +1,93 @@
1
+ """One scheduler for the whole process.
2
+
3
+ Plugins register their own jobs against it rather than each starting a
4
+ scheduler of its own, which is what keeps the jobs visible in one place -- and
5
+ what lets an administrator see and trigger them. Running the same job in every
6
+ replica is prevented one level up, by the distributed lock around the job
7
+ itself, not here.
8
+ """
9
+
10
+ import asyncio
11
+ import logging
12
+ from datetime import datetime
13
+
14
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
15
+ from fastapi import Depends, HTTPException
16
+
17
+ from keepup.auth.dependencies import get_current_admin
18
+
19
+ #: What an application may import from this module. Everything else is
20
+ #: internal and may change without notice -- see doc/keepup.md.
21
+ __all__ = [
22
+ "init_scheduler",
23
+ ]
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ #: The process-wide scheduler, created by init_scheduler().
28
+ scheduler = None
29
+
30
+
31
+ def get_scheduler():
32
+ """Return the process-wide scheduler, or None before it is created."""
33
+ return scheduler
34
+
35
+
36
+ def init_scheduler():
37
+ """Create and configure the task scheduler."""
38
+ global scheduler
39
+
40
+ scheduler = AsyncIOScheduler()
41
+
42
+ logger.info("Global scheduler initialized - tasks will be registered by plugins")
43
+ return scheduler
44
+
45
+
46
+ def register_scheduler_routes(app):
47
+ """Register the scheduler endpoints on the application."""
48
+
49
+ @app.get("/api/admin/scheduler/jobs")
50
+ async def get_scheduler_jobs(admin: dict = Depends(get_current_admin)):
51
+ """Return the scheduler's jobs (administrators only)."""
52
+ if not scheduler:
53
+ return {"error": "Scheduler not initialized"}
54
+
55
+ jobs = []
56
+ for job in scheduler.get_jobs():
57
+ jobs.append({
58
+ "id": job.id,
59
+ "name": job.name,
60
+ "next_run_time": job.next_run_time,
61
+ "trigger": str(job.trigger)
62
+ })
63
+
64
+ return {"jobs": jobs}
65
+ @app.post("/api/admin/scheduler/jobs/{job_id}/trigger")
66
+ async def trigger_scheduler_job(job_id: str, admin: dict = Depends(get_current_admin)):
67
+ """Run a scheduler job by hand (administrators only)."""
68
+ if not scheduler:
69
+ raise HTTPException(status_code=500, detail="Scheduler not initialized")
70
+
71
+ job = scheduler.get_job(job_id)
72
+ if not job:
73
+ raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
74
+
75
+ job.modify(next_run_time=datetime.utcnow())
76
+
77
+ return {"success": True, "message": f"Job {job_id} triggered manually"}
78
+ @app.get("/api/admin/scheduler/stats")
79
+ async def get_scheduler_stats(admin: dict = Depends(get_current_admin)):
80
+ """Return scheduler statistics (administrators only)."""
81
+ if not scheduler:
82
+ return {"error": "Scheduler not initialized"}
83
+
84
+ jobs = scheduler.get_jobs()
85
+ next_run_times = [job.next_run_time for job in jobs if job.next_run_time]
86
+ next_wakeup = min(next_run_times) if next_run_times else None
87
+
88
+ return {
89
+ "scheduler_running": scheduler.running,
90
+ "total_jobs": len(jobs),
91
+ "next_wakeup": next_wakeup,
92
+ "pending_tasks": len(asyncio.all_tasks()) if asyncio.get_event_loop() else 0
93
+ }