test: reproduce native import retention without managed caller

This commit is contained in:
Joseph Doherty
2026-11-10 17:39:00 -05:00
parent 041189aa6d
commit 1298ecc194
14 changed files with 619 additions and 29 deletions
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""One fixed-200 native bridge import diagnostic; build/run only after review."""
import argparse
from collections import Counter
import hashlib
import json
import os
@@ -92,6 +93,72 @@ def wipe_owned(root):
shutil.rmtree(root)
def validate_operation(row):
if row['failed'] or row['fallbackCleanup'] or not row['privatePathVerified'] or not row['importStateReleased'] or row['logicalOwnersRemaining'] or row['modernErrorPresent'] or row['externalErrorPresent']:
raise RuntimeError('Native ownership/cleanup guard failed')
if any(row[k] for k in ['certStatus', 'createStatus', 'pathStatus', 'neverLockStatus', 'legacyStatus', 'moveStatus', 'copyCertStatus', 'deleteStatus', 'modernErrorCode', 'externalErrorCode']) or any(row[k] != 1 for k in ['certReturn', 'modernReturn', 'externalReturn', 'legacyReturn', 'moveReturn']):
raise RuntimeError('Native bridge statuses failed')
leaf_check = row['iteration'] in [1, 200]
if row['leafIdentityChecked'] != leaf_check or row['leafIdentityMatches'] != leaf_check:
raise RuntimeError('First/last native identity checks failed')
copies = row['copies']
if [c['stage'] for c in copies] != COPY_STAGES or any(c['status'] or c['returnedRef'] != c['privateAssociation'] for c in copies):
raise RuntimeError('Native wrapper-copy sequence/status/path failed')
# Independently reconstruct ownership from observed associations, with no fixed non-null pattern.
actions = ['track', 'lookup', 'untrack', 'track', 'track', 'track', 'untrack', 'untrack', 'untrack']
items = ['original', None, 'original', 'original', 'identity', 'copied', 'original', 'copied', 'identity']
tracked = {'original': False, 'copied': False, 'identity': False}
logical = 0
native_owner = False
deletion = None
live_at_delete = None
for index, (copy, action, item) in enumerate(zip(copies, actions, items)):
if index == 1: # Fresh native keychain created between DER TrackItem and Move wrapper.
logical = 1
native_owner = True
if index == 7: # Initial import state releases after disposing the original certificate.
if row['importOwnersBefore'] != logical or not native_owner:
raise RuntimeError('Initial import owner release was misplaced')
logical -= 1
if row['importOwnersAfter'] != logical or logical < 0:
raise RuntimeError('Initial import owner accounting failed')
if logical == 0:
deletion = 'release-import-state'
native_owner = False
live_at_delete = {'copy': False, 'originalCertificate': False, 'copiedCertificate': True,
'identity': True, 'legacyKey': True}
if copy['action'] != action or copy['logicalOwnersBefore'] != logical or copy['nativeOwnerBefore'] != native_owner:
raise RuntimeError('Native wrapper ownership before copy does not reconcile')
associated = copy['privateAssociation']
if action == 'track' and associated:
if tracked[item] or not native_owner:
raise RuntimeError('Track tried to duplicate or use a retired native owner')
tracked[item] = True
logical += 1
elif action == 'untrack':
if tracked[item]:
if not associated or not native_owner:
raise RuntimeError('Previously tracked item lost its association before Untrack')
tracked[item] = False
logical -= 1
if logical == 0:
if deletion is not None:
raise RuntimeError('Duplicate native deletion')
deletion = copy['stage']
native_owner = False
live_at_delete = {'copy': True, 'originalCertificate': index == 6, 'copiedCertificate': index in [6, 7],
'identity': True, 'legacyKey': True}
elif associated and native_owner:
raise RuntimeError('Untracked item would consume a still-registered owner')
if logical < 0 or copy['logicalOwnersAfter'] != logical or copy['nativeOwnerAfter'] != native_owner:
raise RuntimeError('Native wrapper ownership after copy does not reconcile')
if logical or native_owner or any(tracked.values()) or deletion is None or row['deleteStage'] != deletion or row['deleteLiveReferences'] != live_at_delete:
raise RuntimeError('Native logical owners or actual zero-owner delete stage did not reconcile')
expected_outputs = 8 + sum(c['returnedRef'] for c in copies) + int(leaf_check)
if row['ownedOutputs'] != expected_outputs or row['releasedOutputs'] != expected_outputs:
raise RuntimeError('Native returned CF ownership did not reconcile')
def main():
os.umask(0o077) # This collector and its children only; includes normal SDK seed PFX files.
parser = argparse.ArgumentParser(description=__doc__)
@@ -117,7 +184,7 @@ def main():
'repetitions': 200, 'stages': STAGES, 'idleSeconds': 5, 'fullSoakGate': False,
'managedCallerInMeasuredChild': False, 'managedPfxParsingEmulated': False,
'legacyKeyLifetime': 'Explicit CFRelease after identity disposal; managed local has no explicit using scope.',
'wrapperNativeCopyCallsPerOperation': 9, 'checkpointDeadlineSeconds': 180,
'wrapperNativeCopyCallsPerOperation': 9, 'logicalOwnersFromObservedPrivateAssociationsOnly': True, 'checkpointDeadlineSeconds': 180,
'deadlineScope': 'Checkpoint/child deadline; in-progress bounded probes and bounded reap add overhead.',
'defaultOrSearchListSetters': False, 'fixtureCreationUmask': '0077'}
save(output / 'provenance.json', provenance)
@@ -180,19 +247,16 @@ def main():
if status or len(rows) != 207 or len(operations) != 200 or len(fingerprints) != 2 or len(complete) != 1 or [r['iteration'] for r in operations] != list(range(1, 201)):
raise RuntimeError('Native fixed operation/completion counts failed')
for row in operations:
if row['failed'] or row['fallbackCleanup'] or not row['privatePathVerified'] or not row['deleteDuringFinalIdentityUntrack'] or row['logicalOwnersRemaining'] or row['modernErrorPresent'] or row['externalErrorPresent'] or row['ownedOutputs'] != row['releasedOutputs']:
raise RuntimeError('Native ownership order/cleanup failed')
if [c['stage'] for c in row['copies']] != COPY_STAGES or any(c['status'] for c in row['copies']) or [c['returnedRef'] for c in row['copies']] != [False] * 3 + [True] * 6:
raise RuntimeError('Native wrapper-copy sequence failed')
if any(row[k] for k in ['certStatus', 'createStatus', 'pathStatus', 'neverLockStatus', 'legacyStatus', 'moveStatus', 'copyCertStatus', 'deleteStatus', 'modernErrorCode', 'externalErrorCode']) or any(row[k] != 1 for k in ['certReturn', 'modernReturn', 'externalReturn', 'legacyReturn', 'moveReturn']):
raise RuntimeError('Native bridge statuses failed')
if sha(task / 'seed/leaf.der') != seeds[0]['leafSha256'] or complete[0]['operations'] != 200 or complete[0]['bridgeSha256'] != BRIDGE_SHA or complete[0]['ownedOutputs'] != complete[0]['releasedOutputs']:
validate_operation(row)
if sha(task / 'seed/leaf.der') != seeds[0]['leafSha256'] or complete[0]['operations'] != 200 or complete[0]['bridgeSha256'] != BRIDGE_SHA or complete[0]['ownedOutputs'] != sum(r['ownedOutputs'] for r in operations) or complete[0]['releasedOutputs'] != sum(r['releasedOutputs'] for r in operations) or complete[0]['createdRefs'] != 200 or complete[0]['releasedRefs'] != 200:
raise RuntimeError('Native identity/completion ownership guard failed')
if any(samples[-1][k] for k in ['ownedKeychainFdCount', 'ownedKeychainFileCount']):
raise RuntimeError('Private keychain files/descriptors retained')
save(output / 'result.json', {'status': 'passed', 'seed': seeds[0], 'samples': samples, 'fingerprints': fingerprints,
'complete': complete[0], 'wallSecondsIncludingProbes': time.monotonic() - started, 'fullSoakGate': False,
'nativeInventoryIsNotOpenHandlesOrExclusiveRss': True, 'measuredChildManagedRuntimePresent': False})
'nativeInventoryIsNotOpenHandlesOrExclusiveRss': True, 'measuredChildManagedRuntimePresent': False,
'actualDeletionStages': dict(Counter(r['deleteStage'] for r in operations)),
'returnedCopyReferencesByStage': {stage: sum(c['returnedRef'] for r in operations for c in r['copies'] if c['stage'] == stage) for stage in COPY_STAGES}})
finally:
reap(process)
finally: