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

@@ -0,0 +1,109 @@
"""The generated "required on all PCs" policy follows the app by appid.
The generated policy name embeds appname, so a name lookup orphaned the policy
on rename. These pin the appid lookup, rename+untick in one PUT, delete handling
of a customised ('kept') policy and of other policies naming the appid, and the
truthful note that the generated policy is not attached to a business policy.
"""
from shopdb.core.models import Application
def _policies():
from plugins.computers.models import ConfigurationPolicy
return ConfigurationPolicy.query
def _create_required(client, headers, name='Fleet App'):
response = client.post('/api/applications',
json={'appname': name, 'isrequired': True,
'acknowledgepolicy': True},
headers=headers)
assert response.status_code == 201, response.get_json()
return response.get_json()['data']
def test_created_response_says_the_policy_is_not_attached(client, db, auth_headers):
data = _create_required(client, auth_headers)
assert data['policyresult'] == 'created'
assert 'business policy' in data['policynote']
def test_ack_message_mentions_business_policy(client, db, auth_headers):
response = client.post('/api/applications',
json={'appname': 'Unacked', 'isrequired': True},
headers=auth_headers)
assert response.status_code == 400
assert 'business policy' in response.get_json()['data']['error']['message']
def test_rename_keeps_the_policy_and_renames_it(client, db, auth_headers):
data = _create_required(client, auth_headers, 'Old Name')
response = client.put(f"/api/applications/{data['appid']}",
json={'appname': 'New Name'}, headers=auth_headers)
assert response.status_code == 200, response.get_json()
names = [policy.name for policy in _policies().all()]
assert names == ['Required app: New Name']
def test_untick_after_rename_removes_the_policy(client, db, auth_headers):
data = _create_required(client, auth_headers, 'Before')
from plugins.computers.models import ConfigurationPolicy
# Simulate a rename that bypassed the sync (older data): name is stale.
policy = ConfigurationPolicy.query.one()
application = db.session.get(Application, data['appid'])
application.appname = 'After'
db.session.commit()
assert policy.name == 'Required app: Before'
response = client.put(f"/api/applications/{data['appid']}",
json={'isrequired': False}, headers=auth_headers)
assert response.status_code == 200, response.get_json()
assert response.get_json()['data']['policyresult'] == 'removed'
assert _policies().count() == 0
def test_rename_and_untick_in_one_put_removes_the_policy(client, db, auth_headers):
data = _create_required(client, auth_headers, 'Combo')
response = client.put(f"/api/applications/{data['appid']}",
json={'appname': 'Combo Renamed', 'isrequired': False},
headers=auth_headers)
assert response.status_code == 200, response.get_json()
assert response.get_json()['data']['policyresult'] == 'removed'
assert _policies().count() == 0
def test_delete_deactivates_kept_and_referencing_policies(client, db, auth_headers):
from plugins.computers.models import (ConfigurationPolicy,
ConfigurationPolicyAction,
POLICY_SOURCE_LOCAL)
data = _create_required(client, auth_headers, 'Doomed')
generated = ConfigurationPolicy.query.one()
generated.source = POLICY_SOURCE_LOCAL # admin customised it
handmade = ConfigurationPolicy(name='Hand made push', scopejson=None)
db.session.add(handmade)
db.session.flush()
db.session.add(ConfigurationPolicyAction(
configurationpolicyid=handmade.configurationpolicyid,
action='update_app', params={'appid': data['appid']}))
unrelated = ConfigurationPolicy(name='Unrelated', scopejson=None)
db.session.add(unrelated)
db.session.commit()
response = client.delete(f"/api/applications/{data['appid']}",
json={'confirm': 'OK'}, headers=auth_headers)
assert response.status_code == 200, response.get_json()
body = response.get_json()
assert body['data']['policyresult'] == 'kept'
assert sorted(body['data']['deactivatedpolicies']) == \
['Hand made push', 'Required app: Doomed']
db.session.expire_all()
states = {policy.name: policy.isactive for policy in _policies().all()}
assert states == {'Required app: Doomed': False, 'Hand made push': False,
'Unrelated': True}

View File

@@ -121,7 +121,20 @@ EXEMPT_ENDPOINTS = {'knowledgebase.track_click', 'users.update_user',
# resolves to, so the key cannot ack another machine's alert.
# AUTHORING a fleet alert is the actual authority and stays
# permission-gated in the notifications plugin.
'endpoints.acknowledge_fleet_alert'}
'endpoints.acknowledge_fleet_alert',
# Agent enrollment. A PC with no credential asks for one on
# the shared collector key (same shape as the exempt
# collector blueprint); with the shared key switched off it
# takes no auth and only collects a credential an admin
# already approved for that hostname, serial and nonce.
# Approving, rejecting and revoking ARE admin-gated and
# ARE swept.
'endpoints.enroll_endpoint',
# Agent telemetry ingest under the endpoints prefix. The
# same handler as POST /api/collector/endpoints, whose
# blueprint is exempt: authenticated by the per-PC
# credential or the shared collector key.
'endpoints.agent_collect'}
@pytest.fixture(autouse=True)

View File

@@ -0,0 +1,28 @@
"""GET /api/plugins/settings-routes survives a plugin whose hook raises."""
def test_a_raising_plugin_is_skipped_not_fatal(app, client, db, monkeypatch):
manager = app.extensions.get('plugin_manager')
plugins = manager.get_all_plugins()
enabled = [name for name in plugins if manager.registry.is_enabled(name)]
assert len(enabled) >= 2
broken, healthy = enabled[0], enabled[1]
def explode():
raise RuntimeError('broken settings hook')
def contribute():
return [{'hub': 'model-catalog', 'path': 'probe', 'name': 'probe-route',
'tab': 'Probe', 'component': 'probe.vue'}]
monkeypatch.setattr(plugins[broken], 'get_settings_routes', explode,
raising=False)
monkeypatch.setattr(plugins[healthy], 'get_settings_routes', contribute,
raising=False)
response = client.get('/api/plugins/settings-routes')
assert response.status_code == 200, response.get_json()
names = [route['name'] for route in response.get_json()['data']['routes']]
assert 'probe-route' in names