feat: capture gated native logical and physical identity evidence

This commit is contained in:
阿白叔 committed 2026-11-03 11:39:38 +08:00
1 parent ca84bce24f
commit 63f3417f19
2 files changed
+483

No files matched your search

@@ -0,0 +1,331 @@
"""Pinned EE7.9.5 native logical exports plus conservative physical/assets proof.
This contract is not raw iCDB equivalence or a claim of exhaustive arbitrary CES
semantics. It compares the proven hierarchy/flat ASCII and CSV/property exports,
and preserves physical design and all other primary engineering assets exactly.
"""
from dataclasses import dataclass
import hashlib
from pathlib import Path
import re
import subprocess
import time
from .management import source_project, _write_json
from .scoped_manifest import ManifestScope, build_manifest, hash_file
POLICY = 'mentor795-native-content-v1'
COVERAGE = {'logical_connectivity_and_properties': 'native hierarchy/flat ASCII and CSV',
'physical_design_and_primary_assets': 'raw SHA256',
'schematic_graphical_geometry': 'unproven', 'production_acceptance': False}
EXPORTER_PROOF = {
'icdb2ascii.exe': 'e37c87356eaf57c0b97e4183458bc8c5eb6eb0ac497cc7ad40dcd585d8cd213b',
'icdb2csv.exe': '22059f4a432e8eabf30a5326ebcbd463ed6fa6495af21d7aad5ab5d2f892f255',
}
INF_HEADER = (b'Design Name\tSystem Name\tSystem Version\tSystem_Date\tCompany_Name\tDepartment_Name'
b'\tAddress\tAddress1\tCity\tState_Province\tCountry\tZip\tPhone\tPhone_Ext\tFax\tFax_Ext')
CSV_SUFFIXES = ('', '.esf', '.inf', '.npr', '.ppn', '.ppr', '.prm', '.prt', '.pth',
'.sht', '.spn', '.spr', '.sym', '.thn')
_retained_exports = []
_OWNER_NAMES = frozenset({'icdb2ascii.exe', 'icdb2csv.exe', 'icdbnetserver.exe',
'icdbnetlauncher.exe', 'icdbservermanager.exe', 'icdbservermonitor.exe'})
@dataclass(frozen=True)
class IdentityOutcome:
identity: dict | None
safe_to_continue: bool
detail: str
evidence_path: Path
def _digest(data):
return hashlib.sha256(data).hexdigest()
def normalize_ascii(data, top):
"""Only the three observed, position-bound report metadata values vary."""
lines = data.splitlines(keepends=True)
prefixes = {0: b'iCDB Ascii Report Generation Date: ',
4: b'\t iCDB directory: ', 5: b'\t DATE: '}
if (len(lines) < 12 or lines[3].rstrip(b'\r\n') != b'\tReport Criteria:'
or any(not lines[i].startswith(prefix) or not lines[i][len(prefix):].strip()
for i, prefix in prefixes.items())):
raise ValueError('Incomplete or unknown native ASCII report header.')
header = b''.join(lines[:next((i for i, line in enumerate(lines) if line.startswith(b'Block ')), len(lines))])
required = (b'\t REPORT FORMAT: FREEFORM', b'\t MODE: HIER AND FLAT BLOCKS',
b'\t CONNECTION LISTS: ON', b'\t TEXT LISTS: ON')
if any(header.count(value) != 1 for value in required):
raise ValueError('Native ASCII export mode does not match the proven contract.')
top_bytes = top.encode('mbcs')
if (not any(line.rstrip(b'\r\n') == b'Block '+top_bytes+b' \tRoot' for line in lines)
or not any(line.startswith(b'Config ') for line in lines)):
raise ValueError('Native ASCII export lacks the exact root or flat configuration.')
for index, prefix in prefixes.items():
ending = b'\r\n' if lines[index].endswith(b'\r\n') else b'\n'
lines[index] = prefix+b'<REPORT_METADATA>'+ending
return b''.join(lines)
def normalize_inf(data):
lines = data.splitlines(keepends=True)
if len(lines) != 2 or lines[0].rstrip(b'\r\n') != INF_HEADER:
raise ValueError('Unknown native CSV information schema.')
values = lines[1].rstrip(b'\r\n').split(b'\t')
if len(values) != 16 or values[:3] != [b'identity', b'Design Capture', b'VB99.0']:
raise ValueError('Malformed native CSV information row.')
if not re.fullmatch(rb'\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', values[3]):
raise ValueError('Unknown native CSV System_Date format.')
values[3] = b'<SYSTEM_DATE>'
ending = b'\r\n' if lines[1].endswith(b'\r\n') else b'\n'
return lines[0]+b'\t'.join(values)+ending
def csv_identity(root):
from .scoped_manifest import scan_tree
root = Path(root)
paths = {p.relative_to(root).as_posix(): p for p in scan_tree(root) if p.is_file()}
expected = {'work/identity'+suffix for suffix in CSV_SUFFIXES}
if paths.keys() != expected or any(not p.stat().st_size for p in paths.values()):
raise ValueError('Native CSV export is empty, incomplete or an unsupported snapshot.')
index = paths['work/identity'].read_bytes().splitlines()
expected_index = {b'file:identity'+suffix.encode('ascii') for suffix in CSV_SUFFIXES if suffix}
if len(index) != len(expected_index) or set(index) != expected_index:
raise ValueError('Native CSV index does not bind every exported table.')
return {name: _digest(normalize_inf(path.read_bytes()) if name.endswith('.inf') else path.read_bytes())
for name, path in sorted(paths.items())}
def _project_encoding(data):
if data.startswith((b'\xff\xfe', b'\xfe\xff')): return 'utf-16'
if data.startswith(b'\xef\xbb\xbf'): return 'utf-8-sig'
try: data.decode('utf-8'); return 'utf-8'
except UnicodeDecodeError: return 'mbcs'
def project_library(source):
"""Require one existing approved source library across every project ref."""
from .backup_recovery import _project_text
source, pcb, _ = source_project(source)
libraries = set()
for path in (source, pcb.parent/'pcb.prj'):
values = re.findall(r'^KEY CentralLibrary "([^"\r\n]+)"', _project_text(path), re.M)
if not values: raise ValueError('Project lacks CentralLibrary references.')
for value in values:
target = (path.parent/value).resolve(strict=True)
if target.suffix.casefold() != '.lmc' or not target.is_file():
raise ValueError('CentralLibrary is not an existing LMC.')
libraries.add(target)
if len(libraries) != 1: raise ValueError('Project CentralLibrary references disagree.')
return libraries.pop()
def _normalized_project(path, expected_library):
data = path.read_bytes(); encoding = _project_encoding(data)
text = data.decode(encoding)
refs = re.findall(r'^KEY CentralLibrary "([^"\r\n]*)"', text, re.M)
if not refs or any((path.parent/value).resolve() != expected_library.resolve() for value in refs):
raise ValueError(f'CentralLibrary reference does not resolve to the approved library: {path}')
return re.sub(r'(?m)^(KEY CentralLibrary ")[^"\r\n]*(")',
r'\1<CENTRAL_LIBRARY>\2', text).encode(encoding)
def asset_identity(source, expected_library):
from .backup_recovery import _project_text
source, pcb, top = source_project(source)
expected_library = Path(expected_library)
if not expected_library.is_file(): raise ValueError('Approved CentralLibrary is missing.')
root = source.parent
projects = (source, pcb.parent/'pcb.prj')
databases = []
for project in projects:
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)
databases.extend((project.parent/value).resolve() for value in values)
main_database = databases[0]
runtime = [db/'cdbsvr' for db in databases]
files = build_manifest(root, scope=ManifestScope())['files']
assets = {}
for relative, record in files.items():
path = root/relative
if path == main_database/'icdb.dat' or any(path.is_relative_to(p) for p in runtime):
continue
if path in projects:
data = _normalized_project(path, expected_library)
assets[relative] = {'size': len(data), 'sha256': _digest(data)}
else:
assets[relative] = {'size': record['size'], 'sha256': record['sha256']}
return {'policy': POLICY, 'top_level_block': top,
'layout_sha256': hash_file(pcb.parent/'Layout/LayoutDB.lyt'), 'assets': assets}
def check_exporters(mentor_home):
for name, expected in EXPORTER_PROOF.items():
path = Path(mentor_home)/'iCDB/win32/bin'/name
if not path.is_file() or hash_file(path) != expected:
raise ValueError(f'Native identity exporter is not the proven EE7.9.5 binary: {path}')
def validate_export_output(kind, code, report, log):
text = Path(log).read_bytes().decode('mbcs', errors='strict')
if code != 0 or re.search(r'(?im)^\s*(?:#\s*)?(?:error|fatal)\b', text):
raise ValueError('Native identity exporter failed or reported an error.')
if kind == 'ascii':
if (not Path(report).is_file() or not Path(report).stat().st_size
or f'Report generation complete, report file is {report}' not in text):
raise ValueError('Native ASCII export lacks a complete nonempty report.')
elif kind == 'csv':
if 'iCDB to CSV complete' not in [line.strip() for line in text.splitlines()]:
raise ValueError('Native CSV export lacks its completion marker.')
csv_identity(report)
else:
raise ValueError('Unsupported native export kind.')
def _process_snapshot():
import win32com.client
service = win32com.client.GetObject('winmgmts:')
try:
return [{'pid': int(p.ProcessId), 'parent': int(p.ParentProcessId or 0),
'name': str(p.Name), 'executable': str(p.ExecutablePath or '')}
for p in service.ExecQuery('SELECT ProcessId, ParentProcessId, Name, ExecutablePath FROM Win32_Process')]
finally:
service = None
def _database_released(project_root):
"""Exclusive reads plus absent addresses prove the copied native DBs idle."""
import win32file, win32con
from contextlib import ExitStack
root = Path(project_root)
if any(root.rglob('sAddress.adr')):
return False
with ExitStack() as stack:
for path in root.rglob('*'):
if path.is_file() and path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
stack.callback(handle.Close)
return True
def _run_exports(project, root, mentor_home, timeout_seconds):
"""Observe exact exporter/descendant handles; never kill a database owner."""
import win32api, win32con, win32event, pywintypes
root = Path(root)
before = _process_snapshot()
if any(p['name'].casefold() in _OWNER_NAMES for p in before):
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
if not _database_released(project.parent):
return {'success': False, 'safe_to_continue': False, 'detail': 'Analysis copy has unreleased native addresses or DB handles.'}
commands = [
('ascii', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2ascii.exe'),
f'-project={project}', f'-file={root/"design.rpt"}', f'-clog={root/"ascii.log"}',
'-f', '-h', '-c', '-t', '-nostrip'], root/'design.rpt', root/'ascii.log'),
('csv', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2csv.exe'),
f'-project={project}', '-snap=DxD', '-file=identity', f'-output={root/"tables"}',
f'-clog={root/"csv.log"}', '-properties', '-nostrip'], root/'tables', root/'csv.log'),
]
for kind, command, report, log in commands:
process = None
handles = {}
released = False
record = {'command': command, 'kind': kind, 'success': False, 'safe_to_continue': False}
try:
deadline = time.monotonic()+float(timeout_seconds)
with (root/(kind+'-stdout.txt')).open('wb') as output:
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
record['pid'] = process.pid
descendants = {process.pid}
_write_json(root/(kind+'-process.json'), record)
while time.monotonic() < deadline:
snapshot = _process_snapshot()
changed = True
while changed:
previous = len(descendants)
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
changed = len(descendants) != previous
owners = [p for p in snapshot if p['pid'] in descendants or p['name'].casefold() in _OWNER_NAMES]
for owner in owners:
if owner['pid'] not in handles:
try: handles[owner['pid']] = win32api.OpenProcess(win32con.SYNCHRONIZE, False, owner['pid'])
except pywintypes.error as error:
if error.winerror != 87: raise
record['observed_pids'] = sorted(descendants | handles.keys())
if (process.poll() is not None and not owners
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
released = _database_released(project.parent)
if released: break
time.sleep(.1)
record.update(exit_code=process.poll(), safe_to_continue=released)
if not released:
record['detail'] = 'TIMEOUT: native export owner or copied database release remains unconfirmed.'
return record
validate_export_output(kind, process.returncode, report, log)
record.update(success=True, detail='Native export complete and owners released.')
except Exception as error:
record.update(detail=str(error), safe_to_continue=released)
return record
finally:
if process is not None and not released:
_retained_exports.append((process, handles))
else:
for handle in handles.values(): handle.Close()
_write_json(root/(kind+'-process.json'), record)
return {'success': True, 'safe_to_continue': True, 'detail': 'Both native exports completed and released.'}
def capture_identity(source, evidence_root, *, expected_library, owner_library, mentor_home,
timeout_seconds=180):
"""Capture on a fresh project copy while an existing transaction owns its library."""
from .backup_recovery import _align_library
from .library_lock import LibraryLock, owned_snapshot
from .scoped_manifest import copy_verified
import win32event, win32con
source, pcb, top = source_project(source)
root = Path(evidence_root).absolute()
library = Path(owner_library)
lease = LibraryLock(library)
if owned_snapshot(lease.path) is None:
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
or root.resolve().is_relative_to(library.parent.resolve())):
raise ValueError('Native identity evidence must be independent of source and library.')
check_exporters(mentor_home)
root.mkdir(parents=True, exist_ok=False)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
owner_safe = True
outcome = IdentityOutcome(None, True, 'Identity capture did not start.', root)
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise RuntimeError('Another CBB operation owns the management mutex.')
with LibraryLock(library, safe_to_release=lambda: owner_safe):
assets = asset_identity(source, Path(expected_library))
original = copy_verified(source.parent, root/'project')
clone = root/'project'/source.name
_, clone_pcb, _ = source_project(clone)
_align_library(clone, clone_pcb, Path(expected_library))
if any((root/'project').rglob('sAddress.adr')):
raise ValueError('Analysis source contains an unresolved database address.')
owner_safe = False
native = _run_exports(clone, root, mentor_home, timeout_seconds)
owner_safe = native.get('safe_to_continue') is True
_write_json(root/'native-outcome.json', native)
if not owner_safe or not native.get('success'):
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
else:
ascii_bytes = normalize_ascii((root/'design.rpt').read_bytes(), top)
csv = csv_identity(root/'tables')
if build_manifest(source.parent) != original:
raise ValueError('Identity input changed while exporting its disposable copy.')
fingerprint = {**assets, 'coverage': COVERAGE, 'ascii_sha256': _digest(ascii_bytes), 'csv': csv}
outcome = IdentityOutcome(fingerprint, True, 'Native logical exports and primary assets captured.', root)
except Exception as error:
outcome = IdentityOutcome(None, owner_safe, str(error), root)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
'detail': outcome.detail, 'policy': POLICY})
return outcome
+152
View File
@@ -0,0 +1,152 @@
"""Native export and asset identity boundaries; never launch native tools."""
from pathlib import Path
import pytest
def ascii_report(date=b'Tue Nov 03 11:19:39 2026', directory=b'C:\\copy\\database'):
return (b'iCDB Ascii Report Generation Date: '+date+b'\r\n\r\n\r\n\tReport Criteria:\r\n'
b'\t iCDB directory: '+directory+b'\r\n\t DATE: '+date+b'\r\n\r\n'
b'\t REPORT FORMAT: FREEFORM\r\n\t MODE: HIER AND FLAT BLOCKS\r\n'
b'\t CONNECTION LISTS: ON\r\n\t TEXT LISTS: ON\r\n\r\n'
b'Block Top \tRoot\r\n\tPort A\r\nConfig default\tview none\r\n\tPin A\r\n')
def test_ascii_only_normalizes_three_validated_header_values():
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
first = ascii_report()
changed = ascii_report(b'Wed Nov 04 12:00:00 2026', b'D:\\other\\database')
assert normalize_ascii(first, 'Top') == normalize_ascii(changed, 'Top')
assert normalize_ascii(first, 'Top') != normalize_ascii(first.replace(b'Port A', b'Port B'), 'Top')
body = b'\tiCDB Ascii Report Generation Date: design property\r\n'
assert normalize_ascii(first+body, 'Top') != normalize_ascii(first+body.replace(b'property', b'value'), 'Top')
@pytest.mark.parametrize('change', ['empty', 'wrong_root', 'missing_config', 'header_duplicate', 'wrong_mode'])
def test_ascii_rejects_missing_or_unrecognized_structure(change):
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
data = ascii_report()
data = {'empty': b'', 'wrong_root': data.replace(b'Block Top ', b'Block Other '),
'missing_config': data.replace(b'Config default', b'Partial default'),
'header_duplicate': data.replace(b'\tReport Criteria:', b'\t DATE: extra'),
'wrong_mode': data.replace(b'HIER AND FLAT BLOCKS', b'FLAT ONLY')}[change]
with pytest.raises(ValueError): normalize_ascii(data, 'Top')
def test_inf_only_normalizes_unique_timestamp_column():
from cbb_refresh_verify.native_engineering_identity import normalize_inf, INF_HEADER
row = [b'identity', b'Design Capture', b'VB99.0', b'11/03/26 11:21:34']+[b'value']*12
first = INF_HEADER+b'\r\n'+b'\t'.join(row)+b'\r\n'
assert normalize_inf(first) == normalize_inf(first.replace(b'11:21:34', b'11:21:37'))
assert normalize_inf(first) != normalize_inf(first.replace(b'value', b'changed', 1))
with pytest.raises(ValueError): normalize_inf(first.replace(b'System_Date', b'Unknown'))
with pytest.raises(ValueError): normalize_inf(first+b'extra row\r\n')
@pytest.fixture
def project(tmp_path):
from test_management import project
source = project(tmp_path/'project', name='Source')
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
for path in (source, source.parent/'PCB/pcb.prj'):
with path.open('a', encoding='utf-8') as stream:
stream.write(f'KEY CentralLibrary "{library}"\n')
return source, library
def test_assets_require_correct_library_references_and_unknown_bytes(project):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
before = asset_identity(source, library)
runtime = source.parent/'database/cdbsvr/events/events.dat'
runtime.parent.mkdir(parents=True); runtime.write_bytes(b'runtime')
(source.parent/'database/icdb.dat').write_bytes(b'native normalized database')
assert asset_identity(source, library) == before
unknown = source.parent/'unknown-engineering.bin'; unknown.write_bytes(b'engineering')
assert asset_identity(source, library) != before
unknown.unlink()
(source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'changed physical design')
assert asset_identity(source, library) != before
text = (source.parent/'PCB/pcb.prj').read_text()
(source.parent/'PCB/pcb.prj').write_text(text.replace(str(library), 'missing.lmc'))
with pytest.raises(ValueError, match='CentralLibrary'):
asset_identity(source, library)
@pytest.mark.parametrize('failure', ['empty', 'missing_completion', 'error', 'exit'])
def test_export_evidence_requires_successful_complete_native_output(tmp_path, failure):
from cbb_refresh_verify.native_engineering_identity import validate_export_output
report = tmp_path/'design.rpt'; report.write_bytes(b'report')
log = tmp_path/'native.log'
log.write_text(f'Report generation complete, report file is {report}\n')
code = 0
if failure == 'empty': report.write_bytes(b'')
if failure == 'missing_completion': log.write_text('partial report\n')
if failure == 'error':
with log.open('a') as stream: stream.write('ERROR: database corrupt\n')
if failure == 'exit': code = 2
with pytest.raises(ValueError): validate_export_output('ascii', code, report, log)
def test_capture_only_exports_fresh_copy_and_leaves_source_unchanged(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock
from cbb_refresh_verify.scoped_manifest import build_manifest
source, library = project
original = build_manifest(source.parent)
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
def exports(clone, root, *_):
assert clone.parent == root/'project' and clone != source
(clone.parent/'database/icdb.dat').write_bytes(b'export changed disposable copy')
(root/'design.rpt').write_bytes(ascii_report())
return {'success': True, 'safe_to_continue': True, 'detail': ''}
monkeypatch.setattr(identity, '_run_exports', exports)
monkeypatch.setattr(identity, 'csv_identity', lambda _: {'work/identity': 'csv proof'})
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity['policy'] == identity.POLICY and result.safe_to_continue
assert build_manifest(source.parent) == original
def test_capture_unreleased_exporter_retains_caller_lease(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard
source, library = project
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_run_exports', lambda *a: {
'success': False, 'safe_to_continue': False, 'detail': 'TIMEOUT: native exporter retained'})
lease = LibraryLock(library)
try:
with lease:
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and not result.safe_to_continue
with pytest.raises(LibraryBusy):
with LibraryLock(library): pass
finally:
with _guard:
owner = _owners.pop(lease.key, None)
if owner: owner['handle'].Close()
blocker_path(library).unlink(missing_ok=True)
def test_export_timeout_retains_process_without_kill(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
seen = []
class Running:
pid = 987654
def __init__(self, command, **kwargs): seen.append(command)
def poll(self): return None
def kill(self): pytest.fail('native owner cannot be killed')
def terminate(self): pytest.fail('native owner cannot be terminated')
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
result = identity._run_exports(source, root, tmp_path, 0)
assert not result['safe_to_continue'] and 'TIMEOUT' in result['detail']
assert len(identity._retained_exports) == 1
assert seen[0][-5:] == ['-f', '-h', '-c', '-t', '-nostrip']
assert (root/'ascii-process.json').is_file()