Files
cbb-refresh-verify-795/src/cbb_refresh_verify/management_transaction.py
T

125 lines
7.0 KiB
Python

"""Prepared Add authority bound to the engine checkpoint, baseline and live lease."""
import json
import os
from pathlib import Path
import threading
from uuid import uuid4
from .management import _write_json, engineering_identity
from .scoped_manifest import build_manifest
def _read(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def fixture_authority(root, library, token):
root = Path(root).resolve()
expected = root/'native-add/fixture/mentor_lib.lmc'
owner = _read(root/'probe-owner.json')
if (not token or owner.get('token') != token or not expected.is_file()
or Path(library).resolve() != expected.resolve()
or Path(owner.get('library', '')).resolve() != expected.resolve()):
raise ValueError('Management research requires the exact newly created owned fixture.')
return {'root': str(root), 'token': token}
def current_lease(library):
from .library_lock import LibraryLock, _library_guard, _owners, blocker_path, checkpoint_record
lease = LibraryLock(library)
with _library_guard(lease.key):
owner = _owners.get(lease.key)
guard = checkpoint_record(blocker_path(library))
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
or guard is None or guard['pid'] != os.getpid()
or guard['status'] != 'OPERATION_IN_PROGRESS'
or owner['lease_id'] != guard['lease_id']
or Path(guard['library']).resolve() != Path(library).resolve()):
raise ValueError('Management transaction requires the current thread exact active library lease.')
return {'lease_id': owner['lease_id'], 'lease_handle': int(owner['handle']), 'supervisor_pid': os.getpid()}
def _authorize(record, mentor_home):
fixture = record.get('fixture')
if fixture is not None:
fixture_authority(fixture['root'], record['library'], fixture['token'])
else:
from .native_management import NativeManagementAdapter
capability = NativeManagementAdapter(mentor_home=mentor_home).capabilities()['add']
if not capability.supported: raise ValueError(capability.reason)
def prepare_transaction(request, root, expected_identity, *, mentor_home, fixture=None):
root = Path(root).resolve()
source = Path(request.source).resolve()
if source.parent != root/'source':
raise ValueError('Native Add accepts only the management engine staged source.')
library = Path(request.library).resolve()
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('Management transaction evidence overlaps the target library.')
checkpoint = _read(root/'checkpoint.json')
stages = {item['stage'] for item in checkpoint.get('history', [])}
if (checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'prepare_identity'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != request.name or checkpoint['partition'] != request.partition
or not {'baseline', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine baseline/staging checkpoint.')
library_baseline = _read(root/'library-baseline-manifest.json')
baseline = _read(root/'source-identity/identity.json')
if baseline.get('safe_to_continue') is not True or baseline.get('identity') != expected_identity:
raise ValueError('Native source identity evidence is missing or changed.')
record = {**current_lease(library), 'nonce': uuid4().hex, 'library': str(library),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_name': source.name, 'source_identity': engineering_identity(source),
'source_manifest': build_manifest(source.parent), 'library_baseline': library_baseline,
'expected_identity': expected_identity, 'fixture': fixture}
_authorize(record, mentor_home)
_write_json(root/'native-add-prepared.json', record)
return record['nonce']
def validate_transaction(job, root, *, check_source=True):
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive
import win32api, win32con, win32file
root = Path(root).resolve()
record = _read(root/'native-add-prepared.json')
library = Path(job['library']).resolve()
source = root/'source'/record['source_name']
guard = checkpoint_record(blocker_path(library))
checkpoint = _read(root/'checkpoint.json')
if (not job.get('transaction_nonce') or job['transaction_nonce'] != record['nonce']
or Path(record['library']).resolve() != library
or any(job.get(key) != record[key] for key in ('name', 'partition', 'top_level_block', 'source_identity'))
or source.parent != root/'source' or source.resolve().parent != (root/'source').resolve()
or Path(job['source']).resolve() != source.resolve()
or guard is None or guard['lease_id'] != record['lease_id']
or guard['pid'] != record['supervisor_pid'] or guard['pid'] != job['supervisor_pid']
or guard['status'] != 'OPERATION_IN_PROGRESS'
or Path(guard['library']).resolve() != library or not _supervisor_alive(guard['pid'])
or checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'native_add'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != record['name'] or checkpoint['partition'] != record['partition']):
raise ValueError('Native Add transaction authority is missing, stale or foreign.')
_authorize(record, job['mentor_home'])
baseline = _read(root/'source-identity/identity.json')
if (baseline.get('safe_to_continue') is not True or baseline.get('identity') != record['expected_identity']
or _read(root/'library-baseline-manifest.json') != record['library_baseline']
or check_source and (build_manifest(source.parent) != record['source_manifest']
or engineering_identity(source) != record['source_identity'])):
raise ValueError('Native Add library baseline or staged source proof changed.')
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, record['supervisor_pid'])
duplicate = None
try:
duplicate = win32api.DuplicateHandle(process, record['lease_handle'], win32api.GetCurrentProcess(),
0, False, win32con.DUPLICATE_SAME_ACCESS)
final_path = win32file.GetFinalPathNameByHandle(duplicate, 0)
if final_path.startswith('\\\\?\\UNC\\'): final_path = '\\\\'+final_path[8:]
elif final_path.startswith('\\\\?\\'): final_path = final_path[4:]
expected_lock = library.with_name('.'+library.stem+'.cbb-upload.lock')
if Path(final_path).resolve() != expected_lock.resolve():
raise ValueError('Native Add supervisor lease belongs to another library.')
finally:
if duplicate is not None: duplicate.Close()
process.Close()
return record