Add ALD Transition Console preview and Astra lab build workflow

This commit is contained in:
scandalist-trash committed 2026-10-27 10:50:43 -04:00
1 parent f330a3c00a
commit e5c6a2fc0e
199 files changed
+9866

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Local build and unit-test handoff; Python 3.7+, standard library only.
Never installs packages, starts the live GUI, changes a domain or qualifies a
release. Reports contain build output and package observations, not projects.
"""
import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[1]
def utc_now():
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--jobs', type=int, default=2, choices=range(1, 9))
parser.add_argument('--build-dir', default='build-astra')
args = parser.parse_args()
if os.geteuid() == 0:
print('Запускайте сборку обычным пользователем, без sudo.', file=sys.stderr)
return 77
os.umask(0o077)
build = (ROOT / args.build_dir).resolve()
# Restrict generated build files to a separate, ignored directory.
if build.parent != ROOT or not build.name.startswith('build-'):
parser.error('--build-dir должен быть отдельным каталогом build-* в корне исходников')
destination = ROOT / 'artifacts' / 'astra-lab'
destination.mkdir(parents=True, exist_ok=True)
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ-')
report_dir = Path(tempfile.mkdtemp(prefix=stamp, dir=str(destination)))
report = dict(schema_version=1, started_at=utc_now(), finished_at=None,
scope='LOCAL_BUILD_AND_UNIT_TESTS_ONLY', release_validated=False,
status='RUNNING', build_directory=str(build), steps=[])
source_hash = hashlib.sha256()
sources = [ROOT / 'CMakeLists.txt']
for directory in ('src', 'schemas', 'data', 'resources', 'tests/unit', 'tools'):
sources.extend(p for p in (ROOT / directory).rglob('*')
if p.is_file() and '__pycache__' not in p.parts and p.suffix != '.pyc')
for path in sorted(sources):
source_hash.update(path.relative_to(ROOT).as_posix().encode('utf-8') + b'\0')
source_hash.update(path.read_bytes())
report['source_digest'] = source_hash.hexdigest()
def run(name, argv, cwd=ROOT, env=None):
print('\n{}: {}'.format(name, ' '.join(shlex.quote(str(a)) for a in argv)), flush=True)
step = dict(name=name, argv=[str(a) for a in argv], cwd=str(cwd),
started_at=utc_now(), status='RUNNING', log=name + '.log')
report['steps'].append(step)
try:
with (report_dir / step['log']).open('w', encoding='utf-8') as log:
with subprocess.Popen(argv, cwd=str(cwd), env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, universal_newlines=True,
encoding='utf-8', errors='replace') as process:
try:
for line in process.stdout:
print(line, end='', flush=True)
log.write(line)
code = process.wait()
except KeyboardInterrupt:
process.terminate()
process.wait()
raise
step['exit_code'] = code
if code:
raise RuntimeError('Этап {} завершился с кодом {}. См. {}'.format(name, code, step['log']))
step['status'] = 'PASS'
except (OSError, RuntimeError, KeyboardInterrupt) as error:
step['status'] = 'INTERRUPTED' if isinstance(error, KeyboardInterrupt) else 'FAIL'
step['error'] = str(error)
raise
finally:
step['finished_at'] = utc_now()
code = 1
try:
# Save observations even when Qt/CMake are absent; never edit the release lock.
run('environment', [sys.executable, str(ROOT / 'tools/collect_compatibility.py'),
'--output', str(report_dir / 'environment.json')])
missing = [name for name in ('cmake', 'ctest', 'g++', 'make') if not shutil.which(name)]
if missing:
raise RuntimeError('Не найдены инструменты: {}. Порядок подготовки: docs/astra-lab.ru.md'.format(', '.join(missing)))
run('configure', ['cmake', '-S', str(ROOT), '-B', str(build), '-G', 'Unix Makefiles',
'-DCMAKE_BUILD_TYPE=Debug', '-DCMAKE_INSTALL_PREFIX=/usr',
'-DBUILD_TESTING=ON', '-DALD_CORE_ONLY=OFF'])
run('build', ['cmake', '--build', str(build), '--parallel', str(args.jobs)])
environment = os.environ.copy()
environment['QT_QPA_PLATFORM'] = 'offscreen'
# ctest --test-dir is newer than the project's CMake 3.13 baseline.
run('ctest', ['ctest', '--output-on-failure', '--timeout', '120'], cwd=build, env=environment)
report['binaries'] = []
for name in ('ald-transition-console', 'ald-transition-executor'):
binary = build / name
report['binaries'].append(dict(name=name, size=binary.stat().st_size,
sha256=hashlib.sha256(binary.read_bytes()).hexdigest()))
report['status'] = 'PASS'
code = 0
except KeyboardInterrupt:
report['status'] = 'INTERRUPTED'
report['error'] = 'Сборка или тестирование прерваны оператором.'
code = 130
except (OSError, RuntimeError) as error:
report['status'] = 'FAIL'
report['error'] = str(error)
print('\n' + str(error), file=sys.stderr)
finally:
report['finished_at'] = utc_now()
(report_dir / 'result.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
archive = report_dir.with_suffix('.tar.gz')
with tarfile.open(str(archive), 'w:gz') as tar:
tar.add(str(report_dir), arcname=report_dir.name)
print('\nРезультат: {}. Архив отчёта: {}'.format(report['status'], archive), flush=True)
print('PASS означает сборку и локальные тесты. Испытания домена и допуск релиза остаются отдельными.')
if code == 0:
print('\nЗапуск из рабочего стола Astra, без sudo:')
print('{} --project {}'.format(shlex.quote(str(build / 'ald-transition-console')),
shlex.quote(str(ROOT / 'astra-lab-project'))))
return code
if __name__ == '__main__':
sys.exit(main())
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Validate actual shipped schemas, catalog coverage, manifests and fixture provenance."""
from pathlib import Path
import hashlib,json,sys,xml.etree.ElementTree as ET
import jsonschema
ROOT=Path(__file__).resolve().parents[1]
def load(path):return json.loads((ROOT/path).read_text())
def check(value,schema):jsonschema.Draft7Validator(load('schemas/'+schema+'.schema.json'),format_checker=jsonschema.FormatChecker()).validate(value)
for p in (ROOT/'schemas').glob('*.schema.json'):jsonschema.Draft7Validator.check_schema(json.loads(p.read_text()))
check(load('data/sources.json'),'source')
check(load('tests/fixtures/demo.inventory.json'),'inventory')
for p in (ROOT/'data/checklists').glob('*.json'):check(json.loads(p.read_text()),'checklist')
source_ids={s['id'] for s in load('data/sources.json')['sources']}
assert len(source_ids)==len(load('data/sources.json')['sources'])
original=next(s for s in load('data/sources.json')['sources'] if s['id']=='FSTEC_LINUX_2022')
assert original['artifact_sha256'] is None and original['verification_state']=='pending_original'
cards=load('data/hardening/fstec-linux-2022.catalog.json')['items']
expected={f'2.{section}.{number}' for section,count in enumerate([2,2,11,8,11,6],1) for number in range(1,count+1)}
assert {c['paragraph'] for c in cards}==expected and len(cards)==40
for c in cards:
assert set(c['source_refs'])<=source_ids
assert c['mapping_state']=='UNKNOWN' and c['accepted_value'] is None
assert c['manual_check_ru'] and c['reversibility_ru']
assert next(c for c in cards if c['paragraph']=='2.6.1')['recovery_class']=='REBOOT_REQUIRED'
assert len({x['id'] for x in load('data/checklists/all.ru.json')['items']})==17
for task in load('resources/tasks/manifest.json')['tasks']:
p=ROOT/'resources/tasks'/task['path'];assert task['sha256']==hashlib.sha256(p.read_bytes()).hexdigest()
assert not task['mutating'] and task['parameters']=={}
assert set(task['source_refs'])<=source_ids
text=(ROOT/'resources/tasks/windows/ad-inventory.ps1').read_text()
assert '-Properties $allowed' in text and '-ResultSetSize 50001' in text
assert 'Start-Job' not in text and 'Register-ScheduledTask' not in text
qrc=ET.parse(ROOT/'resources/resources.qrc')
paths={e.attrib['alias']:(ROOT/'resources'/e.text).resolve() for e in qrc.iter('file')}
for a in load('resources/asset-manifest.json')['assets']:
assert a['path'] in paths and paths[a['path']].is_file()
assert hashlib.sha256(paths[a['path']].read_bytes()).hexdigest()==a['sha256'],a['path']
for p in paths.values():assert p.is_file()
for p in (ROOT/'tests/fixtures').glob('*.json'):assert json.loads(p.read_text())['synthetic'] is True
# Validate schema rejection, not just self-consistency of accepted examples.
demo=load('tests/fixtures/demo.inventory.json')
for mutated in [{**demo,'schema_version':2},{**demo,'unexpected':1},{**demo,'synthetic':'true'}]:
try:check(mutated,'inventory')
except jsonschema.ValidationError:pass
else:raise AssertionError('Invalid inventory accepted')
print(f'PASS: schemas, {len(paths)} resources, {len(source_ids)} source references, 40 cards, 17 checklist instructions, task hashes and synthetic fixtures')
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Exercise the actual Qt binaries in isolated, explicit offscreen DEMO projects."""
import datetime
import json
import os
import struct
import subprocess
import tempfile
from pathlib import Path
root = Path(__file__).resolve().parents[1]
output = root/'artifacts/screenshots'
output.mkdir(parents=True, exist_ok=True)
records = []
for scale in ('1', '1.5', '2'):
with tempfile.TemporaryDirectory(prefix='ald-gui-') as temporary:
environment = os.environ.copy()
environment.update(QT_QPA_PLATFORM='offscreen', QT_SCALE_FACTOR=scale,
XDG_CONFIG_HOME=temporary+'/preferences')
screenshot = output/('overview-'+scale+'.png')
argv = [str(root/'build/ald-transition-console'), '--project', temporary+'/project',
'--demo', '--smoke-test', '--capture', str(screenshot)]
result = subprocess.run(argv, env=environment, capture_output=True, text=True, timeout=20)
records.append(dict(kind='application_demo', scale=scale, exit_code=result.returncode,
stdout=result.stdout, stderr=result.stderr))
assert result.returncode == 0 and screenshot.is_file(), records[-1]
expected = (int(1440*float(scale)), int(900*float(scale)))
assert struct.unpack('>II', screenshot.read_bytes()[16:24]) == expected
environment['ALD_TEST_CAPTURE_DIR'] = str(output/('scale-'+scale))
result = subprocess.run([str(root/'build/test_ui')], env=environment,
capture_output=True, text=True, timeout=30)
records.append(dict(kind='ui_suite', scale=scale, exit_code=result.returncode,
stdout=result.stdout, stderr=result.stderr))
assert result.returncode == 0, records[-1]
for page in range(1, 11):
image = output/('scale-'+scale)/f'narrow-{page:02d}.png'
expected = (int(1024*float(scale)), int(768*float(scale)))
assert struct.unpack('>II', image.read_bytes()[16:24]) == expected
print(f'PASS: actual Qt DEMO + 10 narrow pages, scale {scale}', flush=True)
report = dict(observed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
platform='Qt offscreen', records=records, astra_validated=False,
x11_desktop_validated=False, screen_reader_validated=False)
(root/'docs/gui-smoke-results.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n')
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""Measure declared opaque token pairs; this is not a rendered GUI/a11y test."""
from pathlib import Path
import re
root=Path(__file__).resolve().parents[1]
tokens=dict(re.findall(r'(\w+)="(#[A-Fa-f0-9]{6})"',(root/'src/ui/Theme.h').read_text()))
def luminance(color):
channels=[int(color[i:i+2],16)/255 for i in (1,3,5)]
channels=[v/12.92 if v<=.04045 else ((v+.055)/1.055)**2.4 for v in channels]
return sum(a*b for a,b in zip(channels,(.2126,.7152,.0722)))
for front,back,required in [('text','background',4.5),('text','panel',4.5),('secondary','panel',4.5),('warning','panel',4.5),('background','accent',4.5),('accent','panel',4.5),('accent','elevated',3)]:
hi,lo=sorted([luminance(tokens[front]),luminance(tokens[back])],reverse=True);ratio=(hi+.05)/(lo+.05)
print(f'{front}/{back}: {ratio:.2f}:1 (required {required}:1)');assert ratio>=required
print('PASS: declared text/focus token contrast; rendered, high-contrast-mode and screen-reader checks remain pending')
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Read-only evidence collector. Never writes or marks a release lock validated."""
import argparse,datetime,json,platform,shutil,subprocess
from pathlib import Path
parser=argparse.ArgumentParser();parser.add_argument('--output',required=True);args=parser.parse_args()
def cmd(argv):
try:
result=subprocess.run(argv,capture_output=True,text=True,timeout=15,check=False)
return {'argv':argv,'exit_code':result.returncode,'stdout':result.stdout,'stderr':result.stderr}
except (OSError,subprocess.TimeoutExpired) as e:return {'argv':argv,'error':str(e)}
def read(p):
try:return Path(p).read_text()
except OSError:return None
report={'schema_version':1,'observed_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'release_validated':False,'os_release':read('/etc/os-release'),'astra_build':read('/etc/astra/build_version'),'kernel':platform.release(),'architecture':platform.machine(),'protection_level':None,'commands':[cmd(['g++','--version']),cmd(['cmake','--version']),cmd(['qmake','-query']),cmd(['ssh','-V']),cmd(['astra-modeswitch','getname']),cmd(['dpkg-query','-W','-f=${binary:Package}\t${Version}\t${db:Status-Status}\n','g++','gcc','cmake','make','python3','libc6','libstdc++6','linux-image-'+platform.release(),'qtbase5-dev','qtbase5-dev-tools','qt5-qmake','libqt5core5*','libqt5gui5*','libqt5widgets5*','libqt5network5*','libqt5sql5*','libqt5test5*','openssh-client','policykit-1','aldpro*','astra-version','freeipa*','sssd*','samba*'])]}
Path(args.output).write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
print('Saved observed evidence. Validation remains false:',args.output)
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Create a reproducible source-only review artifact, never a deployable package."""
import datetime
import gzip
import hashlib
import io
import json
import tarfile
from pathlib import Path
root = Path(__file__).resolve().parents[1]
report = json.loads((root/'docs/local-check-results.json').read_text())
epoch = int(datetime.datetime.fromisoformat(report['observed_at']).timestamp())
name = 'ald-transition-console-0.1.0-source-preview'
files = [root/'.gitignore', root/'CMakeLists.txt', root/'README.md']
for directory in ('src', 'schemas', 'data', 'resources', 'docs', 'tests', 'packaging', 'tools'):
files.extend(p for p in (root/directory).rglob('*')
if p.is_file() and '__pycache__' not in p.parts and p.suffix != '.pyc')
output = root/'artifacts'
output.mkdir(exist_ok=True)
archive = output/(name+'.tar.gz')
with archive.open('wb') as raw:
with gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=epoch) as compressed:
with tarfile.open(fileobj=compressed, mode='w') as tar:
for path in sorted(files):
if path.is_symlink():
raise ValueError('Do not distribute symlinked source: '+str(path))
data = path.read_bytes()
info = tarfile.TarInfo(name+'/'+path.relative_to(root).as_posix())
info.size = len(data)
info.mtime = epoch
info.mode = 0o755 if path.name == 'rules' and 'debian' in path.parts else 0o644
info.uid = info.gid = 0
info.uname = info.gname = ''
tar.addfile(info, io.BytesIO(data))
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
(output/'SHA256SUMS').write_text(digest+' '+archive.name+'\n')
with tarfile.open(archive) as tar:
members = tar.getmembers()
assert len(members) == len(files)
assert all(m.isfile() and not m.name.startswith('/') and '..' not in Path(m.name).parts for m in members)
print(f'Source preview: {len(files)} files, {archive.stat().st_size} bytes')
print(archive)
print('SHA256 '+digest)
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""Compile and run the production portable rules without requiring Qt/CMake."""
import os,subprocess,tempfile
from pathlib import Path
root=Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix='ald-rules-') as temporary:
binary=str(Path(temporary)/'test_rules')
command=['g++','-std=c++17','-Wall','-Wextra','-Wpedantic','-Werror','-fsanitize=address,undefined','-fno-omit-frame-pointer','-g','-I'+str(root/'src'),str(root/'src/core/Rules.cpp'),str(root/'tests/unit/test_rules.cpp'),'-o',binary]
subprocess.run(command,check=True)
environment=os.environ.copy()
# LeakSanitizer cannot inspect processes in the managed sandbox/ptrace context.
# ASan bounds checking and UBSan remain enabled. This does not claim leak coverage.
environment['ASAN_OPTIONS']='detect_leaks=0'
subprocess.run([binary],check=True,env=environment)
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Developer-only deterministic asset manifest update. Review changes before release."""
import hashlib,json
from pathlib import Path
root=Path(__file__).resolve().parents[1]
files=[]
for folder in ('data','schemas'):
for p in sorted((root/folder).rglob('*.json')):files.append((p.relative_to(root).as_posix(),p))
for p in sorted((root/'resources/tasks').rglob('*')):
if p.is_file():files.append((p.relative_to(root/'resources').as_posix(),p))
files.extend([('styles/dedsec.qss',root/'resources/styles/dedsec.qss'),('fixtures/demo.inventory.json',root/'tests/fixtures/demo.inventory.json')])
manifest={'schema_version':1,'assets':[{'path':alias,'sha256':hashlib.sha256(path.read_bytes()).hexdigest()} for alias,path in files]}
(root/'resources/asset-manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
files.append(('asset-manifest.json',root/'resources/asset-manifest.json'))
import os
(root/'resources/resources.qrc').write_text('<RCC><qresource prefix="/">\n'+''.join(f' <file alias="{alias}">{os.path.relpath(path,root/"resources")}</file>\n' for alias,path in files)+'</qresource></RCC>\n')
print(f'Updated {len(manifest["assets"])} embedded asset digests and resources.qrc')
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Run local software checks only; never connect to infrastructure or install tools."""
import argparse
import datetime
import hashlib
import json
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument('--portable-only', action='store_true')
args = parser.parse_args()
records = []
def run(name, argv, expected=0, cwd=ROOT, timeout=120):
try:
result = subprocess.run(argv, cwd=cwd, capture_output=True, text=True, timeout=timeout)
record = dict(name=name, command=argv, expected_exit=expected,
exit_code=result.returncode, stdout=result.stdout, stderr=result.stderr,
status='PASS' if result.returncode == expected else 'FAIL')
except (OSError, subprocess.TimeoutExpired) as error:
record = dict(name=name, command=argv, status='ERROR', error=str(error))
records.append(record)
print(name + ': ' + record['status'], flush=True)
return record['status'] == 'PASS'
run('data_and_manifest', [sys.executable, 'tools/check_assets.py'])
run('declared_theme_contrast', [sys.executable, 'tools/check_theme.py'])
run('portable_rules_asan_ubsan', [sys.executable, 'tools/run_portable_tests.py'])
# The unvalidated lock MUST block packaging in this development preview.
run('unvalidated_release_refused', [sys.executable, 'tools/verify_release_lock.py'], expected=1)
qt_state = 'NOT_RUN_EXPLICIT_PORTABLE_ONLY' if args.portable_only else 'BLOCKED_MISSING_BUILD_TOOLS'
if not args.portable_only and shutil.which('cmake'):
if run('qt_configure', ['cmake', '-S', '.', '-B', 'build', '-DCMAKE_BUILD_TYPE=Debug']):
if run('qt_build', ['cmake', '--build', 'build', '--parallel', '2'], timeout=300):
qt_state = 'PASS' if run('qt_tests', ['ctest', '--output-on-failure'], cwd=ROOT/'build') else 'FAIL'
else:
qt_state = 'FAIL'
else:
qt_state = 'BLOCKED_OR_CONFIGURE_FAILED'
digest = hashlib.sha256()
for base in ('src', 'tests/unit', 'schemas', 'data', 'resources', 'tools'):
for path in sorted((ROOT/base).rglob('*')):
if path.is_file() and '__pycache__' not in path.parts:
digest.update(path.relative_to(ROOT).as_posix().encode() + b'\0' + path.read_bytes())
report = dict(schema_version=1, observed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
source_digest=digest.hexdigest(), checks=records, qt_validation=qt_state,
astra_lab='NOT_AVAILABLE', windows_lab='NOT_AVAILABLE', release_validated=False)
output = ROOT/'docs/local-check-results.json'
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print('Qt validation: ' + qt_state)
print('Report: ' + str(output))
if any(record['status'] != 'PASS' for record in records):
sys.exit(1)
sys.exit(0 if args.portable_only or qt_state == 'PASS' else 2)
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
"""Require actual supported-target evidence before package generation."""
import argparse, json, sys
from pathlib import Path
root = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument('--lock', type=Path, default=root/'docs/compatibility-lock.json')
args = parser.parse_args()
required = ('os_release', 'os_update', 'kernel', 'architecture', 'compiler', 'cmake',
'qt_packages', 'sqlite_driver', 'transports', 'ald_packages')
try:
lock = json.loads(args.lock.read_text())
observed = lock.get('validated_target', {})
missing = [key for key in required if not observed.get(key)]
if lock.get('schema_version') != 1 or lock.get('release_validated') is not True or missing:
raise ValueError('supported Astra validation incomplete; missing: ' + ', '.join(missing))
target = lock.get('target', {})
if target.get('release') != '1.7.7' or target.get('update') != 'UU2' or target.get('ald_version') != '3.1.0':
raise ValueError('target differs from the accepted first laboratory baseline')
except (OSError, ValueError, TypeError, AttributeError) as error:
print('RELEASE BLOCKED: ' + str(error), file=sys.stderr)
sys.exit(1)
print('Required lock fields present. Authenticity and laboratory approval still require review; this is not migration authorization.')