Files
shopdb-flask/plugins/endpoints/commands.py
cproudlock 784964c907 Bring the wilm branch into main: endpoints plugin, agent, policies, CSV import
Ports the corporate-GitHub wilm branch onto main, keeping the two branches
separate. Thirteen upstream commits arrive with their authorship intact; the
review fixes and the portability work below are on top.

What arrives:

  endpoints plugin  - a ShopDB agent reporting endpoint state, telemetry,
                      services and interfaces, with a command channel the agent
                      long-polls. Ingest stays on the generic collector route
                      (ADR-006); the agent key is a UI-managed single-scope
                      token whose revocation is an instant kill switch.
  computers policies - Configuration and Business Policies (RMM-style), scope
                      trees validated at write time, actions checked against
                      the endpoints command allowlist. Feature-gated: every
                      route 404s while the setting is off, so enabling it can
                      never half-expose the surface.
  asset CSV import  - templates, a collector script carrying the site path, and
                      a validate-then-commit import. A plugin can own a virtual
                      column plus a post-write row hook, which is how a PC's
                      machine number becomes a controls link without a
                      hand-built relationships sheet.
  agent/            - the Windows agent and its installer.

Contract 0.21.0 -> 0.24.0, additive throughout: register_import_hook (0.22),
mint/list/revoke_service_token (0.23), collector_authorized (0.24). The stability
table had no rows for any of them and now does.

MySQL 5.6 portability. The branch stored three policy columns as sa.JSON, the
only JSON columns in the product, and 5.6 has no JSON type: the migration failed
with a bare syntax error near the word JSON. They are TEXT now, through a
JSONText type decorator, so all seventeen call sites still read and write dicts.
The convention elsewhere is already TEXT (guides.blocksjson,
geenforce.manifestjson).

Review fixes carried on top:

  - six policy GETs were jwt_required(optional=True), which authenticates a
    caller without checking anything; they require computers.view now, and six
    redundant jwt_required decorators are gone
  - the agent installer took a default BaseUrl and CollectorKey, so a mistyped
    run silently pointed an endpoint at the wrong instance; both are mandatory
    and a non-https BaseUrl throws unless -AllowInsecureHttp is passed
  - a committing CSV import wrote no audit row

Documentation: the 34 new routes are described in docs/api-inventory.json, which
is hand-maintained on purpose, and the generated spec now covers 331 paths and
477 operations across 22 surfaces. DEVELOPMENT-SETUP's 1071 troubleshooting row
said "use MySQL 8 for dev" and now gives the actual fix, including the trap that
5.6 downgrades ROW_FORMAT=DYNAMIC to Compact with a warning instead of an error.

Full suite 2123 passed, vitest 260 passed, all seventeen plugin chains migrate
clean on MySQL 5.6 and the naming, docs, parity and read-surface gates are green.
2026-08-28 16:17:17 -04:00

199 lines
7.9 KiB
Python

