Give each endpoint its own credential and fix the review findings on the server

Per-PC credentials (replaces the 09-14 client-certificate attempt):
- POST /api/endpoints/enroll issues a credential to a PC that matches exactly
  one computer by hostname and BIOS serial and has none yet. Anything else
  (unknown or duplicate hostname, serial mismatch, already enrolled) waits as
  a request an admin approves or rejects. The agent's persisted nonce binds an
  approved request to the PC that asked.
- One auth helper serves every agent route. With X-Endpoint-Credential the
  asset comes from the credential and a request naming another PC gets 403
  ASSET_MISMATCH. The shared key still works for PCs that have not enrolled,
  is refused (401 SHARED_KEY_REFUSED) for any PC that has, and can be switched
  off. A revoked credential gets 401 CREDENTIAL_INVALID so the agent
  re-enrolls.
- The core collector accepts the credential for the computers, printers and
  endpoints collectors through two new plugin hooks exposed on shopdb.api
  (contract 0.33.0), and refuses the shared key for enrolled PCs.
- Admin API: enrollment list, approve, reject, revoke (un-enroll), settings.
  Migration API: per-PC readiness with blockers, and upgrade waves that
  package the agent once and queue the existing agent upgrade per PC.
- Migration 0023 creates endpointcredentials, endpointenrollrequests and
  endpointmigrationwaves, drops the certificate columns from assets where
  test databases have them, and renames app_fingerprint to appfingerprint.
  0021 and 0022 keep their ids but no longer alter the core assets table.
- Removed: client_cert.py, certificate renewal, the unauthenticated
  /test/client-cert route, nginx client certificate forwarding and the agent
  certificate script. The client-cert header could be forged on IIS, the key
  was readable by users, and the shared key remained a fallback.
- GET /settings/server-cert returns the SPKI SHA-256 pin for GE-Enforce.

Review fixes:
- report_command_result used g without importing it; every result was a 500.
- collect_log refuses setup answer files, appsettings, agent directories and
  key files at enqueue.
- Fleet alerts: alerttimeout and alertfleet agree with the migration, the
  scope is validated and a malformed scope no longer reaches the whole fleet,
  and the ack race no longer raises NameError.
- A refused break-glass override leaves no hold and no audit row.
- Agent upgrade checks locks and permissions before repackaging, and writes
  the package atomically.
- Server certificate upload validates the pair before replacing files;
  generation no longer builds an openssl config from user input; audit rows
  are actually written.
- Health evaluation runs in a savepoint so a caught error cannot lose the
  check-in.
- Required-app policies are found by appid, survive renames, and deleting an
  app deactivates policies that still name it. The UI and API now say such a
  policy only takes effect inside a business policy.
- Backfill handles duplicate fingerprints and rolls back a failed batch.
- Plugin settings routes skip a plugin whose hook raises.
- The setup token is no longer printed to the log.
- The naming gate checks top-level files again and handles odd file names.
- Removed root scratch scripts, one of which carried a token.
- Rewrote the fleet alert scheduling and app delta tests on real fixtures.
This commit is contained in:
cproudlock
2026-09-15 12:03:53 -04:00
parent f484be8a33
commit 7480e4fe3a
58 changed files with 4485 additions and 2032 deletions

View File

