Files
rust-discovery/deploy/windows_system_scope_renew.py
2026-11-16 23:18:01 +01:00

301 lines
28 KiB
Python

#!/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')
require(len({m['Destination'] for m in c['Mounts']}) == len(c['Mounts']), 'SYSTEM_RENEW_UNIQUE_MOUNT_DESTINATIONS')
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': sorted(c['Mounts'], key=lambda mount: mount['Destination']), '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}
def complete_prepared_policy_renewal(payload):
"""Manual single-case completion only; preserve staged bytes and original expiry."""
import datetime as dt
import fcntl
import hashlib
import json
import os
from pathlib import Path
import stat
import subprocess
def check(value, code):
if not value: raise RuntimeError(code)
def canon(value): return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def sha(raw): return hashlib.sha256(raw).hexdigest()
def run(args, raw=None): return subprocess.run(args, input=raw, capture_output=True, check=True, timeout=25).stdout
def sync(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, value):
fd=os.open(path, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o600)
with os.fdopen(fd,'wb') as f: os.fchmod(f.fileno(),0o600);f.write(canon(value));f.flush();os.fsync(f.fileno())
def ident(m): return [m.st_dev,m.st_ino,m.st_uid,m.st_gid,stat.S_IMODE(m.st_mode),m.st_nlink]
def read(path, uid, inode, digest):
fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
with os.fdopen(fd,'rb') as f:
m=os.fstat(f.fileno());check(stat.S_ISREG(m.st_mode) and m.st_uid==m.st_gid==uid and m.st_nlink==1 and stat.S_IMODE(m.st_mode)==0o600 and m.st_ino==inode and m.st_size<=65536,'FINISH_FILE_METADATA')
raw=f.read(65537);check(sha(raw)==digest and ident(path.lstat())==ident(m),'FINISH_EXACT_FILE_CAS');return raw,m
case_id='f4de2612-fca6-4c3b-8fc6-2097bb21b278'
check(os.geteuid()==0 and payload=={'operation':'windows_system_complete_prepared_scope_renew_v1','case_id':case_id},'FINISH_FIXED_ROOT_CASE')
root=Path('/opt/rust-discovery');parent=root/'devstate/windows-system-policy';original=parent/'5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33';mounted=original/'mounted';case=parent/('renew-'+case_id);active=mounted/'policy.json';stage=mounted/('.renew-'+case_id+'.json')
for path,uid,mode in [(root,0,None),(root/'devstate',0,None),(parent,0,None),(original,0,0o700),(mounted,10001,0o700),(case,0,0o700)]:
m=path.lstat();check(stat.S_ISDIR(m.st_mode) and m.st_uid==m.st_gid==uid and not m.st_mode&0o022 and (mode is None or stat.S_IMODE(m.st_mode)==mode),'FINISH_PROTECTED_DIRECTORY')
old_sha='c4993009e62ef9c384ea11a2f201566c2e657c1ba3b452410bb2a9d4774b0169';new_sha='0730a000d55fc101385705e9531ccb998cc02f3c932109ac6922c193004fcac7'
expected={
'api':('d589e4100c3826320958788489908943c6f6e860df275ed2616ba7ea273470fd','f7c4f62069fe54d077478d417a3cca929059b7cf7050038d0988a20a39404759','26068c35192c67595bc1ac4cd2788eb76f087ca5c530351f3e3ffb0442eaff3e','8d38126b1e37e5b4d55083d66e52b3b3455ad2579b9e14e67b3c49a503b8c538'),
'gateway':('e778410788b2bfe5c004289831798d13780f2435e8511d9430ade549cc26097c','3c2684b4665674437bbff4d2282f80a4b73962af5bc3efd56718d0d96f7ce2fb','567409c041edaf575a540e68c077e280ce9c73fdb0a9feb4d82d904f99dd5047','a74b6ea46a0b05dfddc7870d7e028232acc45b7588c47b59b219948827311a32')}
image='sha256:f0f3b79153e1ecd9f878cd0436a3a48238a8296f71790cf89f20efe1073b8b86'
def runtime():
result={}
for role,(cid,config_hash,host_hash,mount_hash) in expected.items():
c=json.loads(run(['docker','inspect',cid]))[0];mounts=c['Mounts'];check(len({m['Destination'] for m in mounts})==len(mounts),'FINISH_UNIQUE_MOUNTS');ordered=sorted(mounts,key=lambda m:m['Destination'])
check(c['Id']==cid and c['Name']=='/rust-discovery-server-'+role+'-1' and c['State']['Running'] and c['Image']==image and sha(canon(c['Config']))==config_hash and sha(canon(c['HostConfig']))==host_hash and sha(canon(ordered))==mount_hash and sorted(c['NetworkSettings']['Networks'])==['rust-discovery-server_backend','rust-discovery-server_ingress'],'FINISH_ACTUAL_RUNTIME_DIGESTS')
result[role]={'container_id':cid,'image':image,'config_sha256':config_hash,'host_sha256':host_hash,'sorted_mounts_sha256':mount_hash}
return result
lock=os.open(root/'devstate/.windows-system-scope.lock',os.O_WRONLY|os.O_NOFOLLOW)
try:
lm=os.fstat(lock);check(stat.S_ISREG(lm.st_mode) and lm.st_uid==lm.st_gid==0 and lm.st_nlink==1 and stat.S_IMODE(lm.st_mode)==0o600,'FINISH_ORIGINAL_LOCK');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
check(not (case/'finish-intent.json').exists() and not (case/'completed.json').exists(),'FINISH_EXISTING_INTENT_READBACK_ONLY')
epoch_raw,_=read(original/'renew-c4993009-intent.json',0,286476,'cb72566d923722c6e1413fbcd41b96356a628fab637f41794bc1f45ae0814ef5');intent_raw,_=read(case/'intent.json',0,286478,'6afc2629226890f60abc6d353d75a22b24a5a8291799411b1cb76e9027a7bde2')
backup,_=read(case/'original-policy.json',0,286479,old_sha);old_raw,old_meta=read(active,10001,285460,old_sha);raw,stage_meta=read(stage,10001,286480,new_sha)
epoch=json.loads(epoch_raw);intent=json.loads(intent_raw);new=json.loads(raw);request=intent['request'];scope=new['scopes'][0];expiry='2026-11-16T22:23:25.321002+00:00'
tenant='11111111-1111-4111-8111-111111111111';agent='63ea15b2-0643-403d-b5b4-cba1288dbea3';asset='a176520e-8a91-4e93-a78b-8e7620f430e0';actors=['automation:'+tenant,'simulated-testprincipal-a']
check(epoch['case_id']==case_id and epoch['old_policy_sha256']==intent['old_policy_sha256']==old_sha and epoch['new_policy_sha256']==intent['new_policy_sha256']==new_sha and epoch['new_expires_at']==intent['new_expires_at']==new['expires_at']==expiry and epoch['automatic_retry'] is False and backup==old_raw and ident(old_meta)==intent['old_policy_identity'],'FINISH_ORIGINAL_EPOCH_AND_NAMESPACE')
check(request['case_id']==case_id and request['operation']=='windows_system_existing_expired_script_scope_renew_v1' and request['expected_roles']=={r:{'container_id':v[0],'image':image} for r,v in expected.items()} and request['helper_binary_sha256']=='744dd4e6fd6027cde3f9b7c1f0bbccee9ebbd13a3dd378335e53f1e7af68817e' and request['helper_policy_sha256']=='a65ca9de25d2a3269802a4877874947c76ee8b257adc5ff93a2f545b2797cf3e' and request['acceptance_evidence_id']=='8b70997e-edc5-4438-9870-8a3bb13f8f2b','FINISH_ORIGINAL_REQUEST')
check(new['schema_version']==3 and new['profile']=='development' and len(new['scopes'])==1 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['max_runtime_seconds']==30 and scope['allowed_services']==[] and scope['allowed_script_profiles']==['full_maintenance_v1'],'FINISH_SCRIPT_ONLY_SCOPE')
rebuilt=json.loads(old_raw);rebuilt['expires_at']=expiry;rebuilt['scopes'][0].update({k:request[k] for k in ['helper_binary_sha256','helper_policy_sha256','acceptance_evidence_id']});check(canon(rebuilt)==raw,'FINISH_ONLY_PREPARED_BYTES_NO_NEW_TTL')
check(dt.datetime.now(dt.timezone.utc)<dt.datetime.fromisoformat(expiry),'FINISH_ORIGINAL_WINDOW_EXPIRED')
runtime_before=runtime();key=(root/'devstate/jobs/ed25519.pem').lstat();check(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,'FINISH_JOB_KEY_STAT_ONLY')
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 agent_id='"+agent+"' AND asset_id='"+asset+"' 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']
check(live and all(live[k] is True for k in ['ready','helper_ready','fresh','same_certificate','auth_fresh']) and live['blocked'] is False and observed['open_jobs']==0 and observed['original221']=='failed','FINISH_FRESH_NORMAL_READY_NO_OPEN_JOBS')
needed={'windows.base/1','rmm.sync.v1','helper.system.v1','system:run_script','script.full_maintenance/1','helper.binary.sha256:'+request['helper_binary_sha256'],'helper.policy.sha256:'+request['helper_policy_sha256']};check(needed<=set(live['capabilities']) and not {'linux.base/1','system:ensure_package','system:set_service_state','system:reboot'}&set(live['capabilities']),'FINISH_ACTUAL_NARROW_CAPS')
members=observed['memberships'];check(members==intent['database_readback']['memberships'] and [m['principal'] for m in members]==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(members)),'FINISH_UNCHANGED_EXISTING_ACTORS')
# Everything above is read-only and may be inspected again before this
# one-shot marker. After it exists, any ambiguity means readback only.
check(runtime()==runtime_before and dt.datetime.now(dt.timezone.utc)<dt.datetime.fromisoformat(expiry),'FINISH_IMMEDIATE_RUNTIME_AND_EXPIRY')
read(active,10001,285460,old_sha);read(stage,10001,286480,new_sha)
create(case/'finish-intent.json',{'schema_version':1,'case_id':case_id,'old_policy_sha256':old_sha,'new_policy_sha256':new_sha,'original_expiry':expiry,'runtime':runtime_before,'database_readback':observed,'automatic_retry':False});sync(case)
check(read(active,10001,285460,old_sha)[0]==old_raw and read(stage,10001,286480,new_sha)[0]==raw,'FINISH_LAST_NAMESPACE_CAS')
os.replace(stage,active);sync(mounted)
check(read(active,10001,286480,new_sha)[0]==raw and not stage.exists() and read(case/'original-policy.json',0,286479,old_sha)[0]==backup and runtime()==runtime_before,'FINISH_PUBLICATION_READBACK')
result={'schema_version':1,'case_id':case_id,'renewed':True,'manually_completed_prepared_epoch':True,'old_policy_sha256':old_sha,'policy_sha256':new_sha,'expires_at':expiry,'original_expiry_preserved':True,'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',result);sync(case);return result
finally: os.close(lock)