Add endpoint locks and split endpoints.deploy into three grants
Endpoint locks -------------- Adds EndpointLock so an admin can hold an endpoint against automated and operator action, with migration 0018 and enforcement in the enqueue path rather than only in the UI, so a lock cannot be bypassed by calling the API directly. Split endpoints.deploy ---------------------- endpoints.deploy bundled three actions of very different risk behind a single name: scheduledtask_run -> starts a task already registered and allowlisted update_app -> runs a pinned installer run_script -> arbitrary code as SYSTEM unless the descriptor pins a user context Because they shared one grant there was no way to let an operator push an application update without also handing them arbitrary SYSTEM code execution on every endpoint they could reach. The permission name described the lightest of the three while silently carrying the heaviest. commands.ELEVATED_ACTION_PERMISSIONS now maps each action to its own permission (endpoints.corptools, endpoints.updateapp, endpoints.runscript). The enqueue route reads that table, so no route logic changed. Migration 7d42 preserves existing access exactly: anyone holding endpoints.deploy receives all three replacements.
This commit is contained in:
@@ -103,7 +103,8 @@ COMMAND_ALLOWLIST = {
|
||||
'script sent this way runs as SYSTEM unless its '
|
||||
'descriptor pins the user context, so this is arbitrary '
|
||||
'code execution on the endpoint by design. Grant '
|
||||
'endpoints.deploy only to the most trusted operators, '
|
||||
'endpoints.runscript only to the most trusted '
|
||||
'operators, '
|
||||
'and gate the UI behind an explicit confirm the way '
|
||||
'system_restart is gated (see confirmRestart in '
|
||||
'PCDetail.vue).',
|
||||
@@ -173,25 +174,29 @@ COMMAND_ALLOWLIST = {
|
||||
# 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.
|
||||
# NOTE FOR THE ROLES/PERMISSIONS WORK: scheduledtask_run is deliberately mapped
|
||||
# onto the EXISTING endpoints.deploy grant rather than introducing a new one, so
|
||||
# the wire is pre-built and needs no migration. Be aware this WIDENS what
|
||||
# endpoints.deploy means: it previously covered run_script + update_app, and now
|
||||
# also covers starting approved scheduled tasks. If that bundle is too coarse,
|
||||
# the clean split is a separate endpoints.corptools permission mapped here - no
|
||||
# other code needs to change, because the enqueue route reads this table.
|
||||
#
|
||||
# Suggested operator-facing wording for the combined grant:
|
||||
# "Caution: Operator can run scheduled tasks, update applications, and affect
|
||||
# system-level changes to the endpoint."
|
||||
# That wording is accurate for scheduledtask_run and update_app. It UNDERSTATES
|
||||
# run_script, which is arbitrary SYSTEM code execution - if run_script stays in
|
||||
# this bundle, say so plainly in the role description.
|
||||
# These four are gated by SCOPE, never by Configuration Policy. Policy shapes
|
||||
# what a PC TYPE exposes; it is not the authority on whether a given person may
|
||||
# reboot a machine or run arbitrary code. The check runs in the enqueue route
|
||||
# BEFORE the policy gate, so it is also not break-glass-able: an admin may
|
||||
# override what policy says about a machine, never what permissions say about
|
||||
# the caller.
|
||||
#
|
||||
# Previously scheduledtask_run, run_script and update_app all mapped to a single
|
||||
# endpoints.deploy grant. That bundle made app updates impossible to grant
|
||||
# without also granting arbitrary SYSTEM code execution via run_script, so they
|
||||
# are now four independent permissions. They are NOT equal risk, and the
|
||||
# descriptions in plugin.py get_permissions() say so plainly:
|
||||
# scheduledtask_run - starts something already registered and allowlisted
|
||||
# agent-side
|
||||
# update_app - runs a pinned installer
|
||||
# run_script - arbitrary code as SYSTEM unless the descriptor pins a
|
||||
# user context
|
||||
ELEVATED_ACTION_PERMISSIONS = {
|
||||
'system_restart': 'endpoints.restart',
|
||||
'scheduledtask_run': 'endpoints.deploy',
|
||||
'run_script': 'endpoints.deploy',
|
||||
'update_app': 'endpoints.deploy',
|
||||
'scheduledtask_run': 'endpoints.corptools',
|
||||
'run_script': 'endpoints.runscript',
|
||||
'update_app': 'endpoints.updateapp',
|
||||
}
|
||||
|
||||
|
||||
@@ -304,21 +309,36 @@ def monitor_id_from_action(action):
|
||||
return None
|
||||
|
||||
|
||||
# Actions gated by ROLE ONLY, never by per-endpoint Configuration Policy.
|
||||
# Actions that are NOT a per-endpoint configuration concern.
|
||||
#
|
||||
# These are the Corporate Tools actions. They start already-registered,
|
||||
# agent-allowlisted tasks and are not a per-machine configuration concern, so a
|
||||
# policy that never mentions them must not remove them. Policy exists to shape
|
||||
# what a given PC TYPE exposes (which monitors, which service primitives); it is
|
||||
# not the authority on whether an admin may run a corporate tool.
|
||||
# Membership here is a statement about the action's nature, not its risk. An
|
||||
# action belongs in this set when Configuration Policy has nothing meaningful to
|
||||
# say about it: it invokes an already-registered, agent-allowlisted task rather
|
||||
# than describing how a machine should be shaped. Policy exists to shape what a
|
||||
# given PC TYPE exposes - which monitors run, which service primitives are
|
||||
# reachable - so a policy that never mentions such an action must not be read as
|
||||
# removing it.
|
||||
#
|
||||
# This is deliberately narrow. Do not add an action here merely because a denial
|
||||
# is inconvenient; the correct remedy for an over-narrow policy is to fix the
|
||||
# policy, or to use the audited admin break-glass override at the enqueue route.
|
||||
#
|
||||
# Without this exemption the intersection at the end of ALLOWED_ACTIONS_FOR
|
||||
# silently drops these actions on any endpoint whose effective policy is
|
||||
# non-empty, producing "Action not permitted by policy for this endpoint" even
|
||||
# for a caller holding endpoints.deploy. The real gate for these stays
|
||||
# ELEVATED_ACTION_PERMISSIONS (role), enforced in the enqueue route.
|
||||
# for a caller who holds the matching grant. Exemption from POLICY is not
|
||||
# exemption from PERMISSION: each of these actions still carries its own entry
|
||||
# in ELEVATED_ACTION_PERMISSIONS, enforced per-action in the enqueue route
|
||||
# before policy is ever consulted.
|
||||
POLICY_EXEMPT_ACTIONS = frozenset({
|
||||
'scheduledtask_run',
|
||||
# Read-only telemetry refresh. Policy shapes WHAT a PC type exposes; asking
|
||||
# an agent to report its existing state off-cadence changes nothing about
|
||||
# the machine, so a policy that never mentions it must not be read as
|
||||
# removing it. Without this, "Refresh Status" dies on every endpoint whose
|
||||
# policy is non-empty - a denial no operator can act on, because the fix
|
||||
# lives in a policy that was never about this action.
|
||||
'collect_now',
|
||||
})
|
||||
|
||||
|
||||
@@ -330,9 +350,15 @@ def ALLOWED_ACTIONS_FOR(pctype=None, assetid=None):
|
||||
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. Actions in POLICY_EXEMPT_ACTIONS are never narrowed away;
|
||||
they are gated by role alone. Policy resolution is imported lazily to keep
|
||||
this module free of a hard dependency on the computers plugin.
|
||||
a site opts in. Actions in POLICY_EXEMPT_ACTIONS are never narrowed away,
|
||||
because policy is not the authority on them; they remain gated by their own
|
||||
entry in ELEVATED_ACTION_PERMISSIONS at the enqueue route. Policy resolution
|
||||
is imported lazily to keep this module free of a hard dependency on the
|
||||
computers plugin.
|
||||
|
||||
This answers allowlist questions only. It does not consult desired-state
|
||||
holds, and it is not a permission check - callers must still enforce
|
||||
ELEVATED_ACTION_PERMISSIONS themselves.
|
||||
"""
|
||||
base = set(COMMAND_ALLOWLIST.keys())
|
||||
if assetid is None:
|
||||
@@ -355,8 +381,9 @@ def ALLOWED_ACTIONS_FOR(pctype=None, assetid=None):
|
||||
# "not permitted by policy". Expand each monitor:<id> to its kind's control
|
||||
# actions before intersecting.
|
||||
allowed = allowed | _monitor_control_actions(allowed)
|
||||
# Role-gated actions are added back unconditionally: policy narrows the
|
||||
# per-endpoint surface, but it does not own the corporate tools.
|
||||
# Exempt actions are added back unconditionally: policy narrows the
|
||||
# per-endpoint surface, but it is not the authority on these actions. Their
|
||||
# own elevated permission still gates them in the enqueue route.
|
||||
allowed = allowed | POLICY_EXEMPT_ACTIONS
|
||||
# Never widen past the code-level allowlist: policy can only gate within it.
|
||||
return base & allowed
|
||||
@@ -393,3 +420,256 @@ def _monitor_control_actions(action_names):
|
||||
granted |= {'service_start', 'service_stop', 'service_status'}
|
||||
return granted
|
||||
|
||||
|
||||
def PLACE_POLICY_HOLD(assetid, action, reason, userid=None, username=None,
|
||||
minutes=None):
|
||||
"""Suspend desired-state reconciliation of one action on one endpoint.
|
||||
|
||||
Called after an admin break-glasses past a policy denial, or directly from
|
||||
the admin hold dialog. Without this, an override on a desired-mode action is
|
||||
undone by the next reconcile pass: the admin stops the service, the resolver
|
||||
sees drift, and the command comes straight back. Gate-mode overrides need no
|
||||
hold - nothing reverses them.
|
||||
|
||||
minutes=None takes DEFAULT_HOLD_MINUTES. minutes=0 places an INDEFINITE hold
|
||||
(expiresat null) that never clears itself and stands until released by hand.
|
||||
Nothing surfaces a stale indefinite hold, so it suppresses reconciliation of
|
||||
that action silently and forever - deliberate, but the sharpest edge here.
|
||||
|
||||
Idempotent on an action already actively held: re-holding returns True
|
||||
without stacking a second row. The multi-select picker makes "select all"
|
||||
natural, and duplicate rows would mean release had to be pressed once per
|
||||
hidden duplicate to actually resume policy.
|
||||
|
||||
Returns True when a hold is in place for the action afterwards. Resolved
|
||||
lazily against the computers plugin, matching ALLOWED_ACTIONS_FOR, so this
|
||||
module keeps no hard dependency on it: with the computers plugin absent
|
||||
there is no reconciliation to suppress, and False is the honest answer.
|
||||
"""
|
||||
try:
|
||||
from plugins.computers.models import (PolicyActionHold,
|
||||
DEFAULT_HOLD_MINUTES)
|
||||
from shopdb.api import db
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from sqlalchemy import or_
|
||||
|
||||
existing = (PolicyActionHold.query
|
||||
.filter(PolicyActionHold.assetid == assetid,
|
||||
PolicyActionHold.action == action,
|
||||
PolicyActionHold.isactive.is_(True),
|
||||
or_(PolicyActionHold.expiresat.is_(None),
|
||||
PolicyActionHold.expiresat > datetime.utcnow()))
|
||||
.first())
|
||||
if existing is not None:
|
||||
return True
|
||||
|
||||
if minutes is None:
|
||||
expiresat = datetime.utcnow() + timedelta(minutes=DEFAULT_HOLD_MINUTES)
|
||||
elif int(minutes) == 0:
|
||||
expiresat = None
|
||||
else:
|
||||
expiresat = datetime.utcnow() + timedelta(minutes=int(minutes))
|
||||
|
||||
hold = PolicyActionHold(
|
||||
assetid=assetid,
|
||||
action=action,
|
||||
expiresat=expiresat,
|
||||
createdbyuserid=userid,
|
||||
createdbyusername=username,
|
||||
reason=reason,
|
||||
)
|
||||
db.session.add(hold)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def ACTIVE_POLICY_HOLDS(assetid):
|
||||
"""The unexpired break-glass holds on one endpoint, newest first.
|
||||
|
||||
The read counterpart to PLACE_POLICY_HOLD, resolved lazily against the
|
||||
computers plugin for the same reason: with that plugin absent there is no
|
||||
reconciliation to suppress, so there are no holds and an empty list is the
|
||||
honest answer.
|
||||
|
||||
Expiry is filtered here rather than by a sweeper, matching the resolver, so
|
||||
a stalled job can never silently extend a hold. Expired rows stay in the
|
||||
table as the audit record; they are simply not reported as active.
|
||||
"""
|
||||
try:
|
||||
from plugins.computers.models import PolicyActionHold
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import or_
|
||||
|
||||
# Null expiresat is an indefinite hold and is always active, so it is
|
||||
# matched explicitly - a bare comparison would report it as gone while the
|
||||
# resolver still honours it, which is the worst kind of disagreement.
|
||||
rows = (PolicyActionHold.query
|
||||
.filter(PolicyActionHold.assetid == assetid,
|
||||
PolicyActionHold.isactive.is_(True),
|
||||
or_(PolicyActionHold.expiresat.is_(None),
|
||||
PolicyActionHold.expiresat > datetime.utcnow()))
|
||||
.all())
|
||||
# Sorted here rather than in SQL: NULLS FIRST is not portable across the
|
||||
# dialects this runs on. Indefinite holds sort ahead of every dated one,
|
||||
# then latest expiry first. Keyed on datetime.max rather than a numeric
|
||||
# fallback: datetime.min.timestamp() raises on Windows, and the placeholder
|
||||
# is never actually compared against a real date anyway - the leading flag
|
||||
# already separates the two groups.
|
||||
rows.sort(key=lambda row: (row.expiresat is None,
|
||||
row.expiresat or datetime.max),
|
||||
reverse=True)
|
||||
return [{
|
||||
'action': row.action,
|
||||
'expiresat': row.expiresat.isoformat() if row.expiresat else None,
|
||||
'reason': row.reason,
|
||||
'createdbyusername': row.createdbyusername,
|
||||
} for row in rows]
|
||||
|
||||
|
||||
def HOLDABLE_ACTIONS_FOR(assetid):
|
||||
"""Desired-mode actions on this endpoint, with their current hold state.
|
||||
|
||||
Only desired-mode actions are offered: a hold suspends desired-state
|
||||
reconciliation, so holding a gate-mode action would suspend nothing and the
|
||||
control would silently do nothing.
|
||||
|
||||
Returns [] when the computers plugin is absent or policies are off - with no
|
||||
reconciliation running there is nothing to hold, and an empty picker is the
|
||||
honest answer rather than a list of actions the hold would not affect.
|
||||
"""
|
||||
try:
|
||||
from plugins.computers.services.policyresolver import effective_policy_for
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
effective = effective_policy_for(assetid)
|
||||
held = effective.heldactions
|
||||
return [{
|
||||
'action': name,
|
||||
'held': name in held,
|
||||
} for name in sorted(effective.holdable_actions())]
|
||||
|
||||
|
||||
def RELEASE_POLICY_HOLD(assetid, action):
|
||||
"""End an active hold early, resuming reconciliation of one action.
|
||||
|
||||
Soft-deletes via isactive rather than dropping the row: the hold IS the
|
||||
audit record of what was suppressed and by whom, and deleting it on release
|
||||
would erase exactly the history worth reviewing. Both the resolver and
|
||||
ACTIVE_POLICY_HOLDS already filter on isactive, so clearing it is enough to
|
||||
resume reconciliation on the next resolve.
|
||||
|
||||
Returns the number of holds released, so a caller can tell "released" from
|
||||
"there was nothing to release".
|
||||
"""
|
||||
try:
|
||||
from plugins.computers.models import PolicyActionHold
|
||||
from shopdb.api import db
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import or_
|
||||
|
||||
# Indefinite holds must be releasable too. Without the null branch the one
|
||||
# kind of hold that never clears on its own would also be the one kind the
|
||||
# release button could not clear.
|
||||
rows = (PolicyActionHold.query
|
||||
.filter(PolicyActionHold.assetid == assetid,
|
||||
PolicyActionHold.action == action,
|
||||
PolicyActionHold.isactive.is_(True),
|
||||
or_(PolicyActionHold.expiresat.is_(None),
|
||||
PolicyActionHold.expiresat > datetime.utcnow()))
|
||||
.all())
|
||||
for row in rows:
|
||||
row.isactive = False
|
||||
if rows:
|
||||
db.session.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ACTIVE_LOCK_FOR(assetid):
|
||||
"""The endpoint lock standing on this asset, or None.
|
||||
|
||||
Unlike the hold helpers above there is no defensive cross-plugin import:
|
||||
endpointlocks belongs to THIS plugin, so if the import could fail the
|
||||
enqueue route calling it would not be running either.
|
||||
|
||||
No expiry filter, deliberately. A lock has no TTL - it is cleared by an
|
||||
admin or it stands. Anything that looks like an expiry check here would be
|
||||
a bug.
|
||||
"""
|
||||
from .models import EndpointLock
|
||||
|
||||
return (EndpointLock.query
|
||||
.filter(EndpointLock.assetid == assetid,
|
||||
EndpointLock.releasedat.is_(None))
|
||||
.order_by(EndpointLock.lockedat.desc())
|
||||
.first())
|
||||
|
||||
|
||||
def PLACE_ENDPOINT_LOCK(assetid, reason, userid=None, username=None):
|
||||
"""Quarantine one endpoint against non-admin commands.
|
||||
|
||||
Idempotent on the active lock: if one already stands this returns it
|
||||
unchanged rather than stacking a second row. Two active locks on one
|
||||
endpoint is not a state this table should represent, and the caller who
|
||||
"locked" a locked machine got the outcome they asked for either way.
|
||||
|
||||
The invariant is enforced here rather than by a unique constraint because
|
||||
released rows accumulate per asset as history, so uniqueness on assetid
|
||||
would reject the second lock in an endpoint's life.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from shopdb.api import db
|
||||
|
||||
from .models import EndpointLock
|
||||
|
||||
existing = ACTIVE_LOCK_FOR(assetid)
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
lock = EndpointLock(
|
||||
assetid=assetid,
|
||||
reason=reason,
|
||||
lockedbyuserid=userid,
|
||||
lockedbyusername=username,
|
||||
lockedat=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(lock)
|
||||
db.session.commit()
|
||||
return lock
|
||||
|
||||
|
||||
def RELEASE_ENDPOINT_LOCK(assetid, userid=None, username=None):
|
||||
"""Lift the quarantine, recording who lifted it.
|
||||
|
||||
Stamps releasedat rather than deleting the row: the lock IS the record that
|
||||
this machine was quarantined and why, and that record is most wanted after
|
||||
the lock is gone and no longer able to explain itself. Every read filters on
|
||||
releasedat, so stamping it is enough to restore normal command flow.
|
||||
|
||||
Returns the released lock, or None when there was nothing to release, so a
|
||||
caller can tell those two cases apart.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from shopdb.api import db
|
||||
|
||||
lock = ACTIVE_LOCK_FOR(assetid)
|
||||
if lock is None:
|
||||
return None
|
||||
|
||||
lock.releasedat = datetime.utcnow()
|
||||
lock.releasedbyuserid = userid
|
||||
lock.releasedbyusername = username
|
||||
db.session.commit()
|
||||
return lock
|
||||
|
||||
|
||||
Reference in New Issue
Block a user