Files
shopdb-flask/tests/test_plugins/test_endpoints_app_conflict.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

166 lines
6.2 KiB
Python

"""A concurrent application insert must not sink the whole check-in.
The unique index on (assetid, appfingerprint) detects a second writer inserting
the same application row; it does not resolve one. Before the savepoint went in,
the IntegrityError from the insert flush escaped generic_collect, reached the
global handler, rolled back the WHOLE check-in - state, events and hardware -
and answered the agent with operator-facing 409 form copy.
The insert now behaves like the delete-count mismatch beside it: warn, keep the
telemetry, and let the next check-in (which reports the full list again) settle
the inventory.
"""
import hashlib
from sqlalchemy.exc import IntegrityError
from shopdb.core.models import Asset, AssetType
from plugins.endpoints.models import (
EndpointApplication, EndpointEvent, EndpointState,
)
from plugins.endpoints.plugin import EndpointsPlugin
def _fingerprint(name, version, publisher):
data = '{}|{}|{}'.format(name or '', version or '', publisher or '')
return hashlib.sha256(data.encode('utf-8')).hexdigest()
def _computer(db, hostname):
from plugins.computers.models import Computer
assettype = AssetType.query.filter_by(assettype='computer').first()
if assettype is None:
assettype = AssetType(assettype='computer')
db.session.add(assettype)
db.session.flush()
asset = Asset(assetnumber=hostname, name=hostname,
assettypeid=assettype.assettypeid, isactive=True)
db.session.add(asset)
db.session.flush()
db.session.add(Computer(assetid=asset.assetid, hostname=hostname))
db.session.commit()
return asset.assetid
def _payload(hostname, applications):
return {
'hostname': hostname,
'pendingreboot': True,
'applications': applications,
'events': [{
'eventid': 4625,
'eventrecordid': 501,
'eventchannel': 'Security',
'eventsource': 'Microsoft-Windows-Security-Auditing',
'eventmessage': 'Failed logon',
}],
}
def test_insert_conflict_keeps_the_checkin(db, monkeypatch):
"""A REAL IntegrityError on the insert flush leaves the check-in intact.
The first (bulk) insert adds a genuine duplicate row, so the flush raises on
the unique index exactly as a concurrent check-in would make it. The
reconcile then re-reads and re-inserts, and state plus events still commit.
"""
assetid = _computer(db, 'APPRACE01')
plugin = EndpointsPlugin()
real_insert = EndpointsPlugin._insert_applications
calls = []
def conflicting_insert(assetid_arg, incoming, fingerprints):
rows = real_insert(assetid_arg, incoming, fingerprints)
calls.append(list(fingerprints))
if len(calls) == 1:
# The conflicting row a second writer would have committed.
first = rows[0]
db.session.add(EndpointApplication(
assetid=first.assetid,
displayname=first.displayname,
displayversion=first.displayversion,
publisher=first.publisher,
appfingerprint=first.appfingerprint,
))
return rows
monkeypatch.setattr(EndpointsPlugin, '_insert_applications',
staticmethod(conflicting_insert))
applications = [
{'displayname': 'Alpha', 'displayversion': '1.0', 'publisher': 'ACME',
'fingerprint': _fingerprint('Alpha', '1.0', 'ACME')},
{'displayname': 'Beta', 'displayversion': '2.0', 'publisher': 'ACME',
'fingerprint': _fingerprint('Beta', '2.0', 'ACME')},
]
result = plugin.apply_collector_payload(_payload('APPRACE01', applications))
db.session.commit()
# The collision was detected and reported rather than raised.
assert len(calls) > 1, 'the bulk insert should have collided and reconciled'
assert any('application insert conflict' in w for w in result['warnings'])
# The telemetry the check-in carried is still there.
state = EndpointState.query.filter_by(assetid=assetid).first()
assert state is not None
assert state.pendingreboot is True
assert state.lastreportedat is not None
assert EndpointEvent.query.filter_by(assetid=assetid).count() == 1
# And the inventory reconciled rather than being abandoned.
stored = {row.appfingerprint for row
in EndpointApplication.query.filter_by(assetid=assetid).all()}
assert stored == {app['fingerprint'] for app in applications}
def test_reconcile_skips_fingerprints_that_now_exist(db):
"""Reconcile inserts only what is missing and counts the rest as skipped."""
assetid = _computer(db, 'APPRACE02')
plugin = EndpointsPlugin()
taken = _fingerprint('Alpha', '1.0', 'ACME')
missing = _fingerprint('Beta', '2.0', 'ACME')
db.session.add(EndpointApplication(
assetid=assetid, displayname='Alpha', displayversion='1.0',
publisher='ACME', appfingerprint=taken))
db.session.commit()
incoming = {
taken: {'displayname': 'Alpha', 'displayversion': '1.0',
'publisher': 'ACME'},
missing: {'displayname': 'Beta', 'displayversion': '2.0',
'publisher': 'ACME'},
}
warnings = []
stored = plugin._reconcile_applications(assetid, incoming,
[taken, missing], warnings)
db.session.commit()
assert stored == 1
assert warnings == ['application insert conflict: stored 1, skipped 1 '
'of 2 new (concurrent update?)']
rows = EndpointApplication.query.filter_by(assetid=assetid).all()
assert len(rows) == 2
assert {r.appfingerprint for r in rows} == {taken, missing}
def test_the_unique_index_is_really_there(db):
"""The whole fix rests on the constraint raising. Prove it does."""
assetid = _computer(db, 'APPRACE03')
fingerprint = _fingerprint('Alpha', '1.0', 'ACME')
for _ in range(2):
db.session.add(EndpointApplication(
assetid=assetid, displayname='Alpha', displayversion='1.0',
publisher='ACME', appfingerprint=fingerprint))
raised = False
try:
db.session.flush()
except IntegrityError:
raised = True
db.session.rollback()
assert raised, 'endpointapplications has no unique (assetid, appfingerprint)'