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,355 @@
1
+ """Fan-out of notifications between replicas of one application.
2
+
3
+ A WebSocket connection is held by whichever replica the participant connected
4
+ to, and the registry of those connections is a set of dictionaries in that
5
+ process. An event about a participant, however, is born wherever its source
6
+ arrived: the builder's callback lands on any replica, an agent's report on the
7
+ one holding its socket, an order transition on the one that served the request.
8
+ With the three replicas the k8s manifest declares, the chance that the event and
9
+ the socket share a replica is about one in three.
10
+
11
+ This module carries the event to the other replicas. Every replica listens on
12
+ one PostgreSQL channel; a publisher writes an envelope, every replica receives
13
+ it and delivers to the sockets *it* holds. Nothing keeps a registry of which
14
+ replica holds what: that would be a second source of truth about something each
15
+ replica already knows about its own sockets, and it would go stale exactly when
16
+ it is relied upon -- when a connection drops and when a replica dies.
17
+
18
+ Delivery is best-effort by construction. NOTIFY does not store and does not
19
+ replay, so a replica disconnected at the moment of publication never learns of
20
+ the event. That is why an envelope names an object rather than carrying its
21
+ state: a missed notification costs one extra read, and the panel re-reads its
22
+ objects whenever its socket reconnects. Anything that must not be missed does
23
+ not belong here.
24
+
25
+ Without PostgreSQL -- SQLite is the development mode -- the bus does not start
26
+ and publishing is a no-op. Local delivery still works, which for a single
27
+ replica is indistinguishable from full delivery.
28
+
29
+ The channel is the application's: the framework has none of its own. An
30
+ application names it in `KeepupSettings.notification_channel`, and the
31
+ framework then creates the bus before the plugins initialise and stops it after
32
+ they are cleaned up (`keepup/factory.py`).
33
+ """
34
+
35
+ import asyncio
36
+ import json
37
+ import logging
38
+ from typing import Any, Awaitable, Callable, Dict, List, Optional
39
+
40
+ from keepup.db import db_config
41
+
42
+ #: What an application may import from this module. Everything else is
43
+ #: internal and may change without notice -- see doc/keepup.md.
44
+ __all__ = [
45
+ "MAX_PAYLOAD_BYTES",
46
+ "NotificationBus",
47
+ "ORIGIN_FIELD",
48
+ "RECONNECT_DELAY_INITIAL",
49
+ "RECONNECT_DELAY_MAX",
50
+ "decode_envelope",
51
+ "deliver",
52
+ "encode_envelope",
53
+ "get_notification_bus",
54
+ "is_own_envelope",
55
+ "publish",
56
+ "set_notification_bus",
57
+ ]
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+ #: PostgreSQL caps a NOTIFY payload at 8000 bytes and refuses a longer one at
62
+ #: publish time. The cap is enforced here instead, so an oversized envelope is a
63
+ #: logged fault of the publisher rather than a failed transaction in the caller.
64
+ MAX_PAYLOAD_BYTES = 7500
65
+
66
+ #: Reconnect backoff for the listener, in seconds. It grows so that a database
67
+ #: that is down for minutes is not asked once a second for all of them, and it
68
+ #: stops growing before the delay itself becomes the outage.
69
+ RECONNECT_DELAY_INITIAL = 1.0
70
+ RECONNECT_DELAY_MAX = 30.0
71
+
72
+ #: Field every envelope carries so a replica can recognise its own. Without it a
73
+ #: publisher would deliver locally and then again on receipt, and the
74
+ #: participant would get the message twice.
75
+ ORIGIN_FIELD = "origin"
76
+
77
+
78
+ def encode_envelope(envelope: Dict[str, Any]) -> str:
79
+ """Serialise an envelope for the channel.
80
+
81
+ Raises:
82
+ ValueError: when the result exceeds what the channel accepts. An
83
+ envelope is meant to name an object, not to carry it, so hitting
84
+ this means the caller put state in it.
85
+ """
86
+ payload = json.dumps(envelope, ensure_ascii=False, default=str)
87
+ size = len(payload.encode("utf-8"))
88
+ if size > MAX_PAYLOAD_BYTES:
89
+ raise ValueError(
90
+ f"notification envelope is {size} bytes, over the {MAX_PAYLOAD_BYTES} "
91
+ f"limit: an envelope names an object, it does not carry its state"
92
+ )
93
+ return payload
94
+
95
+
96
+ def decode_envelope(payload: str) -> Optional[Dict[str, Any]]:
97
+ """Parse an envelope off the channel, or None when it is not one.
98
+
99
+ Anything unparseable is dropped rather than raised: the channel is shared,
100
+ and one malformed payload must not take the listener down with it.
101
+ """
102
+ try:
103
+ envelope = json.loads(payload)
104
+ except (TypeError, ValueError):
105
+ logger.warning("Dropping an unparseable envelope")
106
+ return None
107
+
108
+ if not isinstance(envelope, dict):
109
+ logger.warning("Dropping a non-object envelope")
110
+ return None
111
+
112
+ return envelope
113
+
114
+
115
+ def is_own_envelope(envelope: Dict[str, Any], instance_id: str) -> bool:
116
+ """Whether this replica published the envelope it just received.
117
+
118
+ Delivery to local sockets happens at publish time, so accepting the echo
119
+ would send the same message to the same participant twice.
120
+ """
121
+ return envelope.get(ORIGIN_FIELD) == instance_id
122
+
123
+
124
+ class NotificationBus:
125
+ """Publishes envelopes to the other replicas and receives theirs.
126
+
127
+ The bus knows nothing about WebSockets. Subscribers -- in practice a
128
+ WebSocket plugin -- register a handler and decide for themselves whether an
129
+ envelope addresses a connection they hold.
130
+
131
+ One channel per application is enough: envelopes are cheap to filter, and a
132
+ channel per kind would multiply connections without splitting real traffic.
133
+ """
134
+
135
+ def __init__(self, instance_id: str, channel: str):
136
+ if not channel:
137
+ raise ValueError("a notification bus needs the application's channel name")
138
+ self._instance_id = instance_id
139
+ self._channel = channel
140
+ self._handlers: List[Callable[[Dict[str, Any]], Awaitable[None]]] = []
141
+ self._connection = None
142
+ self._listener_task: Optional[asyncio.Task] = None
143
+ self._stopping = False
144
+
145
+ @property
146
+ def is_running(self) -> bool:
147
+ """Whether envelopes from other replicas are currently arriving."""
148
+ return self._connection is not None
149
+
150
+ @property
151
+ def instance_id(self) -> str:
152
+ return self._instance_id
153
+
154
+ def subscribe(self, handler: Callable[[Dict[str, Any]], Awaitable[None]]) -> None:
155
+ """Register a coroutine to be called with every foreign envelope."""
156
+ self._handlers.append(handler)
157
+
158
+ async def dispatch(self, envelope: Dict[str, Any]) -> None:
159
+ """Hand an envelope to every subscriber.
160
+
161
+ Public because it is also the local delivery path: publishing delivers
162
+ through the same call, so the two paths cannot drift apart.
163
+
164
+ One failing handler must not stop the others: an envelope is usually
165
+ addressed to a connection only one of them holds.
166
+ """
167
+ for handler in self._handlers:
168
+ try:
169
+ await handler(envelope)
170
+ except Exception as e:
171
+ logger.error(f"Notification handler failed: {e}", exc_info=True)
172
+
173
+ async def publish(self, envelope: Dict[str, Any]) -> bool:
174
+ """Send an envelope to the other replicas.
175
+
176
+ Never raises: the caller is in the middle of a status change, an agent
177
+ report or a console command, and none of those should fail because
178
+ nobody was listening.
179
+
180
+ Returns:
181
+ bool: whether the envelope reached the channel. False also means
182
+ "the bus is not running", which is the normal state on SQLite.
183
+ """
184
+ envelope = dict(envelope)
185
+ envelope[ORIGIN_FIELD] = self._instance_id
186
+
187
+ if not self.is_running:
188
+ return False
189
+
190
+ try:
191
+ payload = encode_envelope(envelope)
192
+ except ValueError as e:
193
+ logger.error(str(e))
194
+ return False
195
+
196
+ try:
197
+ await self._connection.execute(
198
+ "SELECT pg_notify($1, $2)", self._channel, payload
199
+ )
200
+ return True
201
+ except Exception as e:
202
+ logger.error(f"Could not publish a notification: {e}")
203
+ return False
204
+
205
+ async def start(self) -> bool:
206
+ """Open the listening connection and keep it open.
207
+
208
+ Returns:
209
+ bool: whether listening began. False on a database that has no
210
+ such mechanism, which is a working mode and not a failure.
211
+ """
212
+ if not db_config.is_postgres():
213
+ logger.info(
214
+ "Notification bus is off: it needs PostgreSQL, and notifications "
215
+ "will reach only the sockets of this process"
216
+ )
217
+ return False
218
+
219
+ self._stopping = False
220
+ self._listener_task = asyncio.create_task(self._listen_forever())
221
+ return True
222
+
223
+ async def stop(self) -> None:
224
+ """Close the listening connection and stop reconnecting."""
225
+ self._stopping = True
226
+
227
+ if self._listener_task:
228
+ self._listener_task.cancel()
229
+ try:
230
+ await self._listener_task
231
+ except (asyncio.CancelledError, Exception):
232
+ pass
233
+ self._listener_task = None
234
+
235
+ await self._close_connection()
236
+
237
+ async def _close_connection(self) -> None:
238
+ if self._connection is None:
239
+ return
240
+ connection, self._connection = self._connection, None
241
+ try:
242
+ await connection.close()
243
+ except Exception as e:
244
+ logger.warning(f"Could not close the notification connection: {e}")
245
+
246
+ async def _connect(self):
247
+ """Open a connection dedicated to listening.
248
+
249
+ Deliberately not from the SQLAlchemy pool: LISTEN occupies a connection
250
+ for as long as it listens, and a pooled connection handed back would
251
+ stop delivering while still looking reusable.
252
+ """
253
+ import asyncpg
254
+
255
+ return await asyncpg.connect(
256
+ host=db_config.db_host,
257
+ port=int(db_config.db_port),
258
+ user=db_config.db_user,
259
+ password=db_config.db_password,
260
+ database=db_config.db_name,
261
+ )
262
+
263
+ def _on_notify(self, connection, pid, channel, payload) -> None:
264
+ """asyncpg calls this from the connection's reader task."""
265
+ envelope = decode_envelope(payload)
266
+ if envelope is None:
267
+ return
268
+ if is_own_envelope(envelope, self._instance_id):
269
+ return
270
+ asyncio.create_task(self.dispatch(envelope))
271
+
272
+ async def _listen_forever(self) -> None:
273
+ """Hold the listening connection, reopening it after a break.
274
+
275
+ The break is logged on both sides -- lost and restored -- because
276
+ delivery has no replay: what happened while this was down is not
277
+ recoverable from the bus, and a silent gap would be indistinguishable
278
+ from nothing having happened.
279
+ """
280
+ delay = RECONNECT_DELAY_INITIAL
281
+
282
+ while not self._stopping:
283
+ try:
284
+ self._connection = await self._connect()
285
+ await self._connection.add_listener(self._channel, self._on_notify)
286
+ logger.info(f"Notification bus listening on '{self._channel}'")
287
+ delay = RECONNECT_DELAY_INITIAL
288
+
289
+ while not self._stopping and self._connection is not None:
290
+ if self._connection.is_closed():
291
+ raise ConnectionError("the listening connection was closed")
292
+ await asyncio.sleep(1)
293
+
294
+ except asyncio.CancelledError:
295
+ raise
296
+ except Exception as e:
297
+ await self._close_connection()
298
+ if self._stopping:
299
+ return
300
+ logger.warning(
301
+ f"Notification bus lost its connection ({e}); "
302
+ f"reconnecting in {delay:.0f}s"
303
+ )
304
+ await asyncio.sleep(delay)
305
+ delay = min(delay * 2, RECONNECT_DELAY_MAX)
306
+
307
+
308
+ #: The application's bus. Created at startup so that a module importing this one
309
+ #: does not open a database connection as a side effect of the import.
310
+ _bus: Optional[NotificationBus] = None
311
+
312
+
313
+ def get_notification_bus() -> Optional[NotificationBus]:
314
+ """The running bus, or None before startup and after shutdown."""
315
+ return _bus
316
+
317
+
318
+ def set_notification_bus(bus: Optional[NotificationBus]) -> None:
319
+ """Install the bus. Called at startup, and by tests with a stand-in."""
320
+ global _bus
321
+ _bus = bus
322
+
323
+
324
+ async def publish(envelope: Dict[str, Any]) -> bool:
325
+ """Publish through the application's bus, if there is one.
326
+
327
+ A call before startup, after shutdown or without PostgreSQL is not an
328
+ error: it means nobody outside this process will hear, which is exactly
329
+ the single-replica case.
330
+ """
331
+ bus = get_notification_bus()
332
+ if bus is None:
333
+ return False
334
+ return await bus.publish(envelope)
335
+
336
+
337
+ async def deliver(envelope: Dict[str, Any]) -> bool:
338
+ """Send an envelope to the other replicas and to this one.
339
+
340
+ This is what call sites use. They do not look in their own registries
341
+ first: a sender that skipped the bus whenever the addressee happened to be
342
+ local would exercise the bus only by luck -- never at all on one replica,
343
+ and for the first time on the day a second one is deployed.
344
+
345
+ Returns:
346
+ bool: whether the envelope reached the other replicas. Local delivery
347
+ happens either way, so False is not a failure to deliver.
348
+ """
349
+ published = await publish(envelope)
350
+
351
+ bus = get_notification_bus()
352
+ if bus is not None:
353
+ await bus.dispatch(envelope)
354
+
355
+ return published
@@ -0,0 +1,9 @@
1
+ """The plugin runtime: the contract, the manager, and who is switched on.
2
+
3
+ ``base`` holds :class:`BasePlugin` and :class:`PluginManager`, ``enablement``
4
+ decides which declared plugins run, ``routes`` turns a declared route into an
5
+ endpoint, ``admin`` publishes what the deployment decided about each plugin,
6
+ and ``registry`` assembles the lot -- and is the address an application imports
7
+ from. The directory plugins are loaded from belongs to the application: the
8
+ framework is a different package and holds none.
9
+ """
@@ -0,0 +1,246 @@
1
+ """What the deployment decided about each plugin, and the surface that shows it.
2
+
3
+ Three sources decide whether a declared plugin runs: its own flag in the
4
+ configuration file, an administrator's override kept in this deployment's
5
+ database, and the environment of this stand. The rule itself is
6
+ ``keepup.plugins.enablement``, which is pure; what lives here is everything
7
+ around it that is not -- reading the file, reading and writing the overrides,
8
+ and the administrative endpoints that report the decision and change it.
9
+
10
+ The endpoints are the reason any of this is worth reporting at all. Once the
11
+ server is up, a plugin that was switched off and a plugin that fell over look
12
+ exactly the same from outside: the routes are absent and the server is
13
+ healthy. The difference is kept by the manager and published here.
14
+ """
15
+
16
+ import json
17
+ import logging
18
+ import os
19
+ from datetime import datetime
20
+ from typing import Any, Dict
21
+
22
+ from fastapi import Depends, HTTPException
23
+
24
+ from keepup.auth.dependencies import get_current_admin, get_current_user
25
+ from keepup.db import DatabaseManagerV2
26
+ from keepup.plugins import enablement
27
+ from keepup.plugins import route_mask
28
+
29
+ #: What an application may import from this module. Everything else is
30
+ #: internal and may change without notice -- see doc/keepup.md.
31
+ __all__ = [
32
+ "clear_plugin_override",
33
+ "get_plugins",
34
+ "get_plugins_status",
35
+ "read_plugin_overrides",
36
+ "register_plugin_admin_routes",
37
+ "write_plugin_override",
38
+ ]
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ #: Where this deployment declares its plugins. An application that keeps the
43
+ #: file elsewhere passes its own path to initialize_plugins(); this is the
44
+ #: default, and what the administrative endpoints read.
45
+ MODULES_CONFIG_PATH = 'config/modules.json'
46
+
47
+
48
+ def read_plugin_overrides():
49
+ """What an administrator decided from the panel, per plugin (task 65).
50
+
51
+ Never fatal: a database that cannot answer must not keep the server from
52
+ starting. Without the overrides the file and the environment still decide,
53
+ which is the behaviour that existed before the panel could.
54
+ """
55
+ try:
56
+ rows = DatabaseManagerV2.execute(
57
+ "SELECT plugin_id, enabled FROM plugin_overrides", {})
58
+ except Exception as e:
59
+ logger.warning(f"Could not read plugin overrides, falling back to file and environment: {e}")
60
+ return {}
61
+ return {row["plugin_id"]: bool(row["enabled"]) for row in rows}
62
+
63
+
64
+ def write_plugin_override(plugin_id: str, enabled: bool, changed_by=None) -> None:
65
+ """Record the panel's decision about one plugin, replacing any previous."""
66
+ updated = DatabaseManagerV2.execute_commit(
67
+ "UPDATE plugin_overrides SET enabled = :enabled, changed_by = :who, "
68
+ "changed_at = :now WHERE plugin_id = :pid",
69
+ {"enabled": enabled, "who": changed_by, "now": datetime.utcnow(), "pid": plugin_id})
70
+ if not updated:
71
+ DatabaseManagerV2.execute_commit(
72
+ "INSERT INTO plugin_overrides (plugin_id, enabled, changed_by, changed_at) "
73
+ "VALUES (:pid, :enabled, :who, :now)",
74
+ {"pid": plugin_id, "enabled": enabled, "who": changed_by, "now": datetime.utcnow()})
75
+
76
+
77
+ def clear_plugin_override(plugin_id: str) -> None:
78
+ """Give the decision back to the file and the environment."""
79
+ DatabaseManagerV2.execute_commit(
80
+ "DELETE FROM plugin_overrides WHERE plugin_id = :pid", {"pid": plugin_id})
81
+
82
+
83
+ def _declared_plugin_ids():
84
+ with open(MODULES_CONFIG_PATH, 'r', encoding='utf-8') as f:
85
+ config = json.load(f)
86
+ return {p["id"] for p in enablement.declared_plugins(config)}
87
+
88
+
89
+ def _refuse_if_the_deployment_decides(plugin_id: str):
90
+ """A plugin named in the environment is not the panel's to switch.
91
+
92
+ Storing an override the environment would overrule is a trap: the
93
+ administrator switches it, restarts, and nothing changes. The refusal
94
+ names the reason instead.
95
+ """
96
+ if plugin_id not in _declared_plugin_ids():
97
+ raise HTTPException(status_code=404, detail="config/modules.json does not declare this plugin")
98
+ if enablement.decided_by_environment(plugin_id, os.environ):
99
+ raise HTTPException(
100
+ status_code=409,
101
+ detail=(f"This plugin is decided by the deployment: "
102
+ f"{enablement.ENABLE_ENV}/{enablement.DISABLE_ENV} name it. "
103
+ f"Change the environment of this stand and restart."))
104
+
105
+
106
+ async def get_plugins(manager, current_user):
107
+ """The plugins available to this user: granted to the role and running.
108
+
109
+ A module-level function rather than only a closure of the route, because
110
+ this is the decision worth checking and a closure can be reached only
111
+ through the HTTP layer.
112
+ """
113
+ try:
114
+ with open(MODULES_CONFIG_PATH, 'r', encoding='utf-8') as f:
115
+ config = json.load(f)
116
+
117
+ user_role = current_user['role']
118
+ role_config = None
119
+ for role in config.get('roles', []):
120
+ if role.get('name') == user_role:
121
+ role_config = role
122
+ break
123
+
124
+ if not role_config:
125
+ return {"plugins": []}
126
+ allowed_plugin_names = role_config.get('plugins', [])
127
+
128
+ # The role's list is visibility, not enablement: a plugin the role is
129
+ # shown but that did not come up has no routes to advertise.
130
+ available_plugins = []
131
+ for plugin_config in config.get('plugins', []):
132
+ if plugin_config.get('id') in allowed_plugin_names \
133
+ and manager.get_plugin(plugin_config.get('id')) is not None:
134
+ available_plugins.append({
135
+ "id": plugin_config.get('id'),
136
+ "name": plugin_config.get('name'),
137
+ "config": plugin_config.get('config', {})
138
+ })
139
+
140
+ return {"plugins": available_plugins}
141
+
142
+ except Exception as e:
143
+ logger.error(f"Error getting plugins: {str(e)}")
144
+ return {"plugins": []}
145
+
146
+
147
+ async def get_plugins_status(manager, current_user=None):
148
+ """The state of every declared plugin.
149
+
150
+ Enabled or not and from where, loaded or not, initialised or not, and why.
151
+ An enabled plugin that did not come up is otherwise visible only as a line
152
+ in the start-up log.
153
+ """
154
+ try:
155
+ with open(MODULES_CONFIG_PATH, 'r', encoding='utf-8') as f:
156
+ config = json.load(f)
157
+ # Two resolutions: the snapshot taken at start-up is what is actually
158
+ # running, and the one computed now carries the panel's latest
159
+ # decisions. Where they differ, the row awaits a restart.
160
+ desired = enablement.resolve(
161
+ config, os.environ, overrides=read_plugin_overrides())
162
+ return {"plugins": enablement.status_report(
163
+ config, manager.resolution, manager,
164
+ desired=desired, environ=os.environ)}
165
+ except Exception as e:
166
+ logger.error(f"Error reading plugin status: {str(e)}")
167
+ raise HTTPException(status_code=500, detail="Internal server error")
168
+
169
+
170
+ async def set_plugin_enabled(plugin_id: str, request: Dict[str, Any], admin: dict):
171
+ """Switch a backend plugin on or off from the panel.
172
+
173
+ Takes effect at the next start: the plugin's routes are built once, at
174
+ start-up, and are not removed from a running application.
175
+ """
176
+ _refuse_if_the_deployment_decides(plugin_id)
177
+ enabled = (request or {}).get("enabled")
178
+ if not isinstance(enabled, bool):
179
+ raise HTTPException(status_code=400, detail="Field 'enabled' must be true or false")
180
+ try:
181
+ write_plugin_override(plugin_id, enabled, changed_by=admin.get("id"))
182
+ except Exception as e:
183
+ logger.error(f"Could not store the plugin override for {plugin_id}: {e}")
184
+ raise HTTPException(status_code=500, detail="Internal server error")
185
+ return {"success": True, "plugin_id": plugin_id, "enabled": enabled,
186
+ "pending_restart": True}
187
+
188
+
189
+ async def clear_plugin_enabled(plugin_id: str, admin: dict = None):
190
+ """Give the decision about this plugin back to the file and the environment."""
191
+ _refuse_if_the_deployment_decides(plugin_id)
192
+ try:
193
+ clear_plugin_override(plugin_id)
194
+ except Exception as e:
195
+ logger.error(f"Could not clear the plugin override for {plugin_id}: {e}")
196
+ raise HTTPException(status_code=500, detail="Internal server error")
197
+ return {"success": True, "plugin_id": plugin_id}
198
+
199
+
200
+ def register_plugin_admin_routes(app, manager):
201
+ """Register the plugin endpoints on the application."""
202
+
203
+ @app.get("/api/plugins")
204
+ async def get_plugins_endpoint(current_user: dict = Depends(get_current_user)):
205
+ """Return the plugins available to the current user."""
206
+ return await get_plugins(manager, current_user)
207
+
208
+ @app.get("/api/admin/plugins")
209
+ async def get_plugins_status_endpoint(admin: dict = Depends(get_current_admin)):
210
+ """The state of every declared plugin (administrators only)."""
211
+ return await get_plugins_status(manager, admin)
212
+
213
+ @app.get("/api/admin/route-masks")
214
+ async def get_route_masks_endpoint(admin: dict = Depends(get_current_admin)):
215
+ """The declared masks of every plugin route (administrators only).
216
+
217
+ Machine-readable on purpose: the point of declaring what a route
218
+ accepts is that a wrong request can be refused before the application,
219
+ at a gateway or a proxy, and neither of those can read a signature.
220
+
221
+ Behind the administrator's role because it is a map of the
222
+ application's surface -- not a secret, but not something to hand to
223
+ everybody who signed in either.
224
+ """
225
+ return {"routes": route_mask.describe_routes(manager.get_all_api_routes())}
226
+
227
+ @app.post("/api/admin/plugins/{plugin_id}/enabled")
228
+ async def set_plugin_enabled_endpoint(plugin_id: str, request: Dict[str, Any],
229
+ admin: dict = Depends(get_current_admin)):
230
+ """Switch a backend plugin on or off from the panel (administrators only)."""
231
+ return await set_plugin_enabled(plugin_id, request, admin)
232
+
233
+ @app.delete("/api/admin/plugins/{plugin_id}/enabled")
234
+ async def clear_plugin_enabled_endpoint(plugin_id: str,
235
+ admin: dict = Depends(get_current_admin)):
236
+ """Give the decision about this plugin back to the file (administrators only)."""
237
+ return await clear_plugin_enabled(plugin_id, admin)
238
+
239
+ # There is deliberately no route that calls a named handler by name.
240
+ # get_handlers() is how one plugin calls another inside the process, which
241
+ # is a trusted surface: a handler is written for a caller that has already
242
+ # decided who may do this, so many of them check nothing themselves.
243
+ # Published over HTTP it turned every such handler into an endpoint open to
244
+ # anybody signed in, and the difference between "no such plugin" and "no
245
+ # such handler" listed them for free (task keepup-10). A plugin publishes
246
+ # what it declares in get_api_routes(), and nothing besides.