fix: bind release receipts and external export ownership
This commit is contained in:
1 parent
b070837acb
commit
0440b2efbf
6 files changed
+262
-12
No files matched your search
@@ -100,6 +100,77 @@ def begin_export_analysis(library, root, project):
|
||||
return record['token']
|
||||
|
||||
|
||||
def _external_export_library(process):
|
||||
"""Recover a live copy's owner; an outside path alone proves no association."""
|
||||
import ntpath
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
from .failed_session import _command_args
|
||||
from .backup_recovery import _native_scope_match
|
||||
from .native_engineering_identity import _process_birth
|
||||
def read(path):
|
||||
info = path.lstat()
|
||||
if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT or info.st_size > 1024*1024:
|
||||
raise ValueError('Untrusted export association')
|
||||
value = json.loads(path.read_text('utf-8'))
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError('Invalid export association')
|
||||
return value
|
||||
try:
|
||||
birth = _process_birth(process.get('created'))
|
||||
image = process.get('executable')
|
||||
if birth is None or not image or ntpath.basename(image).casefold() != process['name'].casefold():
|
||||
return None
|
||||
candidates = []
|
||||
for arg in _command_args(process.get('command', ''))[1:]:
|
||||
path = Path(arg.split('=', 1)[-1])
|
||||
if path.is_absolute() and (path.suffix.casefold() in ('.prj', '.pcb')
|
||||
or path.name.casefold() in ('database', 'icdb.dat')):
|
||||
candidates.append(path)
|
||||
associations = set()
|
||||
for path in candidates:
|
||||
project_root = next((p for p in (path, *path.parents) if p.name.casefold() == 'project'), None)
|
||||
if project_root is None or project_root.resolve() != project_root:
|
||||
return None
|
||||
root = project_root.parent
|
||||
owner = read(root/'export-owner.json')
|
||||
project, library = Path(owner['project']), Path(owner['library'])
|
||||
if (owner.get('protocol') != 'cbb-native-export-analysis' or owner.get('version') != 1
|
||||
or not re.fullmatch('[0-9a-f]{32}', str(owner.get('token', '')))
|
||||
or not re.fullmatch('[0-9a-f]{32}', str(owner.get('lease_id', '')))
|
||||
or type(owner.get('supervisor_pid')) is not int or owner['supervisor_pid'] <= 0
|
||||
or Path(owner['analysis_root']) != root or project.parent != project_root
|
||||
or project.suffix.casefold() != '.prj' or not project.is_file()
|
||||
or not library.is_absolute() or library.suffix.casefold() != '.lmc' or not library.is_file()
|
||||
or root.is_relative_to(library.parent) or library.parent.is_relative_to(root)
|
||||
or _native_scope_match(process['command'], roots=(project_root,)) is not True):
|
||||
return None
|
||||
matched = False
|
||||
for kind, executable in (('ascii', 'icdb2ascii.exe'), ('csv', 'icdb2csv.exe'), ('edif', 'edifexporter.exe')):
|
||||
evidence = root/(kind+'-process.json')
|
||||
if not evidence.exists():
|
||||
continue
|
||||
recorded = read(evidence)
|
||||
command = recorded.get('command')
|
||||
if (recorded.get('native_started') is not True or recorded.get('kind') != kind
|
||||
or not isinstance(command, list) or not command or not all(isinstance(v, str) for v in command)
|
||||
or ntpath.basename(command[0]).casefold() != executable
|
||||
or _native_scope_match(subprocess.list2cmdline(command), roots=(project_root,)) is not True):
|
||||
continue
|
||||
for identity in recorded.get('process_identities', []):
|
||||
if (identity.get('pid') == process['pid'] and _process_birth(identity.get('created')) == birth
|
||||
and identity.get('executable')
|
||||
and ntpath.normcase(identity['executable']) == ntpath.normcase(image)):
|
||||
matched = True
|
||||
if not matched:
|
||||
return None
|
||||
associations.add(library.resolve())
|
||||
return next(iter(associations)) if len(associations) == 1 else None
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''):
|
||||
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
|
||||
@@ -116,11 +187,12 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
|
||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||
# Only the explicit release path supplies full-library/native proof and
|
||||
# archives the unchanged metadata while its coordination handle is held.
|
||||
from .library_lock import _owner_matches_scope
|
||||
if any(p['name'].casefold() in _OWNER_NAMES and
|
||||
_owner_matches_scope(p, library, (library.parent,)) is not False
|
||||
for p in _process_snapshot()):
|
||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||
for process in _process_snapshot():
|
||||
if process['name'].casefold() not in _OWNER_NAMES:
|
||||
continue
|
||||
associated_library = _external_export_library(process)
|
||||
if associated_library is None or associated_library == library:
|
||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||
yield []
|
||||
return
|
||||
if checkpoint is None or 'export_analysis' not in checkpoint:
|
||||
|
||||
@@ -67,6 +67,25 @@ def acknowledge_library_release(proof, snapshot, *, block_name=None):
|
||||
_retained_results.pop(path, None)
|
||||
|
||||
|
||||
def _proof_covers_session(proof, session):
|
||||
"""A receipt may acknowledge only resources actually covered by its proof."""
|
||||
scope = proof.get('resource_scope')
|
||||
library = session.get('library')
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED' or proof.get('lease_state') != 'RELEASED'
|
||||
or not isinstance(scope, dict) or scope.get('scope_state') != 'OBSERVED'
|
||||
or not library or _library_key(proof.get('library', '')) != _library_key(library)
|
||||
or _library_key(scope.get('library', '')) != _library_key(library)):
|
||||
return False
|
||||
if proof.get('proof_scope') == 'LIBRARY':
|
||||
return not scope.get('block_names') and not proof.get('proof_block_names')
|
||||
blocks = proof.get('proof_block_names')
|
||||
observed = scope.get('block_names')
|
||||
if (proof.get('proof_scope') not in ('BLOCK', 'BLOCKS') or not isinstance(blocks, list)
|
||||
or not blocks or not isinstance(observed, list) or blocks != observed):
|
||||
return False
|
||||
return bool(session.get('block') and session['block'] in blocks)
|
||||
|
||||
|
||||
def record_session_release(proof, records):
|
||||
"""Persist a past proof only for the pre-proof operation, never replay it."""
|
||||
errors = []
|
||||
@@ -78,7 +97,8 @@ def record_session_release(proof, records):
|
||||
path = Path(record['path'])
|
||||
session = read_session_record(path, evidence_root=path.parent)
|
||||
if (session['operation_id'] != record.get('operation_id')
|
||||
or Path(session['library']).resolve() != library):
|
||||
or Path(session['library']).resolve() != library
|
||||
or not _proof_covers_session(proof, session)):
|
||||
continue
|
||||
write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), {
|
||||
'operation_id': session['operation_id'], 'library': str(library),
|
||||
@@ -434,12 +454,10 @@ def discover_sessions(evidence_root, *, library=None):
|
||||
observation = read_session_record(Path(folder)/name, evidence_root=root)
|
||||
proof = observation.get('release_proof') or {}
|
||||
proof = proof if isinstance(proof, dict) else {}
|
||||
proof_scope = proof.get('resource_scope')
|
||||
session_scope = value.get('resource_scope')
|
||||
if observation['operation_id'] == value['operation_id'] and (
|
||||
observation.get('status') == 'RELEASED'
|
||||
and proof.get('lease_state') == 'RELEASED'
|
||||
and isinstance(proof_scope, dict) and proof_scope.get('scope_state') == 'OBSERVED'
|
||||
and _proof_covers_session(proof, value)
|
||||
or observation.get('status') == 'FINISHED'
|
||||
and isinstance(session_scope, dict) and session_scope.get('scope_state') == 'DECLARED'
|
||||
and observation.get('native_release_confirmed') is True
|
||||
|
||||
Reference in new issue
Block a user