Make main the lean product a site receives
main was 16 days and 259 commits behind the line the product is actually built on, at contract 0.30.0 against 0.35.0, with no per-PC credential code at all. It was neither current nor curated - just stale. This brings it forward and, at the same time, makes it mean something: main is what a receiving site installs, and nothing else. WHAT IT CARRIES. Twelve plugins - backups, computers, endpoints, guides, knowledgebase, machines, network, notifications, printers, slides, tools, warranty - plus applications, which is manifest-less core and always ships. The only manifest dependency inside that set is endpoints on computers, and both are in it, so the closure is self-contained. WHAT IT DOES NOT. employees, geenforce, measuringtools, printedparts and usb stay on the site line. So do the Windows installer tree, the VM rehearsal helpers, the agent tooling config, one site's data loader, the internal audit and findings records, and the planner spreadsheet. 1,135 tracked files against 1,438. A REMOVAL THAT BREAKS THE APP IS NOT A REMOVAL, and two nearly shipped: deploy/site-profile-universal.json still named all seventeen plugins. It is the file docs/DEPLOY.md tells a site to provision from, so a fresh install would have failed at `flask plugin apply-profile` with PluginError - the first thing a receiving site does, broken by the branch meant to serve them. It now names the twelve that exist, and its comment says the two must agree. agent/ was never refreshed. Whoever populated this branch copied shopdb/, plugins/, frontend/ and tests/ from the site line and left the agent tree at its September state: 22 C# and PowerShell sources missing, including AgentCredentials, EnrollmentService, AgentHttpFactory and the fleet-alert client, plus one file the site line had deleted still present. The old tree is internally consistent, so it compiles, and nothing in CI builds it - every gate was green over a server that speaks enrollment and per-PC credentials to a bundled agent source that cannot. Resynced whole. DECISIONS THIS ENCODES, rather than defers: - The plugin-authoring lab builds printedparts, whose manifest depends on employees, so it could not stay. The lab remains on the site line and main ships no build-along tutorial. That is a real loss for an adopting developer and is recorded here rather than discovered later. - Recognition, Training and Recertification notifications are no longer seeded. Each splits one notification into a card per employee and renders a photo, which needs a plugin this branch does not bundle. Seeding them would offer an author a type that cannot resolve anybody. A site that installs employees gets them from that plugin's own seed. - Windows/IIS is documented as the legacy path throughout, and the README leads with Docker, because that is what a receiving site gets. The API description is regenerated for THIS branch - 347 paths and 483 operations, down from 415 and 573 - so the published contract describes what is here rather than what the site line serves. docs/CONFIG.md lost the two measuring-tool label keys the code no longer declares, which two lanes had decided opposite ways. Suite: 3124 passed, 6 skipped. Naming and style gates pass. The docs gates run rather than skip, and every index line count is derived from the file it names.
This commit is contained in:
@@ -4,8 +4,9 @@ from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
from flask import Flask
|
||||
import logging
|
||||
import re
|
||||
|
||||
from .base import BasePlugin, PluginMeta
|
||||
from .base import BasePlugin, PluginMeta, renderable_settings_routes
|
||||
from .registry import PluginRegistry, PluginState
|
||||
from .loader import PluginLoader
|
||||
from .migrations import PluginMigrationManager
|
||||
@@ -102,6 +103,22 @@ class PluginManager:
|
||||
|
||||
for name, plugin in plugins.items():
|
||||
self._register_plugin_components(plugin)
|
||||
self._check_settings_routes(name, plugin)
|
||||
|
||||
def _check_settings_routes(self, name: str, plugin: BasePlugin) -> None:
|
||||
"""Say at boot, once per plugin, if a declared settings tab is dead.
|
||||
|
||||
Only some settings hubs draw plugin tabs (see
|
||||
SETTINGS_HUBS_WITH_PLUGIN_TABS). A route for any other hub is accepted
|
||||
by the hook and returned by the API and then rendered by nobody, which
|
||||
looks from every side like the plugin is at fault. The API drops such a
|
||||
route; this makes the same finding at startup, so it is in the log of a
|
||||
site that never opens the settings page."""
|
||||
try:
|
||||
renderable_settings_routes(name, plugin.get_settings_routes(),
|
||||
logger)
|
||||
except Exception:
|
||||
logger.exception("get_settings_routes failed for %s", name)
|
||||
|
||||
def upgrade_all_plugins(self) -> Dict[str, str]:
|
||||
"""Run pending Alembic migrations for every discovered plugin.
|
||||
@@ -119,6 +136,13 @@ class PluginManager:
|
||||
# upgrade is the only moment left to seed them. Runs even with no
|
||||
# migration manager - it is independent of the Alembic chains.
|
||||
self.sync_all_plugin_settings()
|
||||
# Permissions need the same treatment for the same reason. A permission
|
||||
# added in a later plugin version would otherwise exist only after a
|
||||
# manual `flask seed permissions`, and until someone ran it the route
|
||||
# guarding on that name would refuse every caller - including admins on
|
||||
# sites that gate by permission rather than role. Deploys run
|
||||
# upgrade-all, so this is the moment the new name has to appear.
|
||||
self.sync_all_plugin_permissions()
|
||||
if not self.migration_manager:
|
||||
return results
|
||||
# Only ADOPTED plugins (those in the registry) get migrated. A plugin
|
||||
@@ -158,6 +182,51 @@ class PluginManager:
|
||||
touched += 1
|
||||
return touched
|
||||
|
||||
def sync_all_plugin_permissions(self) -> int:
|
||||
"""Seed every enabled plugin's declared permissions, then relink scopes.
|
||||
|
||||
Returns the number of plugins whose permissions were seeded. Best-effort
|
||||
per plugin: one bad plugin must not abort a deploy's upgrade pass.
|
||||
|
||||
The scope relink is the load-bearing half. Creating the Permission row
|
||||
only makes the name exist; the prebuilt scopes derive their grants from
|
||||
the catalog, so a permission seeded without a following
|
||||
Role.seedscopes() belongs to nobody but admin. The symptom is a plugin
|
||||
that installs cleanly and whose UI is invisible to every non-admin until
|
||||
someone re-runs the seed by hand. Ordering matters for the same reason
|
||||
it does in `flask seed permissions`: seedscopes only links rows that
|
||||
already exist, so it runs last.
|
||||
"""
|
||||
touched = 0
|
||||
for name in list(self.registry.get_all().keys()):
|
||||
if not self.registry.is_enabled(name):
|
||||
continue
|
||||
try:
|
||||
plugin = self.loader.load_plugin(name, self._app, self._db)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Could not load %s to sync its permissions", name)
|
||||
continue
|
||||
if plugin:
|
||||
self._seed_plugin_permissions(plugin)
|
||||
touched += 1
|
||||
|
||||
# Additive: this can hand a scope a newly declared permission, never
|
||||
# take one away, so a site's deliberate role edits survive the deploy.
|
||||
from shopdb.core.models import Role
|
||||
try:
|
||||
with self._app.app_context():
|
||||
result = Role.seedscopes()
|
||||
self._db.session.commit()
|
||||
granted = sum((result or {}).get('granted', {}).values())
|
||||
if granted:
|
||||
logger.info(
|
||||
"Linked %d new scope grant(s) after plugin upgrade",
|
||||
granted)
|
||||
except Exception:
|
||||
logger.exception("Could not relink prebuilt scopes after upgrade")
|
||||
return touched
|
||||
|
||||
def get_declared_plugin_settings(self) -> Dict[str, dict]:
|
||||
"""Return {key: declared entry} across all loaded plugins.
|
||||
|
||||
@@ -468,11 +537,25 @@ class PluginManager:
|
||||
return True
|
||||
|
||||
def enable_plugin(self, name: str) -> bool:
|
||||
"""Enable a disabled plugin."""
|
||||
if not self.registry.is_installed(name):
|
||||
logger.error(f"Plugin {name} is not installed")
|
||||
"""Enable a disabled plugin. Auto-installs if available but not installed."""
|
||||
# Security: Validate plugin name to prevent path traversal
|
||||
# Only allow alphanumeric, underscore, and hyphen (matches existing plugins)
|
||||
if not re.match(r'^[a-zA-Z0-9_-]+$', name):
|
||||
logger.error(f"Invalid plugin name format: {name}")
|
||||
return False
|
||||
|
||||
# Reject reserved names that could be used for directory traversal
|
||||
if name in ('.', '..', ''):
|
||||
logger.error(f"Invalid plugin name: {name}")
|
||||
return False
|
||||
|
||||
# Auto-install if available but not installed (UX: enabling should just work)
|
||||
if not self.registry.is_installed(name):
|
||||
logger.info(f"Plugin {name} not installed, installing first")
|
||||
if not self.install_plugin(name):
|
||||
logger.error(f"Failed to install plugin {name}")
|
||||
return False
|
||||
|
||||
if self.registry.is_enabled(name):
|
||||
logger.info(f"Plugin {name} is already enabled")
|
||||
return True
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Shared Alembic env.py logic for bundled plugins.
|
||||
|
||||
Every bundled plugin that owns tables (computers, employees, knowledgebase,
|
||||
machines, network, notifications, printers, slides, usb, warranty) has a
|
||||
`migrations/env.py` that does the minimum:
|
||||
Every bundled plugin that owns tables (backups, computers, endpoints, guides,
|
||||
knowledgebase, machines, network, notifications, printers, slides, tools,
|
||||
warranty) has a `migrations/env.py` that does the minimum:
|
||||
|
||||
import os
|
||||
os.environ['PLUGIN_NAME'] = 'computers'
|
||||
@@ -23,6 +23,13 @@ the core chain.
|
||||
Plugin tables must be importable via `plugins.<name>.models`. Plugins
|
||||
register their `__tablename__` set in PLUGIN_TABLE_OWNERS below so the
|
||||
filter is explicit (avoids depending on import-side-effect global state).
|
||||
|
||||
ORPHAN_TABLE_OWNERS below is the other half of that map, and it exists because
|
||||
the core chain creates tables that no bundled plugin owns any more. Those rows
|
||||
are not a plugin's, so they must not be in PLUGIN_TABLE_OWNERS - nothing can
|
||||
import their models and no chain owns them - but they still land on every site,
|
||||
and `flask plugin prune-schema` only knows how to drop a table it can attribute
|
||||
to an owner. Drop the entry and the table becomes undroppable.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -51,35 +58,48 @@ PLUGIN_TABLE_OWNERS: dict[str, Iterable[str]] = {
|
||||
'computers': ('computertypes', 'computers', 'computerinstalledapps',
|
||||
'accessprotocols', 'computeraccess',
|
||||
'configurationpolicies', 'configurationpolicyactions',
|
||||
'businesspolicies', 'businesspolicyitems'),
|
||||
'employees': ('directoryemployees',),
|
||||
'endpoints': ('endpointstates', 'endpointevents', 'endpointcommands', 'endpointapplications', 'endpointmonitors', 'operatorreports'),
|
||||
'geenforce': ('manifestscopes', 'manifestentries', 'manifestentrypctypes',
|
||||
'manifestentryhostnames', 'manifestentrymachinenumbers',
|
||||
'manifestinusechecks', 'manifestinusecheckprocesses',
|
||||
'manifestpublishedversions', 'manifestpayloads',
|
||||
'manifestblobs',
|
||||
'manifestenforcementreports', 'manifestenforcementresults',
|
||||
'pctypealiases'),
|
||||
'businesspolicies', 'businesspolicyitems',
|
||||
'policyactionholds'),
|
||||
'endpoints': ('endpointstates', 'endpointevents', 'endpointcommands',
|
||||
'endpointapplications', 'endpointmonitors',
|
||||
'operatorreports', 'endpointhealthstates',
|
||||
'endpointhealthtransitions', 'endpointmonitorimpacts',
|
||||
'endpointlocks', 'endpointlogcollections',
|
||||
'endpointcredentials', 'endpointenrollrequests',
|
||||
'endpointmigrationwaves', 'endpointbootstraptokens'),
|
||||
'guides': ('guides', 'guiderevisions', 'guideimages'),
|
||||
'knowledgebase': ('knowledgebase',),
|
||||
'machines': ('machinetypes', 'machines'),
|
||||
'measuringtools': ('measuringtooltypes', 'measuringtools'),
|
||||
'network': ('networkdevicetypes', 'networkdevices', 'vlans', 'subnets'),
|
||||
'notifications': ('notificationtypes', 'notifications'),
|
||||
'printedparts': ('printeditems', 'printeditemtransactions',
|
||||
'printeditemfiles'),
|
||||
'notifications': ('notificationtypes', 'notifications', 'notificationacknowledgements'),
|
||||
'printers': ('printertypes', 'printers', 'modelsupplies', 'printerdrivers',
|
||||
'printersupplyalerts', 'printerobservedqueues'),
|
||||
'slides': ('tvslides',),
|
||||
# Tech Tools was schemaless until secure send: every other tool in it
|
||||
# runs in the browser and owns nothing.
|
||||
'tools': ('securesendsecrets',),
|
||||
'usb': ('usbdevicetypes', 'usbdevices', 'usbcheckouts'),
|
||||
'warranty': ('warranties', 'warrantyassets'),
|
||||
}
|
||||
|
||||
|
||||
# Tables the CORE Alembic chain creates that NO bundled plugin owns.
|
||||
#
|
||||
# They are not dead weight by accident: the core baseline (68b3947ae14f) creates
|
||||
# usbdevicetypes/usbdevices/usbcheckouts and 7d16_directoryemployees creates
|
||||
# directoryemployees, and neither migration can be removed - the whole plugin
|
||||
# chain set anchors on that head, so editing it breaks `flask db upgrade` on a
|
||||
# fresh database. The tables therefore arrive at every site whether or not
|
||||
# anything reads them.
|
||||
#
|
||||
# Keyed by the name of the plugin that used to own them, because that is the
|
||||
# name an operator recognises in prune-schema output. A key here is NOT a plugin
|
||||
# this build ships, and nothing imports models for it.
|
||||
ORPHAN_TABLE_OWNERS: dict[str, Iterable[str]] = {
|
||||
'employees': ('directoryemployees',),
|
||||
'usb': ('usbdevicetypes', 'usbdevices', 'usbcheckouts'),
|
||||
}
|
||||
|
||||
|
||||
def _get_plugin_metadata(plugin_name: str) -> MetaData:
|
||||
"""Import the plugin's models and return a MetaData containing only its
|
||||
declared tables (filtered via PLUGIN_TABLE_OWNERS)."""
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
"""Base plugin class that all plugins must inherit from."""
|
||||
"""Base plugin class that all plugins must inherit from.
|
||||
|
||||
One rule that is not expressible as a method signature, so it lives here where
|
||||
a plugin author reads it: A PLUGIN MUST NOT HOLD A DB SESSION ACROSS EXTERNAL
|
||||
I/O. Finish with the database, then make the HTTP call / run the subprocess /
|
||||
touch the share, then open a fresh session to write the result. Under gevent a
|
||||
slow external call does not block its worker, but it does pin one of that
|
||||
worker's pooled database connections for its whole duration, and enough
|
||||
concurrent greenlets on such a path drain the pool and stall every other
|
||||
request in the process - the whole site, every plugin, with the CPU idle and
|
||||
MySQL healthy. See CONTRIBUTING.md ("A plugin must not hold a DB session across
|
||||
external I/O") for the shape to write, and docker-compose.yml for how the pool
|
||||
relates to the worker count and to MySQL max_connections.
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Dict, Optional, Type
|
||||
@@ -6,6 +19,41 @@ from dataclasses import dataclass, field
|
||||
from flask import Flask, Blueprint
|
||||
|
||||
|
||||
# Settings hubs whose Vue page actually draws plugin-contributed tabs: it asks
|
||||
# /api/plugins/settings-routes, keeps the routes whose `hub` matches its own id,
|
||||
# and registers them with router.addRoute(). Every other hub renders its own
|
||||
# tabs and nothing else, so a route naming one would be returned by the API and
|
||||
# never drawn - a tab the author declared correctly that simply does not exist
|
||||
# for the user. Hubs are added here only when their .vue file gains that code;
|
||||
# tests/test_core/test_plugin_settings_hubs.py fails if the two drift apart.
|
||||
SETTINGS_HUBS_WITH_PLUGIN_TABS = ('model-catalog',)
|
||||
|
||||
|
||||
def renderable_settings_routes(plugin_name: str, routes: Optional[List[Dict]],
|
||||
logger) -> List[Dict]:
|
||||
"""The subset of a plugin's declared settings routes that a hub can draw.
|
||||
|
||||
Anything naming a hub outside SETTINGS_HUBS_WITH_PLUGIN_TABS is dropped and
|
||||
logged as an error naming the plugin, the hub and the supported set. The
|
||||
declaration is not a crash - the plugin's API, models and pages are all
|
||||
fine - so this refuses the dead tab rather than the plugin. The hard stop
|
||||
lives in the test suite, where the author still has a chance to fix it.
|
||||
"""
|
||||
kept = []
|
||||
for route in routes or []:
|
||||
hub = route.get('hub')
|
||||
if hub in SETTINGS_HUBS_WITH_PLUGIN_TABS:
|
||||
kept.append(route)
|
||||
continue
|
||||
logger.error(
|
||||
"Plugin %s declares settings route '%s' for hub '%s'. No settings "
|
||||
"hub page registers plugin tabs for that hub, so the tab would "
|
||||
"never render; dropping it. Hubs that support plugin tabs: %s",
|
||||
plugin_name, route.get('name'), hub,
|
||||
', '.join(SETTINGS_HUBS_WITH_PLUGIN_TABS))
|
||||
return kept
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginMeta:
|
||||
"""Plugin metadata container."""
|
||||
@@ -16,7 +64,8 @@ class PluginMeta:
|
||||
author: str = ""
|
||||
dependencies: List[str] = field(default_factory=list)
|
||||
# Default to the current pre-1.0 contract range; tighten when 1.0 lands
|
||||
core_version: str = ">=0.2.0,<1.0.0"
|
||||
# 0.20.0: added get_asset_type_descriptor hook (additive, backward-compatible)
|
||||
core_version: str = ">=0.20.0,<1.0.0"
|
||||
api_prefix: str = None
|
||||
|
||||
def __post_init__(self):
|
||||
@@ -78,9 +127,9 @@ class BasePlugin(ABC):
|
||||
"""Transparency note shown when a site enables this plugin.
|
||||
|
||||
Return None for plugins that need no special setup. For plugins that
|
||||
create extra tables (e.g. a self-hosted directory or USB tables), return:
|
||||
create extra tables (a revision history, an events log), return:
|
||||
{
|
||||
'tables': ['directoryemployees', ...], # created in the shopdb DB
|
||||
'tables': ['backuprevisions', ...], # created in the shopdb DB
|
||||
'note': 'Plain-language what/why.',
|
||||
'docs': 'plugins/<name>/README.md', # where the schema lives
|
||||
}
|
||||
@@ -128,6 +177,56 @@ class BasePlugin(ABC):
|
||||
"""
|
||||
return []
|
||||
|
||||
def get_settings_routes(self) -> List[Dict]:
|
||||
"""Frontend routes this plugin adds to settings pages.
|
||||
|
||||
Returns a list of route configurations for the plugin's settings pages.
|
||||
Each route is a dict with:
|
||||
hub - settings hub to attach to; ONLY a hub named in
|
||||
SETTINGS_HUBS_WITH_PLUGIN_TABS (top of this module) draws
|
||||
plugin tabs. A route for any other hub is dropped by
|
||||
/api/plugins/settings-routes with an error in the log.
|
||||
path - route path relative to hub (e.g. 'operatingsystems')
|
||||
name - unique route name (e.g. 'model-catalog-os')
|
||||
tab - tab label shown in hub UI (e.g. 'Operating Systems')
|
||||
component- path to the Vue component AS IT EXISTS IN THE BUILD, i.e.
|
||||
relative to frontend/src, which for a plugin means
|
||||
'.plugins-staged/<name>/views/<Component>.vue' - the copy
|
||||
scripts/stage-frontend.mjs makes of plugins/<name>/frontend
|
||||
|
||||
Example:
|
||||
return [{
|
||||
'hub': 'model-catalog',
|
||||
'path': 'operatingsystems',
|
||||
'name': 'model-catalog-os',
|
||||
'tab': 'Operating Systems',
|
||||
'component': '.plugins-staged/computers/views/OperatingSystemsList.vue'
|
||||
}]
|
||||
|
||||
Three constraints the shape of this hook does not show, so read them
|
||||
before you rely on it (ADR-019, "Constraints as implemented"):
|
||||
|
||||
1. Declare a hub only if it is in SETTINGS_HUBS_WITH_PLUGIN_TABS. Today
|
||||
that is 'model-catalog' alone. The other hubs have no code to draw
|
||||
your tab, so the route is accepted and dropped.
|
||||
2. Route the page yourself as well, in plugins/<name>/frontend/
|
||||
routes.js, and treat THAT as the real route. The hub interpolates
|
||||
`component` into a dynamic import with no static file extension,
|
||||
which Vite will not rewrite, so the tab loads under `npm run dev`
|
||||
and 404s in a production build. A page reachable only through the
|
||||
tab is a page nobody can open at a site. Your frontend also has to
|
||||
be staged into the build (SITE_PLUGINS decides that), so enabling a
|
||||
plugin whose UI was never staged needs a frontend rebuild.
|
||||
3. The tab is not a link you can hand out. The hub registers the route
|
||||
when it mounts, so the URL resolves only for someone who has already
|
||||
been through the parent hub in that page load. Do not link to it
|
||||
from an email, a doc, or another page, and do not expect a refresh
|
||||
on it to land anywhere.
|
||||
|
||||
Return [] (default) if the plugin adds no settings pages.
|
||||
"""
|
||||
return []
|
||||
|
||||
def get_settings_defaults(self) -> List[Dict]:
|
||||
"""Declare the Setting rows this plugin owns.
|
||||
|
||||
@@ -211,6 +310,27 @@ class BasePlugin(ABC):
|
||||
f"implement apply_collector_payload"
|
||||
)
|
||||
|
||||
def resolve_agent_credential(self, secret: str) -> Optional[int]:
|
||||
"""Asset id for an active per-PC agent credential, else None.
|
||||
|
||||
Optional (contract 0.33.0). A plugin that issues endpoint credentials
|
||||
answers here so the generic collector can accept them on any schema
|
||||
declaring 'acceptsagentcredential'. Called via
|
||||
shopdb.api.resolve_agent_credential, which asks enabled plugins and
|
||||
takes the first non-None answer.
|
||||
"""
|
||||
return None
|
||||
|
||||
def agent_shared_key_refused(self, hostname: str) -> bool:
|
||||
"""True when the shared collector key may not report for this hostname.
|
||||
|
||||
Optional (contract 0.33.0). True when the shared key is switched off or
|
||||
the hostname's asset holds an active per-PC credential. Called via
|
||||
shopdb.api.agent_shared_key_refused, which is True if any enabled
|
||||
plugin says so.
|
||||
"""
|
||||
return False
|
||||
|
||||
def on_install(self, app: Flask) -> None:
|
||||
"""Called when plugin is installed via CLI."""
|
||||
pass
|
||||
@@ -418,6 +538,11 @@ class BasePlugin(ABC):
|
||||
|
||||
Consumed by GET /api/pluginui/map-overlays. Disabled plugins are
|
||||
skipped; a broken plugin is isolated in prod, re-raised in dev/test.
|
||||
|
||||
No bundled plugin implements this, so the dict above IS the whole
|
||||
specification - there is no shipped example to copy. Core's side is
|
||||
exercised against a stub in tests/test_core/test_pluginui.py, which is
|
||||
also the shortest worked example of a declaration.
|
||||
"""
|
||||
return []
|
||||
|
||||
@@ -438,5 +563,48 @@ class BasePlugin(ABC):
|
||||
|
||||
Consumed by GET /api/pluginui/asset-presentation. Disabled plugins are
|
||||
skipped; a broken plugin is isolated in prod, re-raised in dev/test.
|
||||
|
||||
No bundled plugin implements this either; same note as get_map_overlays
|
||||
above. With nothing declaring one, the route returns [] and core falls
|
||||
back to its legacy id-keyed route map in shopdb/core/api/search.py.
|
||||
"""
|
||||
return []
|
||||
|
||||
def get_asset_type_descriptor(self) -> Optional[Dict]:
|
||||
"""Return subtype management descriptor for this plugin's asset type.
|
||||
|
||||
Declares how to CRUD the plugin's subtype table (printertypes,
|
||||
machinetypes, etc.) so core can render a generic CRUD UI without
|
||||
importing the plugin's models or views. Return None if the plugin
|
||||
has no subtype table.
|
||||
|
||||
Contract (all keys required if returning non-None):
|
||||
{
|
||||
'assettype': str, # matches assettypes.assettype
|
||||
'subtype_endpoint': str, # API path WITHOUT /api prefix (e.g., '/printers/types')
|
||||
'subtype_id_field': str, # PK field name (e.g., 'printertypeid')
|
||||
'subtype_label_field': str, # Display name field (e.g., 'printertype')
|
||||
'subtype_description_field': str, # Description field
|
||||
'subtype_color_field': str, # Color field for map markers
|
||||
'optional_tabs': List[str], # Plugin-specific tabs (e.g., ['supplies'])
|
||||
'edit_permission': str, # Required permission (e.g., 'printers.manage')
|
||||
}
|
||||
|
||||
The endpoint must support:
|
||||
- GET (list) ?active=true/false for pagination
|
||||
- GET /{id} for single record
|
||||
- POST (create)
|
||||
- PUT /{id} (update)
|
||||
- DELETE /{id}
|
||||
|
||||
Payload fields:
|
||||
- {subtype_label_field}: required string
|
||||
- {subtype_description_field}: optional text
|
||||
- {subtype_color_field}: optional string (CSS color)
|
||||
- isactive: optional boolean (default True)
|
||||
|
||||
Consumed by GET /api/pluginui/asset-type-descriptors. Disabled
|
||||
plugins are skipped; a broken plugin is isolated in prod, re-raised
|
||||
in dev/test.
|
||||
"""
|
||||
return None
|
||||
|
||||
@@ -903,9 +903,10 @@ def prune_schema(yes: bool, force: bool):
|
||||
Schema-lean per-site DBs: the shared core Alembic baseline creates every
|
||||
plugin's tables, so a lean site that omits a plugin still carries that
|
||||
plugin's (empty) tables. This drops the tables of every plugin in
|
||||
PLUGIN_TABLE_OWNERS that is not installed here, leaving core + chosen-plugin
|
||||
tables only. Run once at deploy AFTER `flask db upgrade` and
|
||||
`flask plugin upgrade-all`.
|
||||
PLUGIN_TABLE_OWNERS that is not installed here, plus the
|
||||
ORPHAN_TABLE_OWNERS tables the core chain creates for no bundled plugin at
|
||||
all, leaving core + chosen-plugin tables only. Run once at deploy AFTER
|
||||
`flask db upgrade` and `flask plugin upgrade-all`.
|
||||
|
||||
Dry-run by default; pass --yes to execute. Drops by table name (no plugin
|
||||
code import) so it works on a lean image where the omitted plugin's
|
||||
@@ -915,7 +916,8 @@ def prune_schema(yes: bool, force: bool):
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
from shopdb.extensions import db
|
||||
from shopdb.plugins.alembic_template import PLUGIN_TABLE_OWNERS
|
||||
from shopdb.plugins.alembic_template import (
|
||||
ORPHAN_TABLE_OWNERS, PLUGIN_TABLE_OWNERS)
|
||||
|
||||
pm = current_app.extensions.get('plugin_manager')
|
||||
if not pm:
|
||||
@@ -928,8 +930,15 @@ def prune_schema(yes: bool, force: bool):
|
||||
|
||||
# A table is a prune candidate when its owning plugin is not installed here
|
||||
# AND the table actually exists in this database.
|
||||
#
|
||||
# ORPHAN_TABLE_OWNERS is folded in here and nowhere else: those tables have
|
||||
# no plugin left to install, so they are never in `installed` and are always
|
||||
# candidates. Without them a lean site carries them for ever, because the
|
||||
# core chain that creates them cannot be edited.
|
||||
candidates = dict(PLUGIN_TABLE_OWNERS)
|
||||
candidates.update(ORPHAN_TABLE_OWNERS)
|
||||
victims = []
|
||||
for plugin, tables in PLUGIN_TABLE_OWNERS.items():
|
||||
for plugin, tables in candidates.items():
|
||||
if plugin in installed:
|
||||
continue
|
||||
for tablename in tables:
|
||||
|
||||
@@ -84,6 +84,29 @@ class PluginLoader:
|
||||
return self._manifests[name]
|
||||
|
||||
manifest_path = self.plugins_dir / name / 'manifest.json'
|
||||
|
||||
# Security: Ensure resolved path stays within plugins_dir boundary
|
||||
# Defense in depth against path traversal, even if name was validated
|
||||
resolved_manifest = manifest_path.resolve()
|
||||
resolved_plugins = self.plugins_dir.resolve()
|
||||
|
||||
# Python 3.9+ has is_relative_to, fallback for older versions
|
||||
try:
|
||||
if not resolved_manifest.is_relative_to(resolved_plugins):
|
||||
raise PluginNotFoundError(
|
||||
f'Plugin path escapes plugins directory: {name}',
|
||||
plugin_name=name,
|
||||
)
|
||||
except AttributeError:
|
||||
# Python < 3.9 fallback using relative_to
|
||||
try:
|
||||
resolved_manifest.relative_to(resolved_plugins)
|
||||
except ValueError:
|
||||
raise PluginNotFoundError(
|
||||
f'Plugin path escapes plugins directory: {name}',
|
||||
plugin_name=name,
|
||||
)
|
||||
|
||||
if not manifest_path.exists():
|
||||
raise PluginNotFoundError(
|
||||
f'Plugin {name} has no manifest.json at {manifest_path}',
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"type": "array",
|
||||
"description": "Hard dependencies: plugin names that must be installed and enabled first. A name may carry an optional PEP440 range (e.g. 'employees>=1.1'); the runtime loader uses name-only semantics.",
|
||||
"description": "Hard dependencies: plugin names that must be installed and enabled first. A name may carry an optional PEP440 range (e.g. 'computers>=1.1'); the runtime loader uses name-only semantics.",
|
||||
"items": { "type": "string" }
|
||||
},
|
||||
"optional_dependencies": {
|
||||
@@ -48,7 +48,7 @@
|
||||
},
|
||||
"api_prefix": {
|
||||
"type": "string",
|
||||
"description": "URL prefix for the plugin blueprint, e.g. '/api/printedparts'. Must be unique across enabled plugins."
|
||||
"description": "URL prefix for the plugin blueprint, e.g. '/api/warranty'. Must be unique across enabled plugins."
|
||||
},
|
||||
"default_enabled": {
|
||||
"type": "boolean",
|
||||
|
||||
Reference in New Issue
Block a user