Recover a Windows maintenance setup interrupted before policy activation
This commit is contained in:
@@ -74,6 +74,9 @@ def read_registry(data):
|
||||
AND certificate_sha256=last_authenticated_certificate_sha256 AND last_contact_at > now() - interval '2 minutes',
|
||||
'enrollment_generation',enrollment_generation,'assignment_version',assignment_version,'capabilities',capabilities)
|
||||
FROM agent_installations WHERE tenant_id='{tenant}' AND asset_id='{asset}' AND agent_id='{agent}' AND revoked_at IS NULL),
|
||||
'sync_head',(SELECT json_build_object('journal_id',s.journal_id,'checkpoint',s.checkpoint,'decision_id',s.decision_id,
|
||||
'helper_id',s.helper_journal_id,'helper_checkpoint',s.helper_checkpoint) FROM agent_sync_state s
|
||||
WHERE tenant_id='{tenant}' AND agent_id='{agent}'),
|
||||
'open_jobs',(SELECT count(*) FROM jobs WHERE tenant_id='{tenant}' AND agent_id='{agent}'
|
||||
AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')),
|
||||
'principal_authorized',EXISTS (SELECT 1 FROM memberships WHERE tenant_id='{tenant}' AND principal='simulated-testprincipal-a'
|
||||
@@ -156,31 +159,49 @@ def server(action, data):
|
||||
if not (history/'closed').exists():
|
||||
atomic(history/'closed',b'closed\n')
|
||||
return {'central_scope_closed':True}
|
||||
require(action=='enable', 'Unsupported central operation')
|
||||
for key in ('helper_binary_sha256','helper_policy_sha256'):
|
||||
require(re.fullmatch('[a-f0-9]{64}',data[key]),'Invalid helper hash')
|
||||
require(scoped(data, read_registry(data)), 'Device has no current authenticated narrow helper capabilities')
|
||||
require(action in ('prepare','enable'), 'Unsupported central operation')
|
||||
ids={k:identifier(data[k]) for k in ('case_id','tenant_id','asset_id','agent_id','release_id')}
|
||||
hashes={k:data[k] for k in ('agent_sha256','helper_binary_sha256')}
|
||||
require(all(re.fullmatch('[a-f0-9]{64}',v) for v in hashes.values()), 'Invalid signed image pair')
|
||||
expires=stamp(data['expires_at'])
|
||||
require(utc()<expires<=utc()+timedelta(minutes=120), 'Window expired or exceeds 120 minutes')
|
||||
if history.exists():
|
||||
require(not (history/'closed').exists() and (history/'original.json').is_file()
|
||||
and (history/'window.json').is_file(), 'Case is closed or incomplete')
|
||||
expected=(history/'window.json').read_bytes()
|
||||
require(current in (expected,(history/'original.json').read_bytes()), 'Central policy changed while opening')
|
||||
require(json.loads(expected)['expires_at']==data['expires_at'], 'Cannot extend an existing window')
|
||||
else:
|
||||
original,prepared,candidate=history/'original.json',history/'prepared.json',history/'window.json'
|
||||
require(not (history/'closed').exists(),'Case is already closed')
|
||||
observation=read_registry(data)
|
||||
if action=='prepare':
|
||||
require(usable(observation),'An idle, synchronized and authenticated enrollment is required')
|
||||
head=observation['sync_head']
|
||||
require(head and head['helper_id'] is None and head['helper_checkpoint']==0,'Existing helper journal must close first')
|
||||
old=json.loads(current)
|
||||
require(old['profile']=='development' and (stamp(old['expires_at'])<=utc() or not old['scopes']),
|
||||
'Another live maintenance window is active')
|
||||
scope={k:identifier(data[k]) for k in ('tenant_id','asset_id','agent_id')}
|
||||
scope.update(enrollment_generation=1,assignment_version=1,principals=['simulated-testprincipal-a'],
|
||||
acceptance_evidence_id=case,allowed_services=[],max_runtime_seconds=30,
|
||||
windows_update_max_runtime_seconds=3600,
|
||||
**{k:data[k] for k in ('helper_binary_sha256','helper_policy_sha256')})
|
||||
expected=encode(dict(schema_version=3,profile='development',expires_at=data['expires_at'],scopes=[scope]))
|
||||
history.mkdir(mode=0o700)
|
||||
atomic(history/'original.json',current)
|
||||
atomic(history/'window.json',expected)
|
||||
entry={'schema_version':1,**ids,**hashes,**{k:head[k] for k in ('journal_id','checkpoint','decision_id')}}
|
||||
history.mkdir(mode=0o700,exist_ok=True)
|
||||
require(not candidate.exists() and (not original.exists() or original.read_bytes()==current),
|
||||
'Another policy or opening changed this case')
|
||||
if prepared.exists():
|
||||
prior=json.loads(prepared.read_bytes())
|
||||
require(all(prior[k]==entry[k] for k in (*ids,*hashes,'journal_id')), 'Different prepared enrollment')
|
||||
else:
|
||||
atomic(original,current)
|
||||
atomic(prepared,encode(entry))
|
||||
return {'prepared':True,'case_id':case,'journal_id':head['journal_id']}
|
||||
saved=original.read_bytes()
|
||||
prior=json.loads(prepared.read_bytes())
|
||||
require(all(prior[k]==v for k,v in (ids|hashes).items()),'Installed pair differs from the prepared case')
|
||||
require(re.fullmatch('[a-f0-9]{64}',data['helper_policy_sha256']),'Invalid helper policy hash')
|
||||
require(scoped(data,observation),'Device has no current authenticated narrow helper capabilities')
|
||||
scope={k:ids[k] for k in ('tenant_id','asset_id','agent_id')}
|
||||
scope.update(enrollment_generation=1,assignment_version=1,principals=['simulated-testprincipal-a'],
|
||||
acceptance_evidence_id=case,allowed_services=[],max_runtime_seconds=30,
|
||||
windows_update_max_runtime_seconds=3600,helper_binary_sha256=hashes['helper_binary_sha256'],
|
||||
helper_policy_sha256=data['helper_policy_sha256'])
|
||||
expected=encode(dict(schema_version=3,profile='development',expires_at=data['expires_at'],scopes=[scope]))
|
||||
if candidate.exists():
|
||||
require(candidate.read_bytes()==expected and current in (expected,saved),'Changed window or central policy')
|
||||
else:
|
||||
require(current==saved,'Central policy changed after preparation')
|
||||
atomic(candidate,expected)
|
||||
atomic(path,expected,(st.st_uid,st.st_gid))
|
||||
return {'central_scope_open':True,'expires_at':data['expires_at']}
|
||||
|
||||
@@ -255,9 +276,11 @@ def local():
|
||||
emit(plan);return
|
||||
state_dir.mkdir(parents=True,mode=0o700,exist_ok=True)
|
||||
casefile=state_dir/(data['case_id']+'.json')
|
||||
with casefile.open('xb') as dst:
|
||||
data.update(agent_sha256=plan['agent_sha256'],helper_binary_sha256=plan['helper_sha256'])
|
||||
with os.fdopen(os.open(casefile,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600),'wb') as dst:
|
||||
dst.write(encode(data));dst.flush();os.fsync(dst.fileno())
|
||||
emit({'preparing_window':data['case_id'],'expires_at':data['expires_at']})
|
||||
emit(remote_server('prepare',data))
|
||||
try:
|
||||
result=guest('Install',data)
|
||||
require(result['case_id']==data['case_id'] and result['agent_id']==data['agent_id']
|
||||
@@ -299,16 +322,19 @@ def close(data):
|
||||
wait_for(data,lambda row:row['install'] and row['open_jobs']==0,180,
|
||||
'Attempt still active. Central scope is revoked; retry close when the result is terminal.')
|
||||
observed=windows('Inspect-DevelopmentWindowsUpdate.ps1',{})
|
||||
if observed.get('case_id') is not None or observed.get('helper') is not None:
|
||||
absent=observed.get('case_id') is None and observed.get('helper') is None
|
||||
if not absent:
|
||||
require(observed.get('case_id')==data['case_id'],'Local helper belongs to another maintenance window')
|
||||
if observed.get('release_id')==data['release_id']:
|
||||
result=guest('Remove',data)
|
||||
require(result['closed'] and not result['helper_registered'] and result['actor_running'],
|
||||
'Could not withdraw the helper from this enrollment')
|
||||
emit(result)
|
||||
witness=detach_server('witness',data)
|
||||
witness=detach_server('witness',{**data,'native_window_absent':absent})
|
||||
if witness and witness.get('helper_id'):
|
||||
emit(retire_native('Verify',data,witness))
|
||||
emit(detach_server('detach',{**data,'witness':witness}))
|
||||
verified=retire_native('Verify',data,witness)
|
||||
emit(verified)
|
||||
emit(detach_server('detach',{**data,'witness':witness,'native_verification':verified}))
|
||||
emit(retire_native('Apply',data,witness))
|
||||
latest=windows('Inspect-DevelopmentWindowsUpdate.ps1',{})
|
||||
if latest['release_id']==data['release_id']:
|
||||
|
||||
Reference in New Issue
Block a user