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:
cproudlock
2026-09-19 11:24:40 -04:00
parent cb3975049c
commit 534f179ee6
675 changed files with 115759 additions and 60239 deletions

View File

@@ -7,13 +7,82 @@ from werkzeug.security import generate_password_hash
from shopdb.extensions import db
from shopdb.core.models import (
User, Role, Permission, AuditLog, full_permission_catalog,
guest_grantable_permissions)
guest_grantable_permissions, SCOPE_ENDPOINT_ACTIONS,
SCOPES_DENIED_ENDPOINT_ACTIONS)
from shopdb.utils.responses import success_response, error_response, ErrorCodes
from shopdb.utils.authz import require_role
users_bp = Blueprint('users', __name__)
def _check_scope_grants(rolenames, permissionnames):
"""Refuse direct grants a prebuilt scope is defined as never holding.
Returns an error_response, or None when the combination is allowed.
This is the server-side half of the scope dropdown, and it is the half that
is actually load-bearing. The UI greys out the endpoint action checkboxes
for a reporter, but a greyed-out checkbox is a suggestion: the same account
can be created with a restart grant by anyone willing to POST JSON. Reporter
was specified as holding no action capability EVEN IF expressly permitted,
and only a check on the write path can make that true.
Enforced here rather than in User.haspermission() on purpose. A subtractive
ceiling in the read predicate would sit in the hot path of every
permission-gated route in the app and change the meaning of a grant
everywhere, to fix a combination that should simply never have been stored.
Refusing the write is the narrow version: bad state cannot get in, and the
thousands of existing reads keep their current semantics.
Note this deliberately does NOT restrict the admin role, which bypasses
permission checks by rule, nor any site-created custom role. It constrains
only the scopes that were seeded with a documented promise about what they
hold.
"""
denied_scopes = SCOPES_DENIED_ENDPOINT_ACTIONS & set(rolenames)
if not denied_scopes:
return None
conflicts = sorted(set(permissionnames) & set(SCOPE_ENDPOINT_ACTIONS))
if not conflicts:
return None
scope = sorted(denied_scopes)[0]
return error_response(
ErrorCodes.VALIDATION_ERROR,
f"The {scope} scope cannot hold endpoint actions "
f"({', '.join(conflicts)}). Assign the technician or operator scope "
f"if this user needs to act on endpoints.")
def _resolve_directpermissions(names):
"""Resolve permission names to rows, rejecting any that do not exist.
Returns (permissions, error_response). A None permissions value with no
error means the caller did not mention direct grants at all, which is not
the same as sending an empty list - that clears them.
Unknown names are refused rather than dropped. Silently ignoring a typo
would report success while granting nothing, and the admin would believe
the capability was handed out.
"""
if names is None:
return None, None
if not isinstance(names, list):
return None, error_response(
ErrorCodes.VALIDATION_ERROR,
'directpermissions must be a list of permission names')
if not names:
return [], None
wanted = {str(n) for n in names}
permissions = Permission.query.filter(Permission.name.in_(wanted)).all()
missing = sorted(wanted - {p.name for p in permissions})
if missing:
return None, error_response(
ErrorCodes.VALIDATION_ERROR,
'Unknown permissions: ' + ', '.join(missing))
return permissions, None
@users_bp.route('', methods=['GET'])
@jwt_required()
@require_role('admin')
@@ -61,6 +130,28 @@ def create_user():
if User.query.filter_by(email=data['email']).first():
return error_response(ErrorCodes.CONFLICT, 'Email already exists', http_code=409)
# Resolve and VALIDATE roles and grants before touching the User object.
#
# Ordering is deliberate. Assigning user.roles first put the relationship
# into the session's autoflush path while the User itself was still
# unattached, which SQLAlchemy warned about ("Object of type <User> not in
# session, add operation along 'Role.users' won't proceed"). Nothing broke,
# because the refusal returns before db.session.add(). But it left a live
# trap: move or add a query below this point and the autoflush becomes a
# real write of a half-built user, surfacing later as an orphan row nobody
# can explain. Validate everything, then build.
role_ids = data.get('roles', [])
roles = Role.query.filter(Role.roleid.in_(role_ids)).all() if role_ids else []
permissions, err = _resolve_directpermissions(data.get('directpermissions'))
if err:
return err
err = _check_scope_grants(
[r.rolename for r in roles],
[p.name for p in (permissions or [])])
if err:
return err
# Admin-created accounts are forced to change the password on first login
# unless the admin explicitly opts out.
mustchange = data.get('mustchangepassword', True)
@@ -75,12 +166,13 @@ def create_user():
mustchangepassword=bool(mustchange)
)
# Assign roles
role_ids = data.get('roles', [])
if role_ids:
roles = Role.query.filter(Role.roleid.in_(role_ids)).all()
if roles:
user.roles = roles
# Direct per-user permission grants, held alongside (not instead of) roles.
if permissions is not None:
user.directpermissions = permissions
db.session.add(user)
# Audit log
@@ -181,6 +273,39 @@ def update_user(userid: int):
changes['roles'] = {'old': old_roles, 'new': new_roles}
user.roles = roles
# Direct grants are audited by NAME rather than id: the point of the
# audit row is to be readable years later, when a permission id means
# nothing to the person reading it.
if 'directpermissions' in data:
permissions, err = _resolve_directpermissions(
data['directpermissions'])
if err:
return err
old_direct = user.getdirectpermissionnames()
new_direct = sorted(p.name for p in (permissions or []))
if old_direct != new_direct:
changes['directpermissions'] = {
'old': old_direct, 'new': new_direct}
user.directpermissions = permissions or []
# Validate the COMBINATION, after both assignments and against the
# user's effective state rather than only what this request mentioned.
# A payload may change roles without mentioning grants, or grants
# without mentioning roles; checking only the supplied half would let a
# request that demotes an operator to reporter keep the restart grant
# they already held, which is exactly the state the scope promises is
# impossible. Reading back off `user` covers all three shapes.
#
# Safe to check after mutating because nothing has committed yet - the
# early return leaves the session to be rolled down by the request
# teardown, so a refused combination is never persisted.
err = _check_scope_grants(
[r.rolename for r in user.roles],
user.getdirectpermissionnames())
if err:
db.session.rollback()
return err
# Unlock user
if data.get('unlock'):
user.lockeduntil = None
@@ -237,6 +362,21 @@ def delete_user(userid: int):
# revoke their API tokens outright, and DETACH their audit history
# (userid -> NULL) - the log rows themselves are kept, entityname and
# details still tell the story.
#
# What a departing user leaves behind is deliberately NOT undone. Policies
# carry no FK to users, so configuration and business policies they authored
# keep working; the audit rows keep username, which is denormalized on
# auditlogs for exactly this reason. Leaving is not a reason to unpick
# someone's work.
#
# TODO (future): offer to EXPORT this user's audit history at the moment of
# removal, and on a significant scope reduction too. Detaching costs the
# userid link, so after this runs their trail is only reachable by matching
# the username string - which is fragile if the name is ever reused. An
# export taken at the point of change preserves the joined-up record while
# it still exists. Deactivating (isactive=False) instead of deleting keeps
# the userid link intact and is the better choice when the account may ever
# need to be audited in depth.
from shopdb.core.models import ApiToken
ApiToken.query.filter_by(userid=userid).delete(synchronize_session=False)
AuditLog.query.filter_by(userid=userid).update(
@@ -452,6 +592,14 @@ def user_to_dict(user: User) -> dict:
'lastlogindate': user.lastlogindate.isoformat() + 'Z' if user.lastlogindate else None,
'failedlogins': user.failedlogins,
'roles': [{'roleid': r.roleid, 'rolename': r.rolename, 'color': r.color} for r in user.roles],
# Split deliberately. directpermissions is what is STORED on the user and
# is what the editor's checkboxes bind to; permissions is the EFFECTIVE
# set including everything the roles supply, which is what a reader needs
# to answer "can this person do X". A checkbox bound to the effective set
# would appear ticked for a capability the user holds through a role, and
# unticking it would silently do nothing.
'directpermissions': user.getdirectpermissionnames(),
'permissions': sorted(user.getpermissions()),
'createddate': user.createddate.isoformat() + 'Z' if user.createddate else None,
'modifieddate': user.modifieddate.isoformat() + 'Z' if user.modifieddate else None
}