Files
shopdb-flask/plugins/computers/services/policyscope.py
cproudlock 534f179ee6 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.
2026-09-19 11:24:40 -04:00

120 lines
5.1 KiB
Python

"""Boolean scope evaluation for Configuration Policies.
A policy's scopejson is a small typed boolean AST over two endpoint dimensions,
PC type and installed application. This module is the ONLY place that interprets
that AST: it validates the shape (known node types, bounded depth) and evaluates
a validated tree against a resolved endpoint context.
Node grammar (all dict nodes carry a "type"):
{"type": "and", "nodes": [<node>, ...]}
{"type": "or", "nodes": [<node>, ...]}
{"type": "not", "node": <node>}
{"type": "pctype", "id": <computertypeid:int>}
{"type": "app", "id": <appid:int>}
{"type": "allpcs"} # every PC EXCEPT those whose type is designated a server
{"type": "true"} # matches everything, servers included
"allpcs" vs "true": authoring an estate-wide policy almost always means "every
PC an operator sits at", not "every computer we have a row for". Those differ by
the servers, where a reboot or a script push is a materially different event.
"true" is retained because a stored scope of None is equivalent to it and older
policies were written with it, but the builder offers "All PCs" instead.
Server designation is read from the computer type's ICON slug ('server'). That
field is nominally a UI hint, which is a real wart - it is load-bearing here. It
was chosen over matching the type NAME because a site can rename "Server" but a
renamed type keeps its icon, and over a new isserver column because that needs a
migration this did not warrant. If server designation ever becomes a first-class
flag, this is the single place that reads it.
Kept pure and dependency-free (no db, no Flask) so it is trivially unit-tested
and so a future GE-Enforce assembly engine can reuse the exact same evaluator on
the exact same AST when it composes policies.
"""
# Bound the tree so a hand-crafted or imported AST cannot cause pathological
# recursion. Ten levels is far past any policy a human would author.
MAX_SCOPE_DEPTH = 10
# The computer-type icon slug that designates a type as a server. See the module
# docstring for why the icon carries this.
SERVER_ICON = 'server'
_LOGICAL = {'and', 'or', 'not'}
_LEAF = {'pctype', 'app', 'true', 'allpcs'}
class ScopeError(ValueError):
"""Raised when a scope AST is malformed. Carries a human-readable reason."""
def validate_scope(node, _depth=0):
"""Validate a scope AST, raising ScopeError on any problem.
Returns None on success. Call this at write time (CRUD) so a bad tree never
reaches the database; evaluate_scope then trusts the stored shape.
"""
if _depth > MAX_SCOPE_DEPTH:
raise ScopeError(f'scope nested deeper than {MAX_SCOPE_DEPTH} levels')
if not isinstance(node, dict):
raise ScopeError('scope node must be an object')
ntype = node.get('type')
if ntype not in _LOGICAL and ntype not in _LEAF:
raise ScopeError(f'unknown scope node type: {ntype!r}')
if ntype in ('and', 'or'):
nodes = node.get('nodes')
if not isinstance(nodes, list) or not nodes:
raise ScopeError(f'{ntype} requires a non-empty "nodes" list')
for child in nodes:
validate_scope(child, _depth + 1)
elif ntype == 'not':
child = node.get('node')
if child is None:
raise ScopeError('not requires a "node"')
validate_scope(child, _depth + 1)
elif ntype in ('pctype', 'app'):
ident = node.get('id')
if not isinstance(ident, int) or isinstance(ident, bool):
raise ScopeError(f'{ntype} requires an integer "id"')
# 'true' and 'allpcs' carry no payload.
def evaluate_scope(node, context):
"""Evaluate a validated scope AST against an endpoint context.
context is expected to expose:
context['computertypeid'] -> int or None
context['appids'] -> set/collection of installed appids
context['isserver'] -> bool, whether the type is server-designated
Returns True when the endpoint falls in scope. An empty/None scope means the
policy is unscoped and matches everything (same as {"type": "true"}), which
keeps a freshly-created policy usable before a scope is drawn.
"""
if node is None:
return True
ntype = node['type']
if ntype == 'true':
return True
if ntype == 'allpcs':
# Absent designation means "not a server": an endpoint with no type set
# is an ordinary PC until something says otherwise.
return not context.get('isserver', False)
if ntype == 'and':
return all(evaluate_scope(child, context) for child in node['nodes'])
if ntype == 'or':
return any(evaluate_scope(child, context) for child in node['nodes'])
if ntype == 'not':
return not evaluate_scope(node['node'], context)
if ntype == 'pctype':
return context.get('computertypeid') == node['id']
if ntype == 'app':
return node['id'] in (context.get('appids') or ())
# validate_scope should have caught this; be strict rather than silently
# matching an endpoint against an unknown node.
raise ScopeError(f'unknown scope node type at evaluation: {ntype!r}')