Freeze minimal SYSTEM nonstart 221 closure and reproducible Windows source
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-16 21:07:24 +01:00
parent 510c069838
commit 559c4cb292
16 changed files with 2222 additions and 37 deletions
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""Fixed existing expired Windows script ceiling renewal; Root invokes separately.
No CLI dispatch, job/approval, container recreation, membership, environment or
mount mutation. A committed intent makes this case readback-only, never retry.
"""
def renew_existing_expired_policy(payload):
import datetime as dt
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import uuid
def require(value, code):
if not value:
raise RuntimeError(code)
require(os.geteuid() == 0, 'SYSTEM_RENEW_ROOT_BOOTSTRAP')
require(set(payload) == {'operation', 'case_id', 'expected_roles', 'helper_binary_sha256', 'helper_policy_sha256', 'acceptance_evidence_id'}, 'SYSTEM_RENEW_FIXED_INPUT')
require(payload['operation'] == 'windows_system_existing_expired_script_scope_renew_v1', 'SYSTEM_RENEW_OPERATION')
ident = str(uuid.UUID(payload['case_id']))
evidence_id = str(uuid.UUID(payload['acceptance_evidence_id']))
require(ident == payload['case_id'] and evidence_id == payload['acceptance_evidence_id'] and uuid.UUID(ident).int and uuid.UUID(evidence_id).int, 'SYSTEM_RENEW_CANONICAL_IDS')
require(all(re.fullmatch('[a-f0-9]{64}', payload[n]) for n in ('helper_binary_sha256', 'helper_policy_sha256')), 'SYSTEM_RENEW_FINAL_PINS')
root = Path('/opt/rust-discovery')
tenant = '11111111-1111-4111-8111-111111111111'
asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0'
agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3'
actors = ['automation:' + tenant, 'simulated-testprincipal-a']
mounted = root / 'devstate/windows-system-policy/5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33/mounted'
original_sha = 'c4993009e62ef9c384ea11a2f201566c2e657c1ba3b452410bb2a9d4774b0169'
case = root / 'devstate/windows-system-policy' / ('renew-' + ident)
epoch_intent = mounted.parent / 'renew-c4993009-intent.json'
def run(args, data=None):
return subprocess.run(args, input=data, capture_output=True, check=True, timeout=25).stdout
def encode(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def digest(data):
return hashlib.sha256(data).hexdigest()
def sync_directory(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def create(path, data, uid=0, gid=0):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as stream:
os.fchown(stream.fileno(), uid, gid)
os.fchmod(stream.fileno(), 0o600)
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
def identity(m):
return [m.st_dev, m.st_ino, m.st_uid, m.st_gid, stat.S_IMODE(m.st_mode), m.st_nlink]
def directory(path, uid=None):
m = path.lstat()
require(stat.S_ISDIR(m.st_mode) and not stat.S_ISLNK(m.st_mode) and not m.st_mode & 0o022, 'SYSTEM_RENEW_PROTECTED_DIRECTORY')
if uid is not None:
require(m.st_uid == uid and m.st_gid == uid and stat.S_IMODE(m.st_mode) == 0o700, 'SYSTEM_RENEW_EXACT_DIRECTORY_OWNER')
return identity(m)
for parent in [root, root / 'devstate', root / 'devstate/windows-system-policy', mounted.parent, mounted]:
directory(parent)
directory(mounted.parent, 0)
mounted_identity = directory(mounted, 10001)
key = (root / 'devstate/jobs/ed25519.pem').lstat() # STAT ONLY, no key content.
require(stat.S_ISREG(key.st_mode) and key.st_nlink == 1 and key.st_uid == key.st_gid == 10001 and stat.S_IMODE(key.st_mode) == 0o600, 'SYSTEM_RENEW_JOB_KEY_OWNER_STAT_ONLY')
roles = payload['expected_roles']
require(set(roles) == {'api', 'gateway'}, 'SYSTEM_RENEW_BOTH_CURRENT_ROLES')
def runtime(role):
expected = roles[role]
require(set(expected) == {'container_id', 'image'} and re.fullmatch('[a-f0-9]{64}', expected['container_id']) and re.fullmatch('sha256:[a-f0-9]{64}', expected['image']), 'SYSTEM_RENEW_CURRENT_CONTAINER_WITNESS')
c = json.loads(run(['docker', 'inspect', expected['container_id']]))[0]
h, conf = c['HostConfig'], c['Config']
require(c['Name'] == '/rust-discovery-server-' + role + '-1' and c['State']['Running'] and c['Image'] == expected['image'], 'SYSTEM_RENEW_CONTAINER_CAS')
require(conf['User'] == '10001:10001' and h['ReadonlyRootfs'] and h['CapDrop'] == ['ALL'] and not h.get('CapAdd') and h['SecurityOpt'] == ['no-new-privileges:true'] and not h['Privileged'], 'SYSTEM_RENEW_SANDBOX')
port = {'api': '18443', 'gateway': '18444'}[role]
require(h['PortBindings'] == {'18443/tcp': [{'HostIp': '127.0.0.1', 'HostPort': port}]} and h.get('PidMode', '') == '' and h.get('IpcMode') == 'private' and h.get('UsernsMode', '') == '' and h['NetworkMode'] in c['NetworkSettings']['Networks'] and not h.get('Devices'), 'SYSTEM_RENEW_PRIVATE_NAMESPACES_AND_PORT')
env = {}
for entry in conf['Env']:
name, separator, value = entry.partition('=')
require(separator and name not in env, 'SYSTEM_RENEW_ENVIRONMENT')
env[name] = value # private RAM only, never output credentials.
require(env.get('RMM_PROFILE') == 'development' and env.get('RMM_DEV_SYSTEM_ENABLED') == 'true' and env.get('RMM_DEV_SYSTEM_POLICY_FILE') == '/system-policy/policy.json', 'SYSTEM_RENEW_EXISTING_ENABLED_FILE')
mounts = [m for m in c['Mounts'] if m['Destination'] == '/system-policy']
require(len(mounts) == 1 and mounts[0]['Type'] == 'bind' and mounts[0]['Source'] == str(mounted) and mounts[0]['RW'] is False and mounts[0]['Propagation'] == 'rprivate', 'SYSTEM_RENEW_EXISTING_READONLY_DIRECTORY_MOUNT')
# Compare the complete actual configuration again after the one file
# operation; no env/container/membership delta is permitted.
return {'id': c['Id'], 'image': c['Image'], 'config': conf, 'host': h, 'mounts': c['Mounts'], 'networks': sorted(c['NetworkSettings']['Networks'])}
before_roles = {role: runtime(role) for role in ('api', 'gateway')}
lock_path = root / 'devstate/.windows-system-scope.lock'
lock = os.open(lock_path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
lm = os.fstat(lock)
require(stat.S_ISREG(lm.st_mode) and lm.st_uid == 0 and stat.S_IMODE(lm.st_mode) == 0o600 and lm.st_nlink == 1, 'SYSTEM_RENEW_ORIGINAL_SCOPE_LOCK')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
require(not case.exists() and not epoch_intent.exists(), 'SYSTEM_RENEW_EXISTING_CASE_OR_EPOCH_READBACK_ONLY')
policy_path = mounted / 'policy.json'
fd = os.open(policy_path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as original:
old_meta = os.fstat(original.fileno())
require(stat.S_ISREG(old_meta.st_mode) and old_meta.st_nlink == 1 and old_meta.st_uid == old_meta.st_gid == 10001 and stat.S_IMODE(old_meta.st_mode) == 0o600 and old_meta.st_size <= 65536, 'SYSTEM_RENEW_EXACT_OLD_POLICY_METADATA')
old_raw = original.read(65537)
require(len(old_raw) <= 65536 and digest(old_raw) == original_sha, 'SYSTEM_RENEW_OLD_EXPIRED_POLICY_CAS')
old = json.loads(old_raw)
require(set(old) == {'schema_version', 'profile', 'expires_at', 'scopes'} and old['schema_version'] == 3 and old['profile'] == 'development' and len(old['scopes']) == 1, 'SYSTEM_RENEW_OLD_POLICY_FORM')
scope = old['scopes'][0]
fields = {'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'principals', 'helper_policy_sha256', 'helper_binary_sha256', 'acceptance_evidence_id', 'allowed_services', 'max_runtime_seconds', 'allowed_script_profiles'}
require(set(scope) == fields and scope['tenant_id'] == tenant and scope['asset_id'] == asset and scope['agent_id'] == agent and scope['enrollment_generation'] == scope['assignment_version'] == 1 and scope['principals'] == actors and scope['allowed_services'] == [] and scope['max_runtime_seconds'] == 30 and scope['allowed_script_profiles'] == ['full_maintenance_v1'], 'SYSTEM_RENEW_SAME_SCRIPT_ONLY_SCOPE')
now = dt.datetime.now(dt.timezone.utc)
expiry = dt.datetime.fromisoformat(old['expires_at'].replace('Z', '+00:00'))
require(expiry.tzinfo is not None and expiry <= now, 'SYSTEM_RENEW_OLD_WINDOW_MUST_BE_EXPIRED')
require(scope['helper_binary_sha256'] != payload['helper_binary_sha256'] and scope['helper_policy_sha256'] != payload['helper_policy_sha256'] and scope['acceptance_evidence_id'] != evidence_id, 'SYSTEM_RENEW_NEW_INDEPENDENT_FINAL_PAIR_PROOF')
sql = ("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object("
"'installation',(SELECT json_build_object('ready',sync_ready,'helper_ready',helper_sync_ready,'blocked',restore_blocked,'fresh',last_contact_at>clock_timestamp()-interval '45 seconds','same_certificate',certificate_sha256=last_authenticated_certificate_sha256,'auth_fresh',last_authenticated_at>clock_timestamp()-interval '45 seconds','capabilities',capabilities) FROM agent_installations WHERE tenant_id='" + tenant + "' AND asset_id='" + asset + "' AND agent_id='" + agent + "' AND enrollment_generation=1 AND assignment_version=1 AND revoked_at IS NULL),"
"'open_jobs',(SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND state NOT IN ('succeeded','failed','cancelled','expired')),"
"'original221',(SELECT state FROM jobs WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND job_id='94047873-5088-433b-bc1b-490d3eafe0da' AND attempt_id='f071e6d6-8635-42f7-92fa-533c681edd8b'),"
"'memberships',(SELECT json_agg(q ORDER BY principal) FROM (SELECT principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='" + tenant + "' AND principal IN ('automation:" + tenant + "','simulated-testprincipal-a')) q)); COMMIT;")
observed = json.loads(run(['docker', 'exec', '-i', 'rust-discovery-server-postgres-1', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql.encode()))
live = observed['installation']
require(live and all(live[n] is True for n in ('ready', 'helper_ready', 'fresh', 'same_certificate', 'auth_fresh')) and live['blocked'] is False and observed['open_jobs'] == 0 and observed['original221'] == 'failed', 'SYSTEM_RENEW_ACTUAL_NORMAL_SYNC_AND_TERMINAL221')
needed = {'windows.base/1', 'rmm.sync.v1', 'helper.system.v1', 'system:run_script', 'script.full_maintenance/1', 'helper.binary.sha256:' + payload['helper_binary_sha256'], 'helper.policy.sha256:' + payload['helper_policy_sha256']}
require(needed <= set(live['capabilities']) and not {'linux.base/1', 'system:ensure_package', 'system:set_service_state', 'system:reboot'} & set(live['capabilities']), 'SYSTEM_RENEW_ACTUAL_NARROW_FINAL_CAPABILITIES')
memberships = observed['memberships']
require([m['principal'] for m in memberships] == actors and all(m['revoked_at'] is None and {'scripts:execute', 'system:execute'} <= set(m['permissions']) and m['kind'] == ('automation' if n == 0 else 'test_human') for n, m in enumerate(memberships)), 'SYSTEM_RENEW_SAME_EXISTING_AUTHORIZED_ACTORS')
new = json.loads(old_raw)
new['expires_at'] = (now + dt.timedelta(minutes=15)).isoformat()
new['scopes'][0].update(helper_binary_sha256=payload['helper_binary_sha256'], helper_policy_sha256=payload['helper_policy_sha256'], acceptance_evidence_id=evidence_id)
raw = encode(new)
create(epoch_intent, encode({'schema_version': 1, 'case_id': ident, 'old_policy_sha256': original_sha, 'new_policy_sha256': digest(raw), 'new_expires_at': new['expires_at'], 'automatic_retry': False}))
sync_directory(mounted.parent)
case.mkdir(mode=0o700)
create(case / 'intent.json', encode({'schema_version': 1, 'request': payload, 'old_policy_sha256': original_sha, 'old_policy_identity': identity(old_meta), 'new_policy_sha256': digest(raw), 'new_expires_at': new['expires_at'], 'database_readback': observed}))
create(case / 'original-policy.json', old_raw)
sync_directory(case)
sync_directory(case.parent)
stage_name = '.renew-' + ident + '.json'
stage = mounted / stage_name
create(stage, raw, 10001, 10001)
sync_directory(mounted)
require(directory(mounted, 10001) == mounted_identity and identity(policy_path.lstat()) == identity(old_meta) and policy_path.read_bytes() == old_raw and os.fstat(original.fileno()).st_ino == old_meta.st_ino, 'SYSTEM_RENEW_FINAL_NAMESPACE_CAS')
require({role: runtime(role) for role in ('api', 'gateway')} == before_roles, 'SYSTEM_RENEW_RUNTIME_CHANGED_BEFORE_SWAP')
os.replace(stage, policy_path)
sync_directory(mounted)
require(policy_path.read_bytes() == raw and policy_path.stat().st_uid == policy_path.stat().st_gid == 10001 and stat.S_IMODE(policy_path.stat().st_mode) == 0o600 and (case / 'original-policy.json').read_bytes() == old_raw, 'SYSTEM_RENEW_EXACT_FILE_READBACK')
require({role: runtime(role) for role in ('api', 'gateway')} == before_roles, 'SYSTEM_RENEW_RUNTIME_CHANGED_AFTER_SWAP')
result = {'schema_version': 1, 'case_id': ident, 'renewed': True, 'old_policy_sha256': original_sha, 'policy_sha256': digest(raw), 'expires_at': new['expires_at'], 'original_bytes_backup_verified': True, 'containers_unchanged': True, 'environment_unchanged': True, 'mounts_unchanged': True, 'memberships_changed': False, 'jobs_created': False, 'approvals_created': False, 'automatic_retry': False}
create(case / 'completed.json', encode(result))
sync_directory(case)
return result
finally:
os.close(lock)
def read_existing_policy_renewal(payload):
import hashlib
import json
import os
from pathlib import Path
import stat
import uuid
if os.geteuid() != 0 or set(payload) != {'operation', 'case_id'} or payload['operation'] != 'windows_system_existing_script_scope_renew_readback_v1':
raise RuntimeError('SYSTEM_RENEW_READBACK_INPUT')
ident = str(uuid.UUID(payload['case_id']))
if ident != payload['case_id']:
raise RuntimeError('SYSTEM_RENEW_READBACK_CASE')
parent = Path('/opt/rust-discovery/devstate/windows-system-policy')
case = parent / ('renew-' + ident)
active = parent / '5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33/mounted/policy.json'
epoch_path = active.parent.parent / 'renew-c4993009-intent.json'
def read(path, owner):
m = path.lstat()
if not stat.S_ISREG(m.st_mode) or m.st_nlink != 1 or m.st_uid != owner or stat.S_IMODE(m.st_mode) != 0o600 or m.st_size > 65536:
raise RuntimeError('SYSTEM_RENEW_READBACK_FILE')
raw = path.read_bytes()
after = path.lstat()
if (m.st_dev, m.st_ino, m.st_mtime_ns, m.st_size) != (after.st_dev, after.st_ino, after.st_mtime_ns, after.st_size):
raise RuntimeError('SYSTEM_RENEW_READBACK_CHANGED')
return raw
raw = read(active, 10001)
current_sha = hashlib.sha256(raw).hexdigest()
epoch = json.loads(read(epoch_path, 0)) if epoch_path.exists() else None
if epoch is not None and epoch['case_id'] != ident:
raise RuntimeError('SYSTEM_RENEW_READBACK_EPOCH_BOUND_TO_ANOTHER_CASE')
if not case.exists():
return {'read_only': True, 'case_present': False, 'epoch_intent_present': epoch is not None, 'policy_sha256': current_sha, 'retry_authorized': False}
m = case.lstat()
if not stat.S_ISDIR(m.st_mode) or m.st_uid != 0 or stat.S_IMODE(m.st_mode) != 0o700:
raise RuntimeError('SYSTEM_RENEW_READBACK_PRIVATE_CASE')
intent = json.loads(read(case / 'intent.json', 0))
backup_ok = False
if (case / 'original-policy.json').exists():
backup_ok = hashlib.sha256(read(case / 'original-policy.json', 0)).hexdigest() == intent['old_policy_sha256']
observed = 'unexpected_current_policy'
if current_sha == intent['old_policy_sha256']:
observed = 'expired_original_observed'
elif current_sha == intent['new_policy_sha256']:
observed = 'exact_replacement_observed'
completed = None
if (case / 'completed.json').exists():
completed = json.loads(read(case / 'completed.json', 0))
if completed['case_id'] != ident or completed['policy_sha256'] != intent['new_policy_sha256']:
raise RuntimeError('SYSTEM_RENEW_READBACK_COMPLETION_BINDING')
return {'schema_version': 1, 'read_only': True, 'case_present': True, 'observed': observed, 'policy_sha256': current_sha, 'original_bytes_backup_verified': backup_ok, 'completed': completed, 'retry_authorized': False, 'jobs_created': False, 'approvals_created': False}
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Prepare the existing stopped-pair8 controller; never invoke its effects.
Only fixed SDK/source/public evidence files may be staged separately. Final pair
and native nonstart221 proof are required before sealing any deployment input.
"""
import argparse
import hashlib
import json
from pathlib import Path
import uuid
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'deploy/windows/Install-DevelopmentPairSuccessor.ps1'
BASE_SHA='78e0e0111c08ab0c91774d7ef87e2f1e6ddf272629859af92c48292a289a42a4'
def sha(raw):return hashlib.sha256(raw).hexdigest()
def replace_once(text,old,new):
assert text.count(old)==1,'exact reviewed predecessor delta'
return text.replace(old,new,1)
def controller():
raw=BASE.read_bytes();assert sha(raw)==BASE_SHA,'reviewed original pair7 controller'
text=raw.decode()
text=replace_once(text,"$m.previous_revision -ne 6", "$m.previous_revision -ne 7")
text=replace_once(text,"'PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','Read'","'PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','RestoreActiveStopped','Read'")
text=text.replace('revision6 to7','revision7 to8').replace('revision6','revision7')
text=replace_once(text,"$m.old_helper_sha256 -cne '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'", "$m.old_helper_sha256 -cne '0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726'")
text=replace_once(text,"$previousRevision=6", "$previousRevision=7")
text=replace_once(text,"$previousCase=Join-Path $bootstrap ('job-passive-pair-'+$m.previous_case_id)","$previousCase=Join-Path $bootstrap ('job-stopped-pair-'+$m.previous_case_id)")
text=replace_once(text,"$previous.successor_revision -ne 6", "$previous.successor_revision -ne 7")
marker=". ([scriptblock]::Create($text.Substring($i,$j-$i)))"
auto_observer=r"""
# The previously authorized SYSTEM-script bootstrap already set Helper Auto.
# Bind this existing observed definition; do not change SCM configuration.
$serviceSource=(Get-Item Function:\Service).ScriptBlock.ToString()
$manualToken="`$mode='Manual'"
$at=$serviceSource.IndexOf($manualToken,[StringComparison]::Ordinal)
if($at-lt0-or$at-ne$serviceSource.LastIndexOf($manualToken,[StringComparison]::Ordinal)){throw 'Exact historical helper-mode observer changed.'}
Set-Item Function:\Service ([scriptblock]::Create($serviceSource.Replace($manualToken,"`$mode='Auto'")))
"""
text=replace_once(text,marker,marker+'\n'+auto_observer)
text=text.replace('successor_revision=7','successor_revision=8').replace('profile7','profile8')
old="alignment_verification_sha256,case_id,linux_proof_sha256,new_agent_sha256,new_helper_sha256,old_agent_sha256,old_config_sha256,old_helper_sha256,old_pin_sha256,old_profile_sha256,old_settings_sha256,pair_build_sha256,previous_case_id,previous_publication_sha256,previous_revision,schema_version,windows_proof_sha256"
new="alignment_verification_sha256,case_id,linux_proof_sha256,new_agent_sha256,new_helper_sha256,old_agent_sha256,old_config_sha256,old_helper_sha256,old_native_result_sha256,old_pin_sha256,old_profile_sha256,old_qualification_sha256,old_settings_sha256,pair_build_sha256,passive_codec_sha256,passive_render_input_sha256,passive_render_sha256,previous_case_id,previous_publication_sha256,previous_revision,schema_version,windows_proof_sha256"
text=replace_once(text,old,new)
old="if ($alignment.read_only -ne $true -or $alignment.admin_archive_verified -ne $true -or $alignment.helper_checkpoint -ne 201 -or $alignment.agent_checkpoint -ne 10137 -or $alignment.helper_last_decision -cne '2af359c5-5b5c-4992-b445-1c00e271a288' -or $alignment.ready -ne $false -or $alignment.helper_ready -ne $false -or $alignment.unlock -ne $false) { throw 'Actual closed G205 verification required.' }"
# Private, fixed bootstrap witness from actual native221 verification; not a
# product wire protocol, permission, retry, sync lease or approval.
new="""$expectedVerification='active_pending_job_events,grant_id,incident,not_started,old_grant_executed_again,original_unknown_preserved,original_unknown_sha256,raw_retained_job_events,ready,receipt_id,receipt_sha256,revision,state,helper_ready,unlock'
if((($alignment.PSObject.Properties.Name|Sort-Object)-join',')-cne(($expectedVerification.Split(',')|Sort-Object)-join',')-or$alignment.incident-ne221-or$alignment.grant_id-cne'97e705b8-fb2b-4158-84d9-d90595d1ce6e'-or$alignment.state-cne'failed'-or$alignment.revision-ne3-or$alignment.not_started-ne$true-or$alignment.original_unknown_preserved-ne$true-or$alignment.old_grant_executed_again-ne$false-or$alignment.original_unknown_sha256-cne'1f284b66578d61c4364cc0060a67ce9b467e1d661ed8885804391b51a6f18b1a'-or$alignment.raw_retained_job_events-ne1-or$alignment.active_pending_job_events-ne0-or$alignment.receipt_sha256-cnotmatch'^[0-9a-f]{64}$'-or[guid]::ParseExact($alignment.receipt_id,'D').ToString()-cne$alignment.receipt_id-or$alignment.ready-ne$false-or$alignment.helper_ready-ne$false-or$alignment.unlock-ne$false){throw 'Exact actual SDK verify_applied221 output required; no projected wrapper or fabricated witness.'}"""
text=replace_once(text,old,new)
old="foreach ($name in @('linux-proof.json','windows-proof.json')) { $proof=Get-Content -LiteralPath (Join-Path $inputFolder $name) -Raw|ConvertFrom-Json;if ($proof.verified -ne $true -or $proof.passed -ne 3 -or $proof.failed -ne 0) { throw 'Native targeted units have not passed.' } }"
new=r"""foreach($name in @('linux-proof.json','windows-proof.json')){
$proof=Get-Content -LiteralPath (Join-Path $inputFolder $name) -Raw|ConvertFrom-Json
if($name-ceq'linux-proof.json'){
if($proof.native_platform-cne'cloud-linux-x86_64'-or$proof.exit_code-ne0-or$proof.verified-ne$true-or$proof.uid-ne65534-or$proof.isolated_network-ne$true-or$proof.no_new_privs-ne$true-or$proof.stderr-cne''-or$proof.binary_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Actual original Cloud Linux receipt-contract result required.'}
$contract=$proof.stdout|ConvertFrom-Json
}else{
if($proof.native_platform-cne'windows11-amd64'-or$proof.sdk_sha256-cnotmatch'^[0-9a-f]{64}$'-or$null-eq$proof.actual_result){throw 'Actual original native Windows receipt-contract result required.'}
$contract=$proof.actual_result
}
foreach($field in @('valid_actual_signed_receipt','wrong_grant_rejected','wrong_original_hash_rejected','wrong_signature_rejected','original_helper_cache_refreshed_once','stale_cache_failure_reproduced','resolved_unlock_storage_guard_preserves_original','original_placeholder_retired','other_message_not_retired','other_raw_not_retired','physical_placeholder_preserved')){if($contract.$field-ne$true){throw 'Actual current nonstart221 contract incomplete.'}}
if($contract.effects-ne$false-or$contract.product_databases_opened-ne$false){throw 'Receipt-contract must have no product effects.'}
}"""
text=replace_once(text,old,new)
start=text.index(' $s=$utf8.GetString([IO.File]::ReadAllBytes((Baseline \'settings\')))')
end=text.index(" $c=Get-Content -LiteralPath (Baseline 'config')",start)
replacement=r''' $renderInputPath=Join-Path $inputFolder 'passive-input.json'
$renderPath=Join-Path $inputFolder 'passive-render.json'
foreach($entry in @(@($renderInputPath,$m.passive_render_input_sha256),@($renderPath,$m.passive_render_sha256))){CheckControl $entry[0] $false;if((Hash $entry[0])-cne$entry[1]){throw 'Typed passive renderer evidence changed.'}}
$ri=Get-Content -LiteralPath $renderInputPath -Raw|ConvertFrom-Json
$ro=Get-Content -LiteralPath $renderPath -Raw|ConvertFrom-Json
if($ri.schema_version-ne1-or$ri.current_settings_sha256-cne$m.old_settings_sha256-or(BytesHash ([byte[]]$ri.current_settings))-cne$m.old_settings_sha256-or$ri.new_agent_sha256-cne$m.new_agent_sha256-or$ri.new_helper_sha256-cne$m.new_helper_sha256-or$ro.source-cne'actual_rust_settings_codec'-or$ro.prepared_only-ne$true-or$ro.target_mutations-ne$false-or$ro.target_job_executed-ne$false-or$ro.effects_enabled-ne$false){throw 'Exact deny-only typed passive pair render required.'}
$codec=Join-Path (Join-Path $bootstrap $m.passive_codec_sha256) 'windows_script_pair_prepare.exe';CheckControl $codec $false
if((Hash $codec)-cne$m.passive_codec_sha256){throw 'Actual readonly typed codec artifact changed.'}
$settingsBytes=[byte[]]$ro.settings_bytes;$pinBytes=[byte[]]$ro.pin_bytes
$newHashes.settings=BytesHash $settingsBytes;$newHashes.pin=BytesHash $pinBytes
if($newHashes.settings-cne$ro.settings_sha256-or$newHashes.pin-cne$ro.pin_sha256){throw 'Actual typed passive bytes changed.'}
$old=Get-Content -LiteralPath (Baseline 'settings') -Raw|ConvertFrom-Json
$ns=$utf8.GetString($settingsBytes)|ConvertFrom-Json;$np=$utf8.GetString($pinBytes)|ConvertFrom-Json
if($old.schema_version-ne3-or$old.enable_effects-ne$true-or$old.max_runtime_seconds-ne30-or($old.allowed_script_profiles-join',')-cne'full_maintenance_v1'-or$ns.enable_effects-ne$false-or$ns.allow_reboot-ne$false-or$ns.max_runtime_seconds-ne30-or@($ns.allowed_services).Count-ne0-or$null-ne$ns.PSObject.Properties['allowed_script_profiles']-or$null-ne$ns.PSObject.Properties['allowed_msi_recipe_sha256']-or$ns.agent.binary_sha256-cne$m.new_agent_sha256-or$ns.helper.binary_sha256-cne$m.new_helper_sha256-or$np.policy_sha256-cne$newHashes.settings-or!(JsonEqual $ns.binding $old.binding)-or!(JsonEqual $np.binding $old.binding)){throw 'Only same-identity passive script pair transition.'}
'''
text=text[:start]+replacement+text[end:]
text=replace_once(text,"return [ordered]@{settings=$utf8.GetBytes($s);pin=$utf8.GetBytes($p);config=$configBytes}","return [ordered]@{settings=$settingsBytes;pin=$pinBytes;config=$configBytes}")
# The old script qualification belongs to the old image/policy. Keep its
# bytes, native file IDs AND ACL while retiring the active names, under
# both original locks before any new passive component can start.
declaration=r"""
function OriginalScriptQualification {
$q=[ordered]@{}
foreach($entry in @(@('qualification','system-qualification.json',$m.old_qualification_sha256),@('native_result','system-native-result.json',$m.old_native_result_sha256))){
$path=Join-Path $helperRoot $entry[1];$v=FileIdentity $path
if($v.sha256-cne$entry[2]){throw 'Exact old script qualification CAS required.'}
$q[$entry[0]]=$v
}
return $q
}
function ArchiveOriginalScriptQualification($original) {
StopCheck
if(Test-Path -LiteralPath (Marker 'qualification-archive-intent')){throw 'Existing qualification archive intent: readback only.'}
if(!(JsonEqual $original (OriginalScriptQualification))){throw 'Old script qualification changed after preparation.'}
Record 'qualification-archive-intent' @{id=$id;files=$original;manifest_sha256=$ManifestSha256}
$after=[ordered]@{}
foreach($entry in @(@('qualification','system-qualification.json'),@('native_result','system-native-result.json'))){
$name=$entry[0];$source=Join-Path $helperRoot $entry[1];$dest=Join-Path $work ('archived-'+$entry[1])
if(Test-Path -LiteralPath $dest){throw 'Original qualification archive already exists.'}
if(!(JsonEqual $original.$name (FileIdentity $source))){throw 'Original qualification CAS changed.'}
[IO.File]::Move($source,$dest)
$v=FileIdentity $dest
# Same-volume rename must retain bytes, file identity AND security;
# do not restrict/change the original descriptor or reconstruct a file.
foreach($field in @('sha256','file_id','volume_serial','acl_sha256')){if($v.$field-cne$original.$name.$field){throw 'Original qualification archive identity or ACL changed.'}}
if(Test-Path -LiteralPath $source){throw 'Old active qualification name still present.'}
$after[$name]=$v
}
Record 'qualification-archived' @{id=$id;files=$after;originals=$original;active_names_absent=$true;new_qualification_created=$false}
}
"""
text=replace_once(text,'$rendered=RenderPairFiles',declaration+'\n$rendered=RenderPairFiles')
text=replace_once(text,'$before=CurrentFiles;$device=PreservedNativeState','$before=CurrentFiles;$device=PreservedNativeState;$scriptQualification=OriginalScriptQualification')
text=replace_once(text,'new_hashes=$newHashes;original_services_stopped=$true;successor_revision=8;','new_hashes=$newHashes;script_qualification=$scriptQualification;original_services_stopped=$true;successor_revision=8;')
text=replace_once(text," foreach ($name in $locations.Keys) {\n $inputPath=Join-Path $work ('new-'+$name)"," ArchiveOriginalScriptQualification $preparedPair.script_qualification\n foreach ($name in $locations.Keys) {\n $inputPath=Join-Path $work ('new-'+$name)")
restore=r"""
if($Action-ceq'RestoreActiveStopped') {
StopCheck
$publication=LoadRecord 'profile-published';$installedPair=LoadRecord 'installed'
if($publication.id-cne$id-or$publication.successor_revision-ne8-or(Hash $target)-cne$publication.configuration.sha256){throw 'Actual published profile8 required before original config restoration.'}
foreach($name in @('agent','helper','settings','pin')){if((Hash $locations[$name])-cne$newHashes[$name]){throw 'Exact passive final pair required.'}}
if((Hash $config)-cne$newHashes.config-or(Hash (Join-Path $work 'old-config'))-cne$m.old_config_sha256){throw 'Exact current passive and preserved original active config required.'}
if(!(Test-Path -LiteralPath (Marker 'qualification-archived'))-or(Test-Path -LiteralPath (Join-Path $helperRoot 'system-qualification.json'))-or(Test-Path -LiteralPath (Join-Path $helperRoot 'system-native-result.json'))){throw 'Old qualification must remain archived; no new scope before actual native prerequisites.'}
if(Test-Path -LiteralPath (Marker 'active-config-restore-intent')){throw 'Existing restore intent means readback-only.'}
$locks=[RmmStoppedPairLocks]::new()
try {
StopCheck
$before=FileIdentity $config;$retained=PreservedNativeState
if(!(JsonEqual $before $installedPair.files.config)){throw 'Actual original passive config identity changed.'}
$active=Get-Content -LiteralPath (Join-Path $work 'old-config') -Raw|ConvertFrom-Json
if($active.enable_jobs-ne$true-or$active.windows_execution_profile-cne'powershell_51_remote_signed'-or$active.server_name-cne'discovery.ease-technologies.de'-or$active.state_directory-cne$agentState){throw 'Only original already authorized active client configuration.'}
Record 'active-config-restore-intent' @{id=$id;original_active_sha256=$m.old_config_sha256;current=$before;preserved=$retained;services_stopped=$true}
SwapFile 'config' (Join-Path $work 'old-config') $before $m.old_config_sha256 'active-config'
if(!(JsonEqual $retained (PreservedNativeState))){throw 'Original state changed during config restoration.'}
Record 'active-config-restored' @{id=$id;config=(FileIdentity $config);preserved=$retained;services_started=$false;scope_activated=$false;job_created=$false}
} finally {$locks.Dispose()}
Write-Output 'Original active config restored under original locks; pair remains stopped and SYSTEM scope unconfigured.';return
}
"""
text=replace_once(text,'# The qualified publisher\'s action bodies are excluded.',restore+'\n# The qualified publisher\'s action bodies are excluded.')
return text.encode()
def policy_controller():
# Same four typed public files and preservation/locking implementation as
# the first native script-scope bootstrap, without its already-completed
# Manual->Auto transition or its one historical no-effect resume exception.
import windows_system_job_bootstrap as base
text=base.APPLY_STOPPED
text=replace_once(text,'param([switch]$ResumeNoEffectEb285544)','$ResumeNoEffectEb285544=$false')
text=text.replace('windows_system_script_scope_stopped_v1','windows_system_script_successor_scope_stopped_v1')
text=replace_once(text,"$p.helper_start_transition.before-cne'Manual'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Manual'","$p.helper_start_transition.before-cne'Auto'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Auto'")
text=text.replace("Exact Manual to Auto helper transition only","Existing Helper Auto must remain Auto")
start=text.index("$stage='helper-autostart'\n")
end=text.index("$stage='final-preservation'",start)
text=text[:start]+r"""$stage='helper-autostart-unchanged'
$automatic=ServiceDefinitions
if(($automatic|ConvertTo-Json -Depth 6 -Compress)-cne($definitions|ConvertTo-Json -Depth 6 -Compress)-or$automatic.RmmDiscoverySystemHelper.start_mode-cne'Auto'-or$automatic.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Original automatic SCM definitions must remain unchanged'}
"""+text[end:]
text=replace_once(text,"helper_autostart='Auto';services=$automatic;","helper_autostart='Auto';helper_start_mode_changed=$false;services=$automatic;")
return text.encode()
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=['controller','policy-controller']);parser.add_argument('folder');args=parser.parse_args()
folder=Path(args.folder);folder.mkdir(mode=0o700,parents=True,exist_ok=True)
data=controller() if args.action=='controller' else policy_controller();path=folder/('Install-SystemScriptPairSuccessor.ps1' if args.action=='controller' else 'Install-SystemScriptSuccessorScope.ps1')
with path.open('xb')as f:f.write(data)
path.chmod(0o600)
print(json.dumps({'controller':str(path),'sha256':sha(data),'prepared_only':True,'target_mutated':False,'native_221_witness_pending':True,'final_pair_pending':True}))
if __name__=='__main__':main()