@@ -11,7 +11,7 @@ from flask_jwt_extended import jwt_required
from shopdb.api import db, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query
from ..models import Notification, NotificationType
from ..models.notification import _utc_iso
from ..models.notification import _utc_iso, ALERT_SCOPE_KEYS
from shopdb.api import require_permission, Setting, intarg
@@ -405,6 +405,69 @@ def get_notification(notification_id: int):
return success_response(n.to_dict())
def _clean_alert_fields(data):
"""Validate and normalise alertfleet / alertscope / alerttimeout.
Returns (fields, error). fields holds only the keys present in data, with
null coerced to the column default. alertscope must be a JSON object (or a
string holding one) whose keys the endpoint matcher understands; empty or
null means the whole fleet.
"""
import json
fields = {}
if 'alertfleet' in data:
value = data['alertfleet']
if value is None:
value = False
if not isinstance(value, bool):
return None, 'alertfleet must be true or false'
fields['alertfleet'] = value
if 'alerttimeout' in data:
value = data['alerttimeout']
if value is None or value == '':
value = 0
if isinstance(value, bool):
return None, 'alerttimeout must be a whole number of seconds'
try:
value = int(value)
except (TypeError, ValueError):
return None, 'alerttimeout must be a whole number of seconds'
if value < 0:
return None, 'alerttimeout must not be negative'
fields['alerttimeout'] = value
if 'alertscope' in data:
scope = data['alertscope']
if isinstance(scope, str):
if not scope.strip():
scope = None
else:
try:
scope = json.loads(scope)
except ValueError:
return None, 'alertscope must be a JSON object'
if scope is not None:
if not isinstance(scope, dict):
return None, 'alertscope must be a JSON object'
unknown = sorted(set(scope) - ALERT_SCOPE_KEYS)
if unknown:
return None, (f'alertscope has unknown key(s): {", ".join(unknown)}. '
f'Allowed: {", ".join(sorted(ALERT_SCOPE_KEYS))}')
for key, wanted in scope.items():
values = wanted if isinstance(wanted, list) else [wanted]
if any(v is not None and not isinstance(v, (str, int, float))
or isinstance(v, bool) for v in values):
return None, (f'alertscope.{key} must be a string or a list '
f'of strings')
if not scope:
scope = None
fields['alertscope'] = scope
return fields, None
@notifications_bp.route('', methods=['POST'])
@require_permission('notifications.create')
def create_notification():
@@ -419,6 +482,10 @@ def create_notification():
if not notification_text:
return error_response(ErrorCodes.VALIDATION_ERROR, 'notification/message is required')
alert_fields, alert_error = _clean_alert_fields(data)
if alert_error:
return error_response(ErrorCodes.VALIDATION_ERROR, alert_error)
# Parse dates
starttime = datetime.now(timezone.utc).replace(tzinfo=None)
if data.get('starttime') or data.get('startdate'):
@@ -456,9 +523,9 @@ def create_notification():
isshopfloor=data.get('isshopfloor', False),
employeesso=data.get('employeesso'),
employeename=data.get('employeename'),
alertfleet=data.get('alertfleet', False),
alertscope=data.get('alertscope'),
alerttimeout=data.get('alerttimeout', 0)
alertfleet=alert_fields.get('alertfleet', False),
alertscope=alert_fields.get('alertscope'),
alerttimeout=alert_fields.get('alerttimeout', 0)
)
db.session.add(n)
@@ -507,12 +574,12 @@ def update_notification(notification_id: int):
n.employeesso = data['employeesso']
if 'employeename' in data:
n.employeename = data['employeename']
if 'alertfleet' in data:
n.alertfleet = data['alertfleet']
if 'alertscope' in data:
n.alertscope = data['alertscope']
if 'alerttimeout' in data:
n.alerttimeout = data['alerttimeout']
alert_fields, alert_error = _clean_alert_fields(data)
if alert_error:
db.session.rollback()
return error_response(ErrorCodes.VALIDATION_ERROR, alert_error)
for field, value in alert_fields.items():
setattr(n, field, value)
# Parse and update dates
if 'starttime' in data or 'startdate' in data:

View File

@@ -7,6 +7,12 @@ from shopdb.api import db
_DEFAULT_TZ = 'America/New_York'
# Keys a fleet alert's alertscope may use. Must stay equal to the set the
# endpoints matcher (_ALERT_SCOPE_KEYS in plugins/endpoints/api/routes.py)
# understands; a test pins the two together.
ALERT_SCOPE_KEYS = frozenset({'hostname', 'assettype', 'computertype',
'location', 'businessunit'})
def _site_zone():
"""Site-configured IANA zone (settings key site_timezone) for calendar day
@@ -146,9 +152,12 @@ class Notification(db.Model):
# ~11 people are listed.
employeesso = db.Column(db.Text, nullable=True)
employeename = db.Column(db.Text, nullable=True)
alertfleet = db.Column(db.Boolean, default=False)
# Matches migration 0006: NOT NULL with server defaults.
alertfleet = db.Column(db.Boolean, nullable=False, default=False,
server_default=db.false())
alertscope = db.Column(db.JSON, nullable=True)
alerttimeout = db.Column(db.Integer, nullable=True)
alerttimeout = db.Column(db.Integer, nullable=False, default=0,
server_default='0')
# Relationships
notificationtype = db.relationship('NotificationType', backref='notifications')