"""Server-side allowlist of endpoint agent commands.
The WebUI never sends an arbitrary command string. It sends an allowlisted
ACTION NAME; the concrete on-endpoint behavior (which script to run, how to stop
a process) lives in the agent. This module is the single source of truth for
which action names are legal and what they mean, so both the enqueue route and
the settings/UI surface validate against the same set.
The structure anticipates per-PC-type allowlists: today every computer may run
every action in COMMAND_ALLOWLIST, but ALLOWED_ACTIONS_FOR is the seam a later
change swaps for a type-scoped lookup (inspection PCs vs shopfloor PCs).
"""
# action name -> operator-facing metadata. label/description feed the UI; the
# agent maps the action name to its local handler (see CommandExecutor).
#
# Two families of action:
# * Named MTConnect actions - fixed target, no parameters. The original,
# bay-specific controls kept for the inline services-panel toggle.
# * Generic RMM actions (service_* / process_*) - the target is supplied by
# the policy action's params ('target' = a Windows service name or a process
# image like 'DncMain.exe'). This is what populates the Configuration Policy
# builder with reusable controls that any scope (PC type or application) can
# attach. The 'targetkind' hint tells the builder which target field to show.
# NOTE: agent-side execution of the generic actions is not wired yet; the
# server allowlist and policy plumbing land first (the whole feature is
# flag-gated), so a generic action saved today is authored and gated but is
# a no-op on the endpoint until the CommandExecutor handlers ship.
COMMAND_ALLOWLIST = {
'service_start': {
'label': 'Start service',
'description': 'Start a Windows service by name on the endpoint.',
'targetkind': 'service',
},
'service_stop': {
'label': 'Stop service',
'description': 'Stop a running Windows service by name on the endpoint.',
'targetkind': 'service',
},
'service_status': {
'label': 'Check service',
'description': 'Report whether a named Windows service is running.',
'targetkind': 'service',
},
'process_start': {
'label': 'Start process',
'description': 'Launch a process by executable path on the endpoint.',
'targetkind': 'process',
},
'process_stop': {
'label': 'Stop process',
'description': 'Stop a running process by image name on the endpoint.',
'targetkind': 'process',
},
'process_status': {
'label': 'Check process',
'description': 'Report whether a named process is running.',
'targetkind': 'process',
},
'mtconnect_start': {
'label': 'Start MTConnect',
'description': 'Run the MTConnect UDC agent start script on the endpoint.',
},
'mtconnect_stop': {
'label': 'Stop MTConnect',
'description': 'Stop the running MTConnect UDC agent on the endpoint.',
},
'mtconnect_status': {
'label': 'Check MTConnect',
'description': 'Report whether the MTConnect UDC agent is running.',
},
'system_restart': {
'label': 'Restart computer',
'description': 'Restart the endpoint computer immediately.',
},
'collect_now': {
'label': 'Collect now',
'description': 'Force the endpoint agent to report fresh telemetry off-cadence.',
},
}
# Actions that demand a permission stricter than the base endpoints.command.
# The enqueue route requires the caller to ALSO hold the mapped permission, so a
# destructive action (a remote reboot) is a heavier grant than a routine toggle.
ELEVATED_ACTION_PERMISSIONS = {
'system_restart': 'endpoints.restart',
}
def elevated_permission_for(action):
"""The extra permission an action requires, or None for routine actions."""
return ELEVATED_ACTION_PERMISSIONS.get(action)
# Maps a monitored services/processes row to the start/stop/status actions that
# control it, so the services panel can render an inline toggle on exactly the
# rows that have a registered command action. The key is the agent-reported
# 'app' label; 'kind' pins the toggle to the authoritative row (for MTConnect
# the agent.exe PROCESS is the source of truth - run.bat launches it and the
# Windows service state is not reliable), so the service row stays badge-only.
ROW_COMMAND_TARGETS = {
('MTConnect', 'process'): {
'start': 'mtconnect_start',
'stop': 'mtconnect_stop',
'status': 'mtconnect_status',
},
}
def row_actions_for(app, kind, name=None):
"""Return the {start, stop, status, target, targetkind} map for a row.
Two paths:
* A row registered in ROW_COMMAND_TARGETS (MTConnect) keeps its fixed,
named actions with no wire target - agent.exe is the source of truth and
the behavior is pinned in the agent.
* Any other process/service row maps to the generic primitives
(process_* / service_*) with the row's OWN reported name as the wire
target. This is what lets a new app light up start/stop/status without
an agent rebuild: the target rides the wire.
Rows with no usable kind return None and render as a plain status badge.
"""
if not app and not name:
return None
fixed = ROW_COMMAND_TARGETS.get((app, (kind or '').lower()))
if fixed:
return {**fixed, 'target': None, 'targetkind': None}
normalized = (kind or '').lower()
if normalized == 'process' and name:
return {
'start': 'process_start',
'stop': 'process_stop',
'status': 'process_status',
'target': name,
'targetkind': 'process',
}
if normalized == 'service' and name:
return {
'start': 'service_start',
'stop': 'service_stop',
'status': 'service_status',
'target': name,
'targetkind': 'service',
}
return None
def is_allowed_action(action):
"""True when action is a known, allowlisted command name."""
return action in COMMAND_ALLOWLIST
def action_targetkind(action):
"""The targetkind an action requires ('service'/'process'), or None.
Generic actions declare a targetkind in COMMAND_ALLOWLIST; fixed-target
actions (mtconnect_*) declare none and must not carry a wire target.
"""
meta = COMMAND_ALLOWLIST.get(action) or {}
return meta.get('targetkind')
def requires_target(action):
"""True when the action is generic and needs a wire target."""
return action_targetkind(action) is not None
def ALLOWED_ACTIONS_FOR(pctype=None, assetid=None):
"""The action names an endpoint may run.
Base allowlist is flat (every action for every computer). When the computers
Configuration/Business Policy feature is enabled AND an assetid is given, the
result is narrowed to the actions the endpoint's effective policy permits -
this is the allowlist-gating half of the policy design. With the feature off
(or no assetid), it returns the full base allowlist, so nothing changes until
a site opts in. Policy resolution is imported lazily to keep this module free
of a hard dependency on the computers plugin.
"""
base = set(COMMAND_ALLOWLIST.keys())
if assetid is None:
return base
try:
from plugins.computers.services.policyresolver import effective_policy_for
except Exception:
return base
effective = effective_policy_for(assetid)
allowed = effective.allowed_actions()
if not allowed:
# No policy spoke for this endpoint. With the feature off the resolver
# returns empty and we fall back to the base allowlist (unchanged
# behavior). This is intentionally permissive; deny-by-default would be
# a separate, explicit setting.
return base
# Never widen past the code-level allowlist: policy can only gate within it.
return base & allowed