Files
rust-discovery/deploy/cloud_mvp_final_readback.py
2026-11-13 22:31:19 +01:00

110 lines
7.5 KiB
Python

"""Fixed read-only final metadata; callers assert the actual returned state."""
def vm(payload):
import stat
retry = str(uuid.UUID(payload['startup_retry_id']))
def owned(path,owner,limit):
require(not path.is_symlink(), 'fixed metadata file symlink')
s = path.stat()
require(stat.S_ISREG(s.st_mode) and s.st_uid == owner and not s.st_mode&0o022
and s.st_size <= limit, 'owned bounded metadata file')
return path.read_bytes()
def service(name):
answer = subprocess.run(['systemctl','show',name,'-p','ActiveState','-p','SubState',
'-p','UnitFileState','-p','MainPID','-p','Restart','-p','RestartUSec','-p','NRestarts'],
capture_output=True,timeout=10)
return dict(properties=dict(line.split('=',1) for line in answer.stdout.decode().splitlines()),
show_exit_code=answer.returncode)
names = ('rmm-agent-remote.service','rmm-helper-cloud.service','rmm-apt-helper.service',
'rmm-agent.service','rmm-helper-dev-test.service')
units = {name:service(name) for name in names}
account = pwd.getpwnam('rmm-agent'); state = Path('/var/lib/rmm-agent-remote')
config_raw = owned(Path('/etc/rmm-remote/helper-general.json'),0,16384)
pin_raw = owned(Path('/etc/rmm-remote/general-helper-proof.json'),0,16384)
general = json.loads(config_raw); pin = json.loads(pin_raw)
cached = json.loads(owned(state/'job-signing-key.json',account.pw_uid,4096))
helper_key = json.loads(owned(Path('/etc/rmm-remote/helper-signing-key.json'),0,4096))
binding = json.loads(owned(state/'binding.json',account.pw_uid,16384))
try: raw_key = bytes.fromhex(cached.get('public_key_hex',''))
except (TypeError,ValueError): raw_key = b''
match = (set(cached) == {'algorithm','schema_version','public_key_hex','key_id'}
and cached == helper_key and cached.get('algorithm') == 'Ed25519'
and type(cached.get('schema_version')) is int and cached['schema_version'] == 1
and len(raw_key) == 32 and cached.get('key_id') == hashlib.sha256(raw_key).hexdigest()
and binding.get('public_key_hex') == cached.get('public_key_hex')
and general.get('signing_key_file') == '/etc/rmm-remote/helper-signing-key.json'
and general.get('binding',{}).get('public_key_hex') in ('',cached.get('public_key_hex'))
and pin.get('identity',{}).get('signing_key_id') == cached.get('key_id')
and all(binding.get(k) == general.get('binding',{}).get(k) == pin.get('identity',{}).get(k)
and binding.get(k) is not None for k in
('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')))
pid = int(units['rmm-agent-remote.service']['properties'].get('MainPID','0'))
process = dict(pid=pid,uids=None,gids=None)
if pid > 0:
try:
lines = Path('/proc/'+str(pid)+'/status').read_text().splitlines()
for label,key in (('Uid:','uids'),('Gid:','gids')):
selected = [line for line in lines if line.startswith(label)]
process[key] = [int(v) for v in selected[0].split()[1:]] if len(selected) == 1 else None
except FileNotFoundError: process['exited_during_read'] = True
probe = Path('/etc/systemd/system/rmm-helper-cloud.service.d/96-cloud-startup-retry-probe.conf')
endpoint = owned(Path('/etc/systemd/system/rmm-agent-remote.service.d/30-cloud-root.conf'),0,4096)
files = {'agent':Path('/usr/local/libexec/rmm-agent-remote'),
'helper':Path('/usr/local/libexec/rmm-privileged-helper'),
'provider':Path('/usr/lib/rmm-apt-transaction/apt_transaction.py')}
return dict(units=units,agent_process=process,
general_unit_sha256=hashlib.sha256(owned(Path('/etc/systemd/system/rmm-helper-cloud.service'),0,16384)).hexdigest(),
general_allow_reboot=general.get('allow_reboot'),
general_config_sha256=hashlib.sha256(config_raw).hexdigest(),
general_pin_sha256=hashlib.sha256(pin_raw).hexdigest(),public_key_cache_match=match,
startup_probe_override_exists=probe.exists() or probe.is_symlink(),
rollback_timer=service('rmm-general-startup-rollback-'+retry+'.timer'),
artifact_sha256={name:hashlib.sha256(owned(path,0,32*1024*1024)).hexdigest() for name,path in files.items()},
apt_endpoint_present=b'RMM_APT_HELPER_' in endpoint)
def server(payload):
import stat
candidate = str(uuid.UUID(payload['candidate_id']))
root = Path('/opt/rust-discovery'); folder = root/'devstate'/('source-upgrade-'+candidate)
def metadata(path):
require(not path.is_symlink(), 'candidate metadata symlink')
s = path.stat()
require(stat.S_ISREG(s.st_mode) and s.st_uid == 0 and s.st_size <= 1024*1024
and not s.st_mode&0o077, 'private bounded candidate metadata')
return json.loads(path.read_bytes())
record = metadata(folder/'source.json'); built = metadata(folder/'build-result.json')
require(record['id'] == candidate and record['image_tag'] == 'rust-discovery-server:upgrade-'+candidate,
'fixed qualified candidate image tag')
def run(args):return subprocess.run(args,capture_output=True,check=True,timeout=10).stdout
def image(tag):return run(['docker','image','inspect',tag,'--format','{{.Id}}']).decode().strip()
compose = ['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml')]
# Select fields inside Docker's formatter: no whole inspect/Config.Env and
# no State.Health log output is ever read into the result.
state_fields = ('Status','Running','Paused','Restarting','OOMKilled','Dead','Pid','ExitCode','StartedAt','FinishedAt')
state = '{'+','.join('"'+key+'":{{json .State.'+key+'}}' for key in state_fields)+'}'
template = ('{"State":'+state+',"Image":{{json .Image}},"User":{{json .Config.User}},'
'"PortBindings":{{json .HostConfig.PortBindings}},'
'"HealthStatus":{{if .State.Health}}{{json .State.Health.Status}}{{else}}null{{end}}}')
flags = ('RMM_PROFILE','RMM_DEV_AUTH','RMM_DEV_DELIVERY_FAULTS','RMM_DEV_TRANSPORT_FAULTS',
'RMM_DEV_DELIVERY_FAULT_FILE','RMM_DEV_TRANSPORT_FAULT_FILE')
roles = {}
for role in ('api','gateway','postgres'):
ids = run(compose+['ps','--all','-q',role]).decode().split()
require(len(ids) <= 1 and all(len(value) == 64 and all(c in '0123456789abcdef' for c in value) for value in ids), 'one bounded exact role container')
if not ids: roles[role] = dict(container_id=None); continue
cid = ids[0]; value = json.loads(run(['docker','inspect','--format',template,cid]))
value['container_id'] = cid
if role in ('api','gateway'):
selected = {}
for key in flags:
answer = subprocess.run(['docker','exec',cid,'printenv',key],capture_output=True,timeout=10)
require(answer.returncode in (0,1) and len(answer.stdout) <= 1024, 'explicit bounded nonsecret flag read')
selected[key] = answer.stdout.decode().strip() if answer.returncode == 0 else None
value['flags'] = selected
roles[role] = value
return dict(candidate_id=candidate,candidate_build_exit_code=built['exit_code'],
candidate_built_image_id=built.get('image_id'),candidate_tag_image_id=image(record['image_tag']),
runtime_tag_image_id=image('rust-discovery-server:local'),roles=roles)