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
keepup/themes.py ADDED
@@ -0,0 +1,496 @@
1
+ """System settings and visual themes."""
2
+
3
+ import logging
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from fastapi import Depends, HTTPException
7
+ from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
8
+
9
+ from keepup.auth.dependencies import get_current_admin
10
+
11
+ from keepup import tables
12
+ from keepup.db import DatabaseManagerV2
13
+
14
+ #: What an application may import from this module. Everything else is
15
+ #: internal and may change without notice -- see doc/keepup.md.
16
+ __all__ = [
17
+ "ConfigService",
18
+ "config_service",
19
+ "register_theme_routes",
20
+ ]
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ THEMES_TABLE = "visual_themes"
25
+
26
+ VISUAL_THEMES = tables.table(
27
+ THEMES_TABLE,
28
+ tables.auto_id(),
29
+ Column("theme_name", String(100).with_variant(Text(), "sqlite"), nullable=False, unique=True),
30
+ Column("main_page_file", String(255).with_variant(Text(), "sqlite"), nullable=False),
31
+ # Branding came after the table; older databases get these two from
32
+ # ensure_tables rather than from the CREATE.
33
+ Column("brand_name", String(100).with_variant(Text(), "sqlite")),
34
+ Column("logo_url", String(255).with_variant(Text(), "sqlite")),
35
+ # SQLite had an integer flag here and the queries write 0/1 into it.
36
+ Column("is_active", Boolean().with_variant(Integer(), "sqlite"),
37
+ server_default=tables.per_dialect(postgres="FALSE", sqlite="0")),
38
+ Column("created_at", DateTime, server_default=tables.NOW),
39
+ Column("updated_at", DateTime, server_default=tables.NOW),
40
+ )
41
+
42
+
43
+ class ConfigService:
44
+ """Reads and writes system settings and visual themes."""
45
+ THEMES_TABLE = THEMES_TABLE
46
+ INSERT_DEFAULT_THEME_SQL = """
47
+ INSERT INTO visual_themes (theme_name, main_page_file, is_active)
48
+ VALUES (:theme_name, :main_page_file, :is_active)
49
+ ON CONFLICT (theme_name) DO NOTHING
50
+ """
51
+
52
+ INSERT_DEFAULT_THEME_SQLITE = """
53
+ INSERT OR IGNORE INTO visual_themes (theme_name, main_page_file, is_active)
54
+ VALUES (:theme_name, :main_page_file, :is_active)
55
+ """
56
+
57
+ GET_ACTIVE_THEME_SQL = """
58
+ SELECT theme_name, main_page_file, brand_name, logo_url, is_active
59
+ FROM visual_themes
60
+ WHERE is_active = TRUE
61
+ LIMIT 1
62
+ """
63
+
64
+ GET_ALL_THEMES_SQL = """
65
+ SELECT id, theme_name, main_page_file, brand_name, logo_url, is_active
66
+ FROM visual_themes
67
+ ORDER BY id
68
+ """
69
+
70
+ SET_THEME_ACTIVE_SQL = """
71
+ UPDATE visual_themes
72
+ SET is_active = (id = :theme_id),
73
+ updated_at = CURRENT_TIMESTAMP
74
+ WHERE id = :theme_id OR is_active = TRUE
75
+ """
76
+
77
+ CREATE_THEME_SQL = """
78
+ INSERT INTO visual_themes (theme_name, main_page_file, brand_name, logo_url, is_active)
79
+ VALUES (:theme_name, :main_page_file, :brand_name, :logo_url, :is_active)
80
+ ON CONFLICT (theme_name) DO UPDATE SET
81
+ main_page_file = EXCLUDED.main_page_file,
82
+ brand_name = EXCLUDED.brand_name,
83
+ logo_url = EXCLUDED.logo_url,
84
+ updated_at = CURRENT_TIMESTAMP
85
+ RETURNING id
86
+ """
87
+
88
+ CREATE_THEME_SQLITE = """
89
+ INSERT OR REPLACE INTO visual_themes (theme_name, main_page_file, brand_name, logo_url, is_active)
90
+ VALUES (:theme_name, :main_page_file, :brand_name, :logo_url, :is_active)
91
+ """
92
+
93
+ DELETE_THEME_SQL = """
94
+ DELETE FROM visual_themes
95
+ WHERE id = :theme_id
96
+ AND is_active = FALSE
97
+ """
98
+
99
+ def __init__(self):
100
+ """Create the service without touching the database.
101
+
102
+ The bootstrap used to run from here, and this module builds its service
103
+ at import: themes were therefore created before the application existed,
104
+ with an empty list of declared ones. Nothing an application did
105
+ afterwards could fix that -- see ``initialize``.
106
+ """
107
+ self._initialized = False
108
+ self._initializing = False
109
+ self._current_theme_cache = None
110
+
111
+ def initialize(self):
112
+ """Create the themes table and make the declared themes exist.
113
+
114
+ Called when the application is assembled, after it has declared its
115
+ themes, and lazily by the first use of the service -- whoever comes
116
+ first gets a working one. Idempotent: a second call changes nothing.
117
+ """
118
+ if self._initialized:
119
+ return
120
+
121
+ logger.info("Initializing ConfigService...")
122
+
123
+ self._initializing = True
124
+ try:
125
+ DatabaseManagerV2.initialize()
126
+ self._ensure_themes_table()
127
+ self._ensure_default_theme()
128
+ self._initialized = True
129
+ logger.info("ConfigService initialized successfully")
130
+
131
+ except Exception as e:
132
+ logger.error(f"Failed to initialize ConfigService: {str(e)}")
133
+ raise
134
+ finally:
135
+ self._initializing = False
136
+
137
+ def _ensure_ready(self):
138
+ """Raise the service if nobody has yet.
139
+
140
+ The re-entry guard matters: the bootstrap itself reads the themes, and
141
+ without it the first read inside ``initialize`` would call it again.
142
+ """
143
+ if self._initialized or self._initializing:
144
+ return
145
+ self.initialize()
146
+
147
+ def _ensure_themes_table(self):
148
+ """Create the visual themes table, or give an older one its branding columns."""
149
+ tables.ensure_tables(VISUAL_THEMES)
150
+
151
+ #: (theme_name, main_page_file, brand_name, logo_url), supplied by the
152
+ #: application through register_built_in_themes(). The framework ships no
153
+ #: theme of its own: a theme is a product's face, and a default one here
154
+ #: would put somebody else's brand in the corner of every application built
155
+ #: on this. A theme that carries no brand leaves the name baked into the
156
+ #: markup by replace_placeholder.sh at build time.
157
+ BUILT_IN_THEMES = ()
158
+
159
+ def register_built_in_themes(self, themes):
160
+ """Declare the themes this application ships, and make them exist.
161
+
162
+ Applying them here rather than only remembering them is what makes the
163
+ order of calls stop mattering: the application may declare its themes
164
+ before the service is up or after, and either way they reach the
165
+ database. Remembering alone was the defect -- the only place that read
166
+ the list had already run, at import.
167
+ """
168
+ self.BUILT_IN_THEMES = tuple(themes)
169
+ if self._initialized:
170
+ self._ensure_built_in_themes()
171
+
172
+ def _ensure_built_in_themes(self):
173
+ """Register the themes shipped with the application.
174
+
175
+ Idempotent, like every other DDL here: an existing row keeps its id and
176
+ its active flag, so re-running this never steals the active theme.
177
+ """
178
+ existing = {theme["theme_name"] for theme in self.get_all_themes()}
179
+ for theme_name, page_file, brand_name, logo_url in self.BUILT_IN_THEMES:
180
+ if theme_name in existing:
181
+ continue
182
+ self.create_theme(
183
+ theme_name=theme_name,
184
+ main_page_file=page_file,
185
+ is_active=False,
186
+ brand_name=brand_name,
187
+ logo_url=logo_url,
188
+ )
189
+ logger.info(f"Built-in theme '{theme_name}' registered")
190
+
191
+ def _ensure_default_theme(self):
192
+ """Make sure the database holds a theme, and that one of them is active.
193
+
194
+ A database with no themes at all happens once in its life, and at that
195
+ moment the only party that knows what the panel is called is the
196
+ application. So its themes go in and the first of them becomes active;
197
+ the nameless default is for an application that ships none -- otherwise
198
+ a fresh stand greets people with the name left over from the build.
199
+
200
+ A database that already holds themes keeps the administrator's choice:
201
+ restarting MUST NOT move the active flag.
202
+ """
203
+ themes = self.get_all_themes()
204
+
205
+ if themes:
206
+ if not self.get_active_theme():
207
+ logger.info("No active theme found. Activating first theme...")
208
+ self.set_active_theme(themes[0]['id'])
209
+ self._ensure_built_in_themes()
210
+ return
211
+
212
+ self._ensure_built_in_themes()
213
+ declared = self.get_all_themes()
214
+ if declared:
215
+ logger.info("Empty database: activating the theme the application ships")
216
+ self.set_active_theme(declared[0]['id'])
217
+ return
218
+
219
+ logger.info("No themes found and none declared. Adding default theme...")
220
+ self._add_default_theme()
221
+ logger.info("Default theme added successfully")
222
+
223
+ def _add_default_theme(self):
224
+ """Insert the default theme."""
225
+ from keepup.db import db_config
226
+
227
+ params = {
228
+ "theme_name": "default",
229
+ "main_page_file": "index_new.html",
230
+ "is_active": True if db_config.is_postgres() else 1
231
+ }
232
+
233
+ if db_config.is_postgres():
234
+ DatabaseManagerV2.execute_one(
235
+ self.INSERT_DEFAULT_THEME_SQL,
236
+ params
237
+ )
238
+ else:
239
+ DatabaseManagerV2.execute_commit(
240
+ self.INSERT_DEFAULT_THEME_SQLITE,
241
+ params
242
+ )
243
+
244
+ def get_active_theme(self) -> Optional[Dict[str, Any]]:
245
+ """Return the currently active theme.
246
+
247
+ Returns:
248
+ Dict with theme_name, main_page_file, brand_name, logo_url and
249
+ is_active, or None when no theme is active.
250
+ """
251
+ self._ensure_ready()
252
+ try:
253
+ result = DatabaseManagerV2.execute_one(self.GET_ACTIVE_THEME_SQL)
254
+ if result and 'is_active' in result:
255
+ from keepup.db import db_config
256
+ if db_config.is_sqlite():
257
+ result['is_active'] = bool(result['is_active'])
258
+
259
+ self._current_theme_cache = result
260
+ return result
261
+
262
+ except Exception as e:
263
+ logger.error(f"Error getting active theme: {str(e)}")
264
+ return None
265
+
266
+ def get_active_theme_brand(self) -> Dict[str, Any]:
267
+ """Return the branding of the active theme.
268
+
269
+ Only the name and the logo: this is served without authentication, so
270
+ nothing else about the theme may leak through it.
271
+ """
272
+ theme = self.get_active_theme() or {}
273
+ return {
274
+ "brand_name": theme.get("brand_name"),
275
+ "logo_url": theme.get("logo_url"),
276
+ }
277
+
278
+ def get_active_theme_page_file(self) -> str:
279
+ """Return the main page file name of the active theme.
280
+
281
+ Returns:
282
+ The file name, or 'index_new.html' by default.
283
+ """
284
+ active_theme = self.get_active_theme()
285
+
286
+ if active_theme and 'main_page_file' in active_theme:
287
+ return active_theme['main_page_file']
288
+
289
+ logger.warning("No active theme found, using default 'index_new.html'")
290
+ return "index_new.html"
291
+
292
+ def get_all_themes(self) -> List[Dict[str, Any]]:
293
+ """Return every visual theme.
294
+
295
+ Returns:
296
+ List[Dict]: the themes.
297
+ """
298
+ self._ensure_ready()
299
+ try:
300
+ themes = DatabaseManagerV2.execute(self.GET_ALL_THEMES_SQL)
301
+ from keepup.db import db_config
302
+ for theme in themes:
303
+ if db_config.is_sqlite() and 'is_active' in theme:
304
+ theme['is_active'] = bool(theme['is_active'])
305
+
306
+ return themes
307
+
308
+ except Exception as e:
309
+ logger.error(f"Error getting all themes: {str(e)}")
310
+ return []
311
+
312
+ def set_active_theme(self, theme_id: int) -> bool:
313
+ """Make a theme active.
314
+
315
+ Args:
316
+ theme_id: id of the theme to activate
317
+
318
+ Returns:
319
+ bool: whether the operation succeeded.
320
+ """
321
+ self._ensure_ready()
322
+ try:
323
+ DatabaseManagerV2.execute_commit(
324
+ self.SET_THEME_ACTIVE_SQL,
325
+ {"theme_id": theme_id}
326
+ )
327
+ self._current_theme_cache = None
328
+ logger.info(f"Theme {theme_id} set as active")
329
+ return True
330
+
331
+ except Exception as e:
332
+ logger.error(f"Error setting active theme: {str(e)}")
333
+ return False
334
+
335
+ def create_theme(self, theme_name: str, main_page_file: str, is_active: bool = False,
336
+ brand_name: str = None, logo_url: str = None) -> Optional[int]:
337
+ """Create a theme.
338
+
339
+ Args:
340
+ theme_name: display name
341
+ main_page_file: main page file name
342
+ is_active: whether the theme becomes active
343
+ brand_name: panel name this theme shows in the top left corner
344
+ logo_url: image shown there instead of the name
345
+
346
+ Returns:
347
+ int: id of the created theme, or None on error.
348
+ """
349
+ self._ensure_ready()
350
+ from keepup.db import db_config
351
+ from keepup.web import static_page
352
+
353
+ # Checked here as well as when the page is served. Authorisation alone
354
+ # would leave an administrator reading the whole file system of the
355
+ # server through the panel, and a name refused at the door never has to
356
+ # be refused again by every reader of the column.
357
+ if static_page(main_page_file) is None:
358
+ logger.error("Refusing a theme whose page (%r) is outside the front-end directory",
359
+ main_page_file)
360
+ raise HTTPException(
361
+ status_code=400,
362
+ detail="main_page_file must name a file inside the front-end directory")
363
+
364
+ params = {
365
+ "theme_name": theme_name,
366
+ "main_page_file": main_page_file,
367
+ "brand_name": brand_name,
368
+ "logo_url": logo_url,
369
+ "is_active": is_active if db_config.is_postgres() else (1 if is_active else 0)
370
+ }
371
+
372
+ try:
373
+ if db_config.is_postgres():
374
+ result = DatabaseManagerV2.execute_one(
375
+ self.CREATE_THEME_SQL,
376
+ params
377
+ )
378
+ theme_id = result['id'] if result else None
379
+ else:
380
+ DatabaseManagerV2.execute_commit(
381
+ self.CREATE_THEME_SQLITE,
382
+ params
383
+ )
384
+ result = DatabaseManagerV2.execute_one(
385
+ "SELECT last_insert_rowid() as id"
386
+ )
387
+ theme_id = result['id'] if result else None
388
+
389
+ if theme_id and is_active:
390
+ self.set_active_theme(theme_id)
391
+
392
+ logger.info(f"Theme '{theme_name}' created with id {theme_id}")
393
+ return theme_id
394
+
395
+ except Exception as e:
396
+ logger.error(f"Error creating theme: {str(e)}")
397
+ return None
398
+
399
+ def delete_theme(self, theme_id: int) -> bool:
400
+ """Delete a theme. The active theme cannot be deleted.
401
+
402
+ Args:
403
+ theme_id: id of the theme to delete
404
+
405
+ Returns:
406
+ bool: whether the operation succeeded.
407
+ """
408
+ self._ensure_ready()
409
+ try:
410
+ active_theme = self.get_active_theme()
411
+ if active_theme and active_theme.get('id') == theme_id:
412
+ logger.warning(f"Cannot delete active theme {theme_id}")
413
+ return False
414
+
415
+ affected = DatabaseManagerV2.execute_commit(
416
+ self.DELETE_THEME_SQL,
417
+ {"theme_id": theme_id}
418
+ )
419
+
420
+ if affected > 0:
421
+ logger.info(f"Theme {theme_id} deleted")
422
+ return True
423
+ else:
424
+ logger.warning(f"Theme {theme_id} not found or is active")
425
+ return False
426
+
427
+ except Exception as e:
428
+ logger.error(f"Error deleting theme: {str(e)}")
429
+ return False
430
+
431
+ def is_initialized(self) -> bool:
432
+ """Return whether the service has been initialised."""
433
+ return self._initialized
434
+
435
+
436
+ # --- HTTP surface -------------------------------------------------------------
437
+ #
438
+ # The branding endpoint answers without authentication on purpose: the logo and
439
+ # the product name are on the sign-in screen, before anyone has signed in.
440
+
441
+
442
+ def register_theme_routes(app, config_service):
443
+ """Register the visual theme endpoints on the application."""
444
+
445
+ @app.get("/api/theme/brand")
446
+ async def get_active_theme_brand():
447
+ """Return the active theme's branding.
448
+
449
+ Deliberately unauthenticated: the logo is on the login screen, before there
450
+ is a user to authorise. The response carries only the name and the logo URL.
451
+ """
452
+ return config_service.get_active_theme_brand()
453
+ # These four change what every visitor of the panel is served, so they are
454
+ # administrative -- and until task keepup-10 that was said in a docstring
455
+ # and nowhere in the code. A docstring is not a check: anybody at all could
456
+ # create a theme, point it at a file outside the front-end directory and
457
+ # read it back through /selfcare.
458
+ @app.get("/themes")
459
+ async def get_all_themes(admin: dict = Depends(get_current_admin)):
460
+ """Return every theme."""
461
+ return {
462
+ "themes": config_service.get_all_themes(),
463
+ "active_theme": config_service.get_active_theme()
464
+ }
465
+ @app.post("/themes/{theme_id}/activate")
466
+ async def activate_theme(theme_id: int, admin: dict = Depends(get_current_admin)):
467
+ """Activate a theme by id."""
468
+ success = config_service.set_active_theme(theme_id)
469
+
470
+ if success:
471
+ return {"success": True, "message": f"Theme {theme_id} activated"}
472
+ else:
473
+ return {"success": False, "message": f"Failed to activate theme {theme_id}"}
474
+ @app.post("/themes/create")
475
+ async def create_theme(theme_name: str, main_page_file: str, is_active: bool = False,
476
+ admin: dict = Depends(get_current_admin)):
477
+ """Create a theme."""
478
+ theme_id = config_service.create_theme(theme_name, main_page_file, is_active)
479
+
480
+ if theme_id:
481
+ return {"success": True, "theme_id": theme_id, "message": "Theme created"}
482
+ else:
483
+ return {"success": False, "message": "Failed to create theme"}
484
+ @app.delete("/themes/{theme_id}")
485
+ async def delete_theme(theme_id: int, admin: dict = Depends(get_current_admin)):
486
+ """Delete a theme."""
487
+ success = config_service.delete_theme(theme_id)
488
+
489
+ if success:
490
+ return {"success": True, "message": f"Theme {theme_id} deleted"}
491
+ else:
492
+ return {"success": False, "message": f"Failed to delete theme {theme_id}"}
493
+
494
+
495
+ #: The one instance the application and the framework share.
496
+ config_service = ConfigService()
keepup/web.py ADDED
@@ -0,0 +1,182 @@
1
+ """The pages and the health of the application itself.
2
+
3
+ Everything here is served from the working directory, not from the package:
4
+ the front end and the version file are data of the deployment, and the
5
+ application says where they are through ``configure()``. The public health
6
+ answer deliberately carries nothing about the database beyond whether it
7
+ answered -- the detailed one is administrative.
8
+ """
9
+
10
+ import logging
11
+ import os
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+
15
+ from fastapi import Depends, HTTPException
16
+ from fastapi.responses import FileResponse, JSONResponse
17
+
18
+ from keepup import cluster
19
+ from keepup.api_versions import describe
20
+ from keepup.audit import incoming_requests_buffer
21
+ from keepup.auth.dependencies import get_current_admin
22
+ from keepup.db import DatabaseManager, db_config
23
+ from keepup.instance import get_instance_id, get_instance_name
24
+ from keepup.themes import config_service
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ #: Where the front end lives, relative to the working directory.
29
+ STATIC_DIR = "static"
30
+ CLIENT_PAGE = "main.html"
31
+ VERSION_FILE = "version.json"
32
+ FAVICON_FILE = "favicon.ico"
33
+
34
+
35
+ #: The package's own front end -- the panel shell. Resolved from this file's
36
+ #: location and never from the working directory: it is data of the package,
37
+ #: and the process may have been started anywhere.
38
+ SHELL_DIR = str(Path(__file__).resolve().parent / "static")
39
+
40
+ #: The page served when the active theme names a file that may not be served.
41
+ #: Not an error page: an administrator who broke the theme still has to be able
42
+ #: to reach the panel and fix it.
43
+ DEFAULT_PANEL_PAGE = "index_new.html"
44
+
45
+
46
+ def static_page(name):
47
+ """Resolve a page name against the front ends, refusing to leave either.
48
+
49
+ Two directories, in this order: the application's, then the package's. The
50
+ application first because a theme of its own must be able to replace one of
51
+ the package's by name; the package second because that is where the shipped
52
+ panel lives once keepup is installed rather than sitting in the repository.
53
+
54
+ The name reaches here from the `visual_themes` table, so it is data, not a
55
+ constant of the code: `os.path.join(STATIC_DIR, "../config/auth.yaml")` is
56
+ a perfectly ordinary path, and FileResponse would serve it. Containment is
57
+ checked after resolution, so that `..`, a symbolic link and an absolute
58
+ name are all refused by the same rule.
59
+
60
+ Args:
61
+ name: the file name as it was stored.
62
+
63
+ Returns:
64
+ The path to serve, or None when the name leads outside both directories
65
+ or names nothing in either.
66
+ """
67
+ if not name:
68
+ return None
69
+ for root_dir in (STATIC_DIR, SHELL_DIR):
70
+ root = os.path.realpath(root_dir)
71
+ candidate = os.path.realpath(os.path.join(root_dir, name))
72
+ if candidate != root and not candidate.startswith(root + os.sep):
73
+ continue
74
+ if os.path.isfile(candidate):
75
+ return candidate
76
+ return None
77
+
78
+
79
+ def theme_page():
80
+ """The active theme's page, or the default one when it may not be served."""
81
+ name = config_service.get_active_theme_page_file()
82
+ path = static_page(name)
83
+ if path is None:
84
+ logger.error(
85
+ "The active theme names a page that is outside the front ends or "
86
+ "absent from both (%r); serving %s instead", name, DEFAULT_PANEL_PAGE)
87
+ return os.path.join(SHELL_DIR, DEFAULT_PANEL_PAGE)
88
+ return path
89
+
90
+
91
+ def configure(static_dir=None, client_page=None, version_file=None, favicon_file=None):
92
+ """Supply the application's front-end paths."""
93
+ global STATIC_DIR, CLIENT_PAGE, VERSION_FILE, FAVICON_FILE
94
+ if static_dir is not None:
95
+ STATIC_DIR = static_dir
96
+ if client_page is not None:
97
+ CLIENT_PAGE = client_page
98
+ if version_file is not None:
99
+ VERSION_FILE = version_file
100
+ if favicon_file is not None:
101
+ FAVICON_FILE = favicon_file
102
+
103
+
104
+
105
+ def register_web_routes(app):
106
+ """Register the pages, the version and the health endpoints."""
107
+
108
+ @app.get("/", response_class=FileResponse)
109
+ async def read_root():
110
+ return FileResponse(os.path.join(STATIC_DIR, CLIENT_PAGE))
111
+ @app.get("/selfcare", response_class=FileResponse)
112
+ async def read_root_selfcare():
113
+ """Return the main page of the active visual theme."""
114
+ file_path = theme_page()
115
+ logger.debug(f"Serving {file_path} for selfcare page")
116
+ return FileResponse(file_path)
117
+ @app.get("/api/version", response_class=FileResponse)
118
+ async def get_version():
119
+ return FileResponse(os.path.join(STATIC_DIR, VERSION_FILE))
120
+ @app.get("/selfcare/modules/{path:path}")
121
+ async def serve_modules_app(path: str):
122
+ """Serve every path under /modules to the frontend."""
123
+ file_path = theme_page()
124
+ logger.debug(f"Serving {file_path} for selfcare page")
125
+ return FileResponse(file_path)
126
+ @app.get("/favicon.ico", include_in_schema=False)
127
+ async def favicon():
128
+ return FileResponse(os.path.join(STATIC_DIR, FAVICON_FILE))
129
+ @app.get("/api/health")
130
+ async def health_check():
131
+ """Whether this instance is up and reaches its database -- and nothing more.
132
+
133
+ The answer is public: the deployment proxies it to the world. It used to carry
134
+ the database connection string, which named the host, port, database and user
135
+ inside the stand's network -- a network deliberately kept behind the public
136
+ proxy. Details are for an administrator, at /api/admin/health.
137
+
138
+ A replica an administrator stopped answers 503 "stopped": that is what
139
+ makes a load balancer take it out (keepup/cluster.py).
140
+ """
141
+ if cluster.current_state() == cluster.STATE_STOPPED:
142
+ return JSONResponse(status_code=503, content={
143
+ "status": cluster.STATE_STOPPED,
144
+ "instance_id": get_instance_id(),
145
+ "timestamp": datetime.utcnow().isoformat(),
146
+ })
147
+ try:
148
+ db_status = DatabaseManager.test_connection()
149
+ except Exception as e:
150
+ db_status = {"success": False, "error": str(e)}
151
+
152
+ if not db_status.get("success"):
153
+ # The reason goes to the log; the caller learns that it failed, not where.
154
+ logger.error(f"Health check failed: {db_status.get('error')}")
155
+ raise HTTPException(status_code=503, detail="Service unavailable")
156
+
157
+ return {
158
+ "status": "healthy",
159
+ # Which instance answered: how one tells the public address and the stand
160
+ # are the same deployment (doc/stand_update.md). A container name, not an address.
161
+ "instance_id": get_instance_id(),
162
+ "timestamp": datetime.utcnow().isoformat(),
163
+ }
164
+ @app.get("/api/versions")
165
+ async def api_versions():
166
+ """Which versions of the API this server speaks; public, read by agents at start."""
167
+ from keepup.api_versions import describe
168
+ return describe()
169
+ @app.get("/api/admin/health")
170
+ async def admin_health_check(admin: dict = Depends(get_current_admin)):
171
+ """The full picture for an administrator: database, its version and settings."""
172
+ try:
173
+ db_status = DatabaseManager.test_connection()
174
+ except Exception as e:
175
+ db_status = {"success": False, "error": str(e)}
176
+ return {
177
+ "status": "healthy" if db_status.get("success") else "unhealthy",
178
+ "database": db_status,
179
+ "instance_id": get_instance_id(),
180
+ "timestamp": datetime.utcnow().isoformat(),
181
+ "incoming_requests_buffer_size": len(incoming_requests_buffer),
182
+ }