Files
rust-discovery/deploy/windows/system_pipe_upgrade.py
T
2026-11-14 14:16:56 +01:00

565 lines
51 KiB
Python

#!/usr/bin/env python3
"""One preserving passive pipe-v2 pair upgrade; no target actions by default.
prepare stages immutable bootstrap artifacts and captures a read-only baseline.
enter needs that exact separately reviewed baseline hash and runs once. A lost
reply permits readback/finish only. Main access-root is read-only, including the
current indices: Root publishes those separately after reviewing this result.
"""
import argparse
import base64
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import uuid
import client_bootstrap as cb
import system_delegation_upgrade as u
require = cb.contract.require
ROOT = cb.ROOT
STATE = cb.EVIDENCE / 'system-pipe-upgrade'
ORIGINAL_RUNNER = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38'
OLD_AGENT = '89004ad3475af3fb8a03bdb1e63c3ef1f2a08d31d0d97193e02fe770a1d7f676'
OLD_HELPER = 'e6aacbdd691c8c56612a2ba205c48396defe70e7d527e031aa3a76a8ae5a3662'
OLD_POLICY = '007adf5f4932dcf68fa4c0c3ba601ec1996b350e7e3e1d14e89a31dd712e5703'
OLD_PIN = '126670bc6ed71aad76438ec588b739d3bc02d36ae305ce8f8b5613e4a9e11a15'
OLD_CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437'
OLD_RESULT_SHA = 'ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460'
PIPE_VERIFIER_SHA = '2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf'
sha, raw_sha, canonical, save = u.sha, u.raw_sha, u.canonical, u.save
def replace_once(text, old, new):
require(text.count(old) == 1, 'exact reviewed bootstrap splice')
return text.replace(old, new, 1)
def write_bytes(path, data):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(data); output.flush(); os.fsync(output.fileno())
# Reuse read-only witnesses only, bound to the historical runner hash below.
# None of its original hard-PID stop, File.Replace(NULL), start, or case logic
# is included. Every new mutation is visible in this file.
PREFIX = u.SCRIPT.split('\nfunction ReadIntent', 1)[0]
PREFIX = replace_once(PREFIX, 'RmmDelegationUpgradePayload', 'RmmPipeUpgradePayload')
PREFIX = replace_once(PREFIX, "@('state','enter','finish','readback')", "@('baseline','enter','finish','readback')")
PREFIX = replace_once(PREFIX, "('system-delegation-'+$p.id)", "('system-pipe-'+$p.id)")
PREFIX = replace_once(PREFIX, "'system-delegation-active-intent.json'", "'system-pipe-active-intent.json'")
for old, new in ((u.OLD_AGENT, OLD_AGENT), (u.OLD_HELPER, OLD_HELPER), (u.OLD_POLICY, OLD_POLICY), (u.OLD_PIN, OLD_PIN)):
PREFIX = replace_once(PREFIX, old, new)
NATIVE = r'''
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32.SafeHandles;
public static class RmmPipeNative {
public sealed class Held : SafeHandleZeroOrMinusOneIsInvalid {
public Held(IntPtr h):base(true){SetHandle(h);}
protected override bool ReleaseHandle(){return CloseHandle(handle);}
}
[StructLayout(LayoutKind.Sequential)] public struct FileId {
public ulong Volume;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=16)] public byte[] Id;
}
[StructLayout(LayoutKind.Sequential)] struct SidAndAttributes {public IntPtr Sid;public uint Attributes;}
[StructLayout(LayoutKind.Sequential)] struct Groups {public uint Count;public SidAndAttributes First;}
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool CloseHandle(IntPtr h);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(Held h,out long creation,out long exit,out long kernel,out long user);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(Held h,uint flags,StringBuilder image,ref uint size);
[DllImport("kernel32.dll",SetLastError=true)] static extern uint WaitForSingleObject(Held h,uint millis);
[DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(Held process,uint access,out IntPtr token);
[DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int kind,IntPtr data,int bytes,out int needed);
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int kind,out FileId id,uint size);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] public static extern SafeFileHandle CreateFile(string path,uint access,uint share,IntPtr security,uint creation,uint flags,IntPtr template);
public static Held Open(int pid){IntPtr h=OpenProcess(0x101000,false,pid);if(h==IntPtr.Zero)throw new Win32Exception();return new Held(h);}
public static bool Alive(Held h){return WaitForSingleObject(h,0)==258;}
public static bool Exited(Held h,uint timeout){return WaitForSingleObject(h,timeout)==0;}
static IntPtr Info(IntPtr token,int kind,out int bytes){
int needed;GetTokenInformation(token,kind,IntPtr.Zero,0,out needed);
if(needed<=0||needed>65536)throw new InvalidOperationException("Token size");
IntPtr p=Marshal.AllocHGlobal(needed);if(!GetTokenInformation(token,kind,p,needed,out bytes)){Marshal.FreeHGlobal(p);throw new Win32Exception();}return p;
}
public static Dictionary<string,object> Proof(Held h,int pid,string owner,string serviceSid,string image){
if(!Alive(h))throw new InvalidOperationException("Process not alive");
long creation,exit,kernel,user;if(!GetProcessTimes(h,out creation,out exit,out kernel,out user))throw new Win32Exception();
StringBuilder path=new StringBuilder(32768);uint length=32768;if(!QueryFullProcessImageName(h,0,path,ref length)||!String.Equals(path.ToString(),image,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Process image");
IntPtr token;if(!OpenProcessToken(h,8,out token))throw new Win32Exception();
try {
int bytes;IntPtr info=Info(token,1,out bytes);string actual;
try {actual=new SecurityIdentifier(Marshal.ReadIntPtr(info)).Value;}finally{Marshal.FreeHGlobal(info);}
if(actual!=owner)throw new InvalidOperationException("Process owner");
info=Info(token,2,out bytes);bool found=false;
try {int count=Marshal.ReadInt32(info);int offset=(int)Marshal.OffsetOf(typeof(Groups),"First");int stride=Marshal.SizeOf(typeof(SidAndAttributes));
if(count<0||count>1024||offset+(long)count*stride>bytes)throw new InvalidOperationException("Groups size");
for(int n=0;n<count;n++){SidAndAttributes g=(SidAndAttributes)Marshal.PtrToStructure(IntPtr.Add(info,offset+n*stride),typeof(SidAndAttributes));if(new SecurityIdentifier(g.Sid).Value==serviceSid&&(g.Attributes&4)!=0&&(g.Attributes&16)==0)found=true;}
}finally{Marshal.FreeHGlobal(info);}
if(!found||!Alive(h))throw new InvalidOperationException("Enabled service SID/process liveness");
return new Dictionary<string,object>{{"pid",pid},{"creation_filetime",creation.ToString(System.Globalization.CultureInfo.InvariantCulture)},{"owner_sid",actual},{"service_sid",serviceSid},{"service_sid_enabled",true},{"image",path.ToString()},{"kernel_handle_bound",true}};
}finally{CloseHandle(token);}
}
}
'@
function FileIdentity($path,[bool]$actor=$false){
Check $path $false $actor;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try{$id=New-Object RmmPipeNative+FileId;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmPipeNative+FileId]);if($size-ne24-or![RmmPipeNative]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Native file identity'}
return [ordered]@{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path $actor)}
}finally{$file.Dispose()}
}
function Kernel($role,$record,$held){
$owner='S-1-5-19';$sid=$agentSid;$image=$agentBinary;if($role-ceq'helper'){$owner=$sys;$sid=$helperSid;$image=$helperBinary}
$proof=[RmmPipeNative]::Proof($held,[int]$record.pid,$owner,$sid,$image)
if($proof.creation_filetime-cne$record.creation_filetime-or$proof.owner_sid-cne$record.owner_sid){throw 'SCM/kernel process identity mismatch'};return $proof
}
function ActualState([bool]$new){
$value=State $new
$value['files']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);config=(FileIdentity $config);ca=(FileIdentity (Join-Path $agentRoot 'server-ca.pem') $true);identity=(FileIdentity (Join-Path $agentState 'identity.json') $true);certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true);private_key=(FileIdentityMetadata (Join-Path $agentState 'device.key'))}
foreach($role in @('agent','helper')){$record=$value.service;if($role-ceq'helper'){$record=$value.helper_service}
$proof=$null;if($record.state-ceq'Running'){$held=[RmmPipeNative]::Open([int]$record.pid);try{$proof=Kernel $role $record $held;if(!(JsonEqual $record (Service $role))-or![RmmPipeNative]::Alive($held)){throw 'SCM/kernel generation changed during proof'}}finally{$held.Dispose()}}
$value[$role+'_kernel']=$proof
};return $value
}
# FILE_READ_ATTRIBUTES only: no key content read/hash/export. This also binds
# the private key's actual native FileID, not merely a timestamp/name.
function FileIdentityMetadata($path){
Check $path $false $true;$i=Get-Item -LiteralPath $path -Force;$h=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero)
try{if($h.IsInvalid){throw 'Private metadata-only handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($h,18,[ref]$id,24)){throw 'Private metadata-only native FileID'};return @{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$i.Length;creation_ticks=$i.CreationTimeUtc.Ticks.ToString();last_write_ticks=$i.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(AclHash $path);private_key_read=$false}}finally{$h.Dispose()}
}
function SameOriginal($before,$after){
Preserved $before $after $false
if(!(JsonEqual $before.files $after.files)){throw 'Original four files/config/private metadata CAS'}
foreach($role in @('service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$role $after.$role)){throw 'Fresh original kernel/SCM generation changed; new reviewed baseline required'}}
}
function PreserveImmutableFiles($before,$after,[bool]$frozen){
Preserved $before $after $frozen
foreach($label in @('config','ca','identity','certificate','private_key')){if(!(JsonEqual $before.files.$label $after.files.$label)){throw 'Original immutable PKI/config native FileID/metadata changed'}}
}
'''
# The original fixed-role SCM configuration checks are reused exactly. Unlike
# Service(), this readback projection makes no running-process proof claim and
# honestly exposes pending/raw State/PID without changing a service.
READBACK_SERVICE = "\nfunction ReadbackService($role){" + u.SCRIPT.split('function Service($role){', 1)[1].split(' $processId=', 1)[0] + r'''
$state=[string]$service.State;if(!$state-or$state.Length-gt64){throw 'Bounded raw SCM state'}
return [ordered]@{state=$state;pid=[uint32]$service.ProcessId;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)));process_identity_verified=$false;read_only=$true}
}
'''
PHASES = r'''
CheckControl $boot $true
if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SystemPipeUpgrade.ps1')-or(Hash $PSCommandPath)-cne$p.script_sha256){throw 'Actual executing pipe-upgrade source'}
if($p.action-ceq'baseline'){$before=ActualState $false;if($before.service.state-cne'Running'-or$before.helper_service.state-notin@('Running','Stopped')-or$before.journal.pending_inventory_events-ne0){throw 'Settled original passive baseline'};$before|ConvertTo-Json -Depth 40 -Compress;exit 0}
function ReadCase{
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;CheckControl $active $false
$i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json
if((($i.payload.PSObject.Properties.Name|Sort-Object)-join',')-cne(($p.PSObject.Properties.Name|Sort-Object)-join',')){throw 'Original exact pipe payload shape'}
foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $i.payload.$field $p.$field)){throw 'Original exact pipe intent'}}
if($a.id-cne$p.id-or$a.script_sha256-cne$p.script_sha256-or$a.baseline_sha256-cne$p.baseline_sha256){throw 'Original active pipe intent'};return $i
}
if($p.action-ceq'readback'){
function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
$i=ReadCase;$phases=[ordered]@{};foreach($label in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','helper-already-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))}
@{read_only=$true;id=$p.id;phase_receipts=$phases;service=(ReadbackService 'agent');helper_service=(ReadbackService 'helper');hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)}}|ConvertTo-Json -Depth 40 -Compress;exit 0
}
if($p.action-ceq'finish'){
$i=ReadCase;$after=ActualState $true;PreserveImmutableFiles $i.before $after $false
CheckControl (Join-Path $folder 'frozen.json') $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;PreserveImmutableFiles $frozen $after $false
foreach($role in @('agent','helper')){CheckControl (Join-Path $folder ($role+'-started.json')) $false;$started=Get-Content -LiteralPath (Join-Path $folder ($role+'-started.json')) -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.state-cne'Running'-or!(JsonEqual $started.service $live)-or!(JsonEqual $started.kernel $after.($role+'_kernel'))){throw 'Same single-start actual component instance required'}}
@{read_only=$true;completed=$true;id=$p.id;native=$after;original=$i.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0
}
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}
$baselineBytes=[Convert]::FromBase64String($p.baseline_base64);if((BytesHash $baselineBytes)-cne$p.baseline_sha256){throw 'Exact separately reviewed baseline bytes'};$baseline=[Text.Encoding]::UTF8.GetString($baselineBytes)|ConvertFrom-Json
$before=ActualState $false;SameOriginal $baseline $before
if($before.journal.pending_inventory_events-ne0-or$before.service.state-cne'Running'){throw 'Original ACK and running agent required'}
$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=$null
try{
$null=Kernel 'agent' $before.service $heldAgent
if($before.helper_service.state-ceq'Running'){$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid);$null=Kernel 'helper' $before.helper_service $heldHelper}
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;script_sha256=$p.script_sha256;baseline_sha256=$p.baseline_sha256;no_jobs=$true}
function StopHeld($role,$record,$held){
$live=Service $role;if(!(JsonEqual $record $live)){throw 'SCM identity changed before own stop'};$null=Kernel $role $record $held
$name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{stop_once=$true;service=$record}
Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(![RmmPipeNative]::Exited($held,20000)){throw 'Pinned original process not exited'}
WriteNew (Join-Path $folder ($role+'-stopped.json')) @{original=$record;kernel_process_exited=$true}
}
StopHeld 'agent' $before.service $heldAgent
if($null-ne$heldHelper){StopHeld 'helper' $before.helper_service $heldHelper}else{if((Service 'helper').state-cne'Stopped'){throw 'Manual helper changed since reviewed stopped baseline'};WriteNew (Join-Path $folder 'helper-already-stopped.json') @{observed_stopped=$true;stop_called=$false;start_called=$false}}
$frozen=ActualState $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0-or!(JsonEqual $before.files $frozen.files)){throw 'Stopped original complete pair/file identities'};WriteNew (Join-Path $folder 'frozen.json') $frozen
function Backup($label,$path,$expected){
$identity=FileIdentity $path;if(!(JsonEqual $identity $before.files.$label)-or$identity.sha256-cne$expected){throw 'Original backup file identity/hash/ACL'}
$backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup
if((Hash $backup)-cne$expected){throw 'Exact private backup bytes'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{original=$identity;backup=(FileIdentity $backup);original_sddl=(Get-Acl -LiteralPath $path).Sddl}
}
Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin
$settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic closed reciprocal settings'}
WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes
function Swap($label,$destination,$source,$oldHash,$newHash){
if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'Both stopped for all four file replacements'}
foreach($other in @('agent','helper','settings','pin')){CheckControl (Join-Path $folder ($other+'-backup.json')) $false;if(!(Test-Path -LiteralPath (Join-Path $folder ($other+'-original')))){throw 'All four private backups precede first replacement'}}
$old=FileIdentity $destination;$sddl=(Get-Acl -LiteralPath $destination).Sddl;$nativeBackup=Join-Path $folder ($label+'-native-original');$candidate=Join-Path $folder ($label+'-candidate')
if(!(JsonEqual $old $before.files.$label)-or$old.sha256-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(Test-Path -LiteralPath $nativeBackup)){throw 'Fresh destination/source/backup CAS'}
[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;$candidateId=FileIdentity $candidate;if($candidateId.sha256-cne$newHash){throw 'Complete staged replacement'}
WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old=$old;candidate=$candidateId;native_backup=$nativeBackup;source_sha256=$p.script_sha256}
if(!(JsonEqual (FileIdentity $destination) $old)-or!(JsonEqual (FileIdentity $candidate) $candidateId)-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate file-ID/hash/ACL CAS'}
[IO.File]::Replace($candidate,$destination,$nativeBackup)
PrivateBackupAcl $nativeBackup;$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne$old.acl_sha256){throw 'Exact actual replacement/explicit native backup/ACL'}
WriteNew (Join-Path $folder ($label+'-replaced.json')) @{original=$old;current=(FileIdentity $destination);native_backup=(FileIdentity $nativeBackup);original_backup=(FileIdentity (Join-Path $folder ($label+'-original')))}
}
Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent
Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper
Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy
Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin
$swapped=ActualState $true;PreserveImmutableFiles $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files while both stopped'};WriteNew (Join-Path $folder 'swapped.json') $swapped
function StartOnce($role){
$checked=ActualState $true;PreserveImmutableFiles $frozen $checked $false;if((Service $role).state-cne'Stopped'){throw 'First exact selected start only'};$name=$helperName;if($role-ceq'agent'){$name=$agentName}
WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true;all_four_files_verified=$true}
Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
$s=Service $role;$held=[RmmPipeNative]::Open([int]$s.pid);try{$kernel=Kernel $role $s $held;WriteNew (Join-Path $folder ($role+'-started.json')) @{service=$s;kernel=$kernel}}finally{$held.Dispose()}
}
StartOnce 'helper';StartOnce 'agent';$after=ActualState $true;PreserveImmutableFiles $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after
@{entered=$true;id=$p.id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
}finally{$heldAgent.Dispose();if($null-ne$heldHelper){$heldHelper.Dispose()}}
'''
SCRIPT = PREFIX + '\n' + NATIVE + READBACK_SERVICE + '\n' + PHASES
PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1')
LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1').replace('RmmTransportPayload', 'RmmPipeUpgradePayload')
class Access:
"""Explicit read-only access roots; never redirects source/manifest globals."""
def __init__(self, root):
self.root = Path(root).absolute()
require(self.root == self.root.resolve() and self.root != ROOT.resolve(), 'separate real access root, no symlink/copy')
self.evidence = self.root / 'devstate/windows-client'
def powershell(self, source, payload, timeout=180):
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
wrapped = "try {\n" + source + "\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}"
command = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand ' + base64.b64encode(wrapped.encode('utf-16le')).decode()
result = subprocess.run(access['ssh_prefix'] + [command], input=canonical(payload) + b'\n', capture_output=True, timeout=timeout)
if result.returncode:
# Fixed error identifiers/line only; never raw stderr/payload/commands.
safe = dict(returncode=result.returncode, stdout_bytes=len(result.stdout), stderr_bytes=len(result.stderr))
try:
error = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
if error.get('bootstrap_error') is True:
safe.update(error_id=error.get('error_id'), line=error.get('line'))
except (ValueError, AttributeError):
pass
save(STATE / ('remote-error-' + str(uuid.uuid4()) + '.json'), safe)
raise RuntimeError('fixed pipe upgrade bootstrap incomplete; readback only')
return json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
def stage(self, path, name):
require(name in ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'RuntimeStateProbe.exe', 'SystemStateProbe.exe', 'SystemPipeUpgrade.ps1'), 'fixed stage names')
path = Path(path)
digest = sha(path)
prepare = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
observed = self.powershell(prepare, dict(sha256=digest))
if not observed['already_uploaded']:
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
prefix = access['ssh_prefix']
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
require(result.returncode == 0, 'immutable exact bootstrap transfer; no retry')
observed = self.powershell(prepare, dict(sha256=digest))
require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'same exact existing-or-new stage')
def server(self, function, payload):
cloud = u.transport.cloud
require(function in (cloud.server, u.auto.server_state, u.transport.server_transport.server_evidence), 'fixed read-only server witnesses')
# The inherited parser is strict data parsing, not source/eval. Its ROOT
# only checks the source .gitignore; its supplied path remains Main.
cfg = cloud.bootstrap.access.load_config(self.root / 'credentials/server.conf')
ssh = ['ssh', '-F', '/dev/null', '-T', '-p', cfg.get('port', '22'), '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), cfg['username'] + '@' + cfg['address'], 'python3 -']
code = ('import os,json,subprocess,base64,hashlib,ssl,http.client,socket,uuid,pwd\nfrom pathlib import Path\n' + inspect.getsource(cloud.bootstrap.require) + '\n' + inspect.getsource(function) + '\ntry:\n print(json.dumps(' + function.__name__ + '(' + repr(payload) + ')))\nexcept Exception as error:\n print(json.dumps(dict(error="READONLY_WITNESS_INCOMPLETE",kind=type(error).__name__)))\n')
result = subprocess.run(ssh, input=code.encode(), capture_output=True, timeout=60)
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'bounded readonly server witness')
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
require('error' not in value, 'readonly server witness incomplete')
return value
def server_state(self):
cloud = u.transport.cloud
linux = cb.contract.protected_json(self.root / 'devstate/cloud-mvp-final-closeout.json')
require(linux['verified'] is True, 'accepted Linux target only')
counts = {name: self.server(cloud.server, dict(kind='gate', tenant_id=tenant, agent_id=agent)) for name, tenant, agent in (
('windows', cloud.TENANT, u.transport.AGENT), ('linux', linux['target']['tenant_id'], linux['target']['agent_id']))}
flags = self.server(u.auto.server_state, {})
require(u.auto.flags_disabled(flags) and counts['windows'] == dict(jobs=0, outbox=0, permits=0, unresolved=0), 'closed hooks and Windows zero-job gate')
return dict(counts=counts, flags=flags)
def observe(self, ident):
return self.server(u.transport.server_transport.server_evidence, dict(tenant_id=u.transport.cloud.TENANT, agent_id=u.transport.AGENT, fault_id=ident))
def device_and_denials(self):
bridge = self
class ReadBackend(u.transport.cloud.Backend):
def request(self, body):
if body['method'] == 'tools/call':
require(body['params']['name'] == 'inventory.get_device', 'only stored inventory reads')
else:
require(body['method'] in ('initialize', 'notifications/initialized'), 'only MCP read session')
return bridge.server(u.transport.cloud.server, dict(kind='http', path='/mcp', method='POST', headers=self.headers, body=body, principal=self.principal))
device = ReadBackend().call('inventory.get_device', dict(tenant_id=u.transport.cloud.TENANT, asset_id=u.transport.ASSET))
require(device['agent_id'] == u.transport.AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1', 'heartbeat/1'} and device['presence'] == 'online', 'honest unchanged passive inventory')
denied = []
backend = ReadBackend('b')
for tenant in (u.transport.cloud.TENANT, '22222222-2222-4222-8222-222222222222'):
backend.sequence += 1
response = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device', arguments=dict(tenant_id=tenant, asset_id=u.transport.ASSET))))
data = response.get('data', {})
require('error' in data or data.get('result', {}).get('isError'), 'foreign tenant denied')
denied.append(dict(tenant_id=tenant, denied=True))
return device, denied
def dependencies():
modules = [cb, cb.contract, u, u.transport, u.auto, u.transport.cloud, u.transport.cloud.bootstrap, u.transport.cloud.bootstrap.access, u.transport.server_transport, u.qualification, u.qualification.feature, u.qualification.previous, u.original_helper]
return {str(Path(m.__file__).resolve().relative_to(ROOT)): sha(m.__file__) for m in modules}
def guards():
require(sha(u.__file__) == ORIGINAL_RUNNER, 'immutable original read-only witness source')
require('function PinProcess' not in PREFIX and 'function Swap' not in PREFIX and 'function StopPinned' not in PREFIX and 'function StartOnce' not in PREFIX, 'historical mutations excluded')
require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in SCRIPT and '[IO.File]::Replace($candidate,$destination,$null)' not in SCRIPT, 'explicit additional absent native backup')
ordered = [SCRIPT.index(token) for token in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")]
require(ordered == sorted(ordered), 'all backups before any replacement; all replacements before helper/agent starts')
require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1, 'single fixed-role control primitives')
require(all(word not in SCRIPT + LAUNCH for word in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass')), 'no install/reconfigure/cleanup/reboot/automatic rollback')
# Fresh isolated interpreter: the Pipe pack deliberately imports its transport
# modules from Main. Reusing its module in this interpreter would accidentally
# reuse our cached worktree client_bootstrap and corrupt the source/access split.
# This code calls verification/read-only proof parsing ONLY, never native().
VERIFY_PACK = r'''
import hashlib,importlib.util,json,re,sys,uuid
from pathlib import Path
path=Path(sys.argv[1]);spec=importlib.util.spec_from_file_location('fixed_pipe_pack',path)
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
manifest_path=Path(sys.argv[2]).resolve();proof_path=Path(sys.argv[3]).resolve()
manifest=pack.verified(manifest_path) # full current code/access hashes + Linux80/Windows58 Core proofs
proof=pack.cb.contract.protected_json(pack.private_file(proof_path));require=pack.require
case=proof['case_id'];require(str(uuid.UUID(case))==case and proof_path==pack.NATIVE/case/'passed.json','exact native pipe case namespace')
require(proof['verified'] is True and proof['manifest_path']==str(manifest_path) and proof['manifest_sha256']==pack.sha(manifest_path) and proof['no_jobs'] is True and proof['clock_adapter_qualified'] is False and proof['local_service_proof'] is False and proof['native_pipe_proof'] is False,'actual same pipe manifest units, no runtime capability')
intent=pack.cb.contract.protected_json(proof_path.parent/'intent.json')
require(intent['id']==case and intent['manifest_path']==str(manifest_path) and intent['manifest_sha256']==pack.sha(manifest_path) and intent['runner_sha256']==pack.sha(path) and intent['script_sha256']==hashlib.sha256(pack.SCRIPT.encode()).hexdigest(),'exact executed native unit source/manifest')
require(pack.cb.contract.protected_json(proof_path.parent/'started-local.json')['start_once'] is True,'original create-once native execution intent')
before=pack.cb.contract.protected_json(proof_path.parent/'server-before.json')
require(pack.auto.flags_disabled(before['flags']) and before['counts']['windows']==dict(jobs=0,outbox=0,permits=0,unresolved=0),'original closed native zero-job scope')
actual=proof['native']
require(actual['completed'] is True and actual['manifest_sha256']==pack.sha(manifest_path) and set(actual['reports'])==set(pack.COUNTS) and actual['both_lists_verified_before_any_test'] is True and actual['bootstrap_administrator_units'] is True and actual['local_service_proof'] is False and actual['native_pipe_proof'] is False and actual['rmm_jobs'] is False and actual['product_state_writes'] is False,'actual completed narrow units only')
for kind,count in pack.COUNTS.items():
report=actual['reports'][kind];listed=report['listed'];run=report['result']
names=re.findall(r'^(.+): test\r?$',listed['stdout'],re.M)
require(report['sha256']==manifest['artifacts'][kind]['sha256'] and names==report['names']==pack.TESTS[kind] and len(set(names))==count and type(listed['exit_code']) is int and listed['exit_code']==0 and type(run['exit_code']) is int and run['exit_code']==0 and listed['timed_out'] is False and run['timed_out'] is False and re.search(r'test result: ok\. '+str(count)+r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',run['stdout']),'all exact 23/7 native cases, no ignored/filtered/timeout')
print(json.dumps(manifest))
'''
def qualified(manifest_path, proof_path):
verifier = ROOT / 'deploy/windows/system_pipe_acceptance.py'
require(sha(verifier) == PIPE_VERIFIER_SHA, 'exact independently reviewed Pipe-v2 pack verifier')
result = subprocess.run([sys.executable, '-I', '-c', VERIFY_PACK, str(verifier), str(manifest_path), str(proof_path)], capture_output=True, timeout=60)
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'fresh isolated read-only Pipe verifier/native proof; details withheld')
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['transport_version'] == 2 and value['native_counts_expected'] == dict(lib=23, bin=7), 'Pipe-v2 manifest, never historical delegation relabeling')
return value
def prior(access):
runtime_path = access.evidence / 'current-runtime.json'
components_path = access.evidence / 'current-components.json'
runtime = cb.contract.protected_json(runtime_path)
components = cb.contract.protected_json(components_path)
result_path = access.evidence / ('system-delegation-upgrade/' + OLD_CASE + '/result.json')
require(sha(result_path) == OLD_RESULT_SHA, 'independently accepted original joint result')
result = cb.contract.protected_json(result_path)
require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted closed passive generation')
evidence = dict(path=str(result_path.resolve()), sha256=OLD_RESULT_SHA)
require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['evidence'] == components['evidence'] == evidence and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['transport'] == 'auto' and runtime['windows_jobs_enabled'] is False and runtime['clock_adapter_qualified'] is False and runtime['system_helper_client_feature'] is True and components['windows_jobs_enabled'] is False and components['clock_adapter_qualified'] is False and components['helper_effects_enabled'] is False, 'current accepted four-file indices, no adoption of readback')
recovery = access.evidence / 'system-delegation-recovery/595dd1da-0d7f-4364-9040-a75e16c6da83/acceptance.json'
require(sha(recovery) == '5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb' and cb.contract.protected_json(recovery)['verified'] is True, 'accepted original explicit-backup recovery preserved')
original = cb.contract.protected_json(result_path.parent / 'intent.json')
settings = base64.b64decode(original['payload']['settings_base64'], validate=True)
require(raw_sha(settings) == OLD_POLICY and raw_sha(base64.b64decode(original['payload']['pin_base64'], validate=True)) == OLD_PIN, 'exact original reciprocal public settings')
return dict(runtime=runtime, components=components, runtime_sha256=sha(runtime_path), components_sha256=sha(components_path), result_sha256=OLD_RESULT_SHA), result, json.loads(settings, object_pairs_hook=cb.contract.strict_object)
def passive_settings(old, agent, helper):
require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services', 'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1 and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30 and old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER, 'exact original closed public settings')
require(all(isinstance(h, str) and len(h) == 64 and all(c in '0123456789abcdef' for c in h) for h in (agent, helper)), 'qualified new image hashes')
new = json.loads(canonical(old)); new['agent']['binary_sha256'] = agent; new['helper']['binary_sha256'] = helper
settings = canonical(new); policy = raw_sha(settings)
pin = canonical(dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper']))
return settings, pin, policy
def leaves(access):
path = access.evidence / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json'
require(sha(path) == u.INTENT_PREPARATION_SHA, 'accepted original empty-leaf preparation')
proof = cb.contract.protected_json(path)
require(proof['verified'] is True and proof['sqlite_initialized'] is False, 'not a store/SQLite qualification')
created_path = path.parent / 'created.json'
require(sha(created_path) == proof['native_created_sha256'], 'original native empty-leaf receipt')
created = cb.contract.protected_json(created_path)
items = {v['name']: v for v in created['leaves']}
require(set(items) == {'system-intents.sqlite', 'system-intents.sqlite-journal'} and all(v['length'] == 0 for v in items.values()), 'exact two original zero-byte leaves')
return {label: dict(name=name, acl_sha256=raw_sha(items[name]['sddl'].encode())) for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]}
def remote(access, intent, action):
require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'immutable new pipe bootstrap source')
return access.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action)))
def load(ident, access):
require(str(uuid.UUID(ident)) == ident, 'canonical original case UUID')
folder = STATE / ident
intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__) and intent['script_sha256'] == raw_sha(SCRIPT.encode()) and intent['dependencies'] == dependencies() and intent['access_root'] == str(access.root), 'same source/dependencies/access root case')
manifest = qualified(Path(intent['manifest_path']), Path(intent['qualification_path']))
require(sha(intent['manifest_path']) == intent['payload']['manifest_sha256'] and sha(intent['qualification_path']) == intent['payload']['qualification_sha256'] and manifest['artifacts']['agent']['sha256'] == intent['payload']['new_agent'] and manifest['artifacts']['helper']['sha256'] == intent['payload']['new_helper'], 'same actually native-qualified new pair')
return folder, intent
def prepare(access, manifest_path, proof_path):
guards()
manifest = qualified(manifest_path, proof_path)
indices, accepted, old = prior(access)
settings, pin, policy = passive_settings(old, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256'])
require(manifest['artifacts']['agent']['sha256'] != OLD_AGENT and manifest['artifacts']['helper']['sha256'] != OLD_HELPER, 'new coordinated pipe pair, no old source round')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
script_sha = raw_sha(SCRIPT.encode())
payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN, new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'], new_policy=policy, new_pin=raw_sha(pin), config_sha256=accepted['native']['config_sha256'], probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'], manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode(), intent_leaves=leaves(access))
draft = dict(id=ident, started_at=cb.contract.now().isoformat(), access_root=str(access.root), runner_sha256=sha(__file__), script_sha256=script_sha, manifest_path=str(manifest_path.resolve()), qualification_path=str(proof_path.resolve()), dependencies=dependencies(), original_indices=indices, payload=payload, no_jobs=True)
save(folder / 'prepare-intent.json', draft)
for name, data in [('runner.py', Path(__file__).read_bytes()), ('SystemPipeUpgrade.ps1', SCRIPT.encode())]:
write_bytes(folder / name, data)
for kind in ('agent', 'helper', 'probe', 'system_probe'):
item = manifest['artifacts'][kind]
require(sha(item['path']) == item['sha256'], 'qualified staged artifact bytes')
access.stage(item['path'], item['name'])
access.stage(folder / 'SystemPipeUpgrade.ps1', 'SystemPipeUpgrade.ps1')
before = remote(access, draft, 'baseline')
expected = accepted['native']
for field in ('agent_id', 'asset_id', 'binary_sha256', 'helper_sha256', 'policy_sha256', 'pin_sha256', 'config_sha256', 'config_acl_sha256', 'binary_acl_sha256', 'helper_binary_acl_sha256', 'settings_acl_sha256', 'pin_acl_sha256', 'public_hashes', 'identity_acls', 'private_key_metadata'):
require(before[field] == expected[field], 'accepted original identity/PKI/config/four-file ACLs; no private key read')
for field in ('database_file_id', 'database_creation', 'identity_sha256', 'schema'):
require(before['journal'][field] == expected['journal'][field], 'same actual original telemetry database identity')
for field in ('helper_ledger', 'executor_lock', 'intent_store'):
require(before['helper_witness'][field] == expected['helper_witness'][field], 'same actual helper DB/lock/FileIDs/zero-byte leaves')
for role in ('service', 'helper_service'):
for field in ('start_name', 'start_mode', 'path', 'service_type', 'sid_type', 'service_acl_sha256'):
require(before[role][field] == expected[role][field], 'original exact SCM account/config/ACL')
baseline = canonical(before)
write_bytes(folder / 'baseline.json', baseline)
payload.update(baseline_base64=base64.b64encode(baseline).decode(), baseline_sha256=raw_sha(baseline))
draft['payload'] = payload
save(folder / 'intent.json', draft)
save(folder / 'server-before.json', access.server_state())
central = access.observe(ident)['device']; require(central and central['agent_id'] == u.transport.AGENT, 'original stored authenticated device')
save(folder / 'central-before.json', central)
print(json.dumps(dict(id=ident, prepared=True, no_component_mutation=True, baseline_sha256=raw_sha(baseline), needs_explicit_review_before_enter=True)))
def enter(access, ident, baseline_sha):
folder, intent = load(ident, access)
require(sha(folder / 'baseline.json') == intent['payload']['baseline_sha256'] == baseline_sha, 'explicit reviewed exact baseline required')
indices, _, _ = prior(access)
require(indices == intent['original_indices'] and access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both original current indices and server gates unchanged')
save(folder / 'enter-attempt.json', dict(enter_once=True, baseline_sha256=baseline_sha, lost_reply_readback_only=True))
result = remote(access, intent, 'enter')
require(result.get('entered') is True and result['id'] == ident, 'actual same single transition reply')
save(folder / 'entered.json', result)
print(json.dumps(dict(id=ident, entered=True, continuation='finish/readback only; never repeat enter')))
def finish(access, ident, read_only=False):
folder, intent = load(ident, access)
action = 'readback' if read_only else 'finish'
observed = remote(access, intent, action)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed)
require(observed['read_only'] is True and observed['id'] == ident, 'only existing case readback')
if read_only:
print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return
require(observed['completed'] is True, 'actual complete pair preservation')
result_path = folder / 'result.json'
if result_path.exists():
previous = cb.contract.protected_json(result_path)
require(previous['verified'] is True and all(previous['native'][role] == observed['native'][role] for role in ('service', 'helper_service')), 'same completed current instances; no republication or mutation')
print(json.dumps(dict(id=ident, verified=True, retained_original_result=True, main_indices_published=False))); return
# Two genuinely new server heartbeats after both single starts, not cached
# contacts from baseline, and no new network-agent jobs/capabilities.
after = cb.contract.timestamp(intent['started_at']); baseline = cb.contract.protected_json(folder / 'central-before.json')
watermark = access.observe(ident)['device']
require(watermark and watermark['agent_id'] == u.transport.AGENT and watermark['last_contact_at'], 'post-finish server heartbeat watermark')
deadline = time.monotonic() + 150; first = None
while True:
evidence = access.observe(ident); device = evidence['device']
if device and device['transport'] == 'wss' and device['last_contact_at'] and cb.contract.timestamp(device['last_contact_at']) > cb.contract.timestamp(watermark['last_contact_at']):
require(all(device[k] == baseline[k] for k in ('agent_id', 'asset_id', 'enrollment_generation', 'assignment_version', 'certificate_sha256')), 'same original mTLS identity')
if first is None: first = evidence
elif device['last_contact_at'] != first['device']['last_contact_at']: break
require(time.monotonic() < deadline, 'two native post-upgrade heartbeats missing')
time.sleep(2)
final = remote(access, intent, 'finish'); native = final['native']
original = json.loads(base64.b64decode(intent['payload']['baseline_base64']), object_pairs_hook=cb.contract.strict_object)
require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > original['journal']['sequence'], 'fresh telemetry sequence and concrete inventory ACK')
device, denied = access.device_and_denials()
require(cb.contract.timestamp(device['observed_at']) >= after, 'fresh original stored inventory')
require(access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both target counts/policies/hooks unchanged')
indices, _, _ = prior(access)
require(indices == intent['original_indices'], 'Main current indices still original; Root owns later CAS publication')
pipe = u.actual_pipe_proof(native, intent)
result = dict(verified=True, completed=True, id=ident, original=final['original'], frozen=final['frozen'], native=native, online=dict(watermark=watermark, first=first, second=evidence), stored_inventory=device, foreign_denied=denied, native_pipe_peer_test=pipe, pipe_framing_version=2, no_jobs=True, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True, helper_effects_enabled=False, no_reboot=True, no_clock_change=True, private_key_read=False, original_indices=intent['original_indices'], main_indices_published=False, manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['payload']['qualification_sha256'], runner_sha256=intent['runner_sha256'], script_sha256=intent['script_sha256'])
save(result_path, result)
print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=pipe, main_indices_published=False)))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('prepare', 'enter', 'finish', 'readback', 'guards'))
parser.add_argument('--access-root', type=Path); parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id'); parser.add_argument('--baseline-sha256')
args = parser.parse_args(); guards()
if args.phase == 'guards':
require(not any((args.access_root, args.manifest, args.qualification, args.id, args.baseline_sha256)), 'local source guards only'); print('PASS: local source guards; no VM action'); return
require(args.access_root, 'explicit separate read-only Main access root')
access = Access(args.access_root)
if args.phase == 'prepare':
require(args.manifest and args.qualification and not (args.id or args.baseline_sha256), 'qualified new pair and read-only baseline preparation')
prepare(access, args.manifest, args.qualification)
elif args.phase == 'enter':
require(args.id and args.baseline_sha256 and not (args.manifest or args.qualification), 'same prepared case and reviewed baseline hash')
enter(access, args.id, args.baseline_sha256)
else:
require(args.id and not (args.manifest or args.qualification or args.baseline_sha256), 'same original case readback/finish')
finish(access, args.id, args.phase == 'readback')
if __name__ == '__main__':
try: main()
except Exception as error:
print('WINDOWS_PIPE_UPGRADE_INCOMPLETE:' + type(error).__name__)
raise SystemExit(2) from None