#!/usr/bin/env python3 """Install an expiring deny/limit policy. This never approves a job.""" import datetime as dt import argparse import hashlib import json import os import uuid import cloud_mvp_acceptance as cloud def install_policy(payload): root=Path('/opt/rust-discovery');compose=root/'deploy/server.compose.yaml';env=root/'devstate/.env' require(hashlib.sha256(compose.read_bytes()).hexdigest()==payload['previous_compose_sha256'],'compose drift') require(not compose.is_symlink() and not env.is_symlink(),'unsafe server config') directory=root/'devstate/root-policy';require(not directory.exists(),'existing root policy requires separate reviewed update') backup=root/'devstate'/('root-policy-bootstrap-'+payload['id']);backup.mkdir(mode=0o700) def create(path,data,mode=0o600,uid=0): fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode) with os.fdopen(fd,'wb') as f: f.write(data);f.flush();os.fsync(f.fileno());os.fchown(f.fileno(),uid,uid);os.fchmod(f.fileno(),mode) create(backup/'server.compose.yaml',compose.read_bytes());create(backup/'server.env',env.read_bytes()) directory.mkdir(mode=0o700);os.chown(directory,10001,10001) create(directory/'policy.json',json.dumps(payload['policy']).encode(),uid=10001) text=env.read_text();require(not any(line.startswith('RMM_DEV_ROOT_') for line in text.splitlines()),'existing root environment') create(env.with_suffix('.root-next'),(text.rstrip()+'\nRMM_DEV_ROOT_ENABLED=true\n').encode()) create(compose.with_suffix('.root-next'),payload['compose'].encode(),0o644) os.replace(env.with_suffix('.root-next'),env);os.replace(compose.with_suffix('.root-next'),compose) cmd=['docker','compose','--env-file',str(env),'-f',str(compose)] subprocess.run(cmd+['config','-q'],capture_output=True,check=True,timeout=30) result=subprocess.run(cmd+['up','-d','--no-deps','api','gateway'],capture_output=True,timeout=60) return dict(deployed=result.returncode==0,expires_at=payload['policy']['expires_at'],policy_sha256=hashlib.sha256((directory/'policy.json').read_bytes()).hexdigest(), approvals_created=False,backup=str(backup)) def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--close-reviewed-test-scope',action='store_true');args=parser.parse_args() if args.close_reviewed_test_scope: records=list((cloud.ROOT/'devstate/cloud-root').glob('policy-*.json')) cloud.require(len(records)==1,'one known policy deployment required') previous=cloud.contract.protected_json(records[0]);identity=previous['policy']['scopes'][0] gate=cloud.bootstrap.rpc('server.conf',cloud.server,dict(kind='gate',tenant_id=identity['tenant_id'],agent_id=identity['agent_id'])) cloud.require(gate['unresolved']==0,'unresolved central job; preserve policy and reconcile') result=cloud.bootstrap.rpc('server.conf',close_policy,dict(expected_sha256=previous['policy_sha256'],backup=previous['backup'])) cloud.contract.write_private(cloud.ROOT/'devstate/cloud-root'/('policy-closed-'+uuid.uuid4().hex+'.json'),result) print(dict(test_scope_closed=result['closed'],expires_at=result['expires_at']));return os.umask(0o077) reports=[cloud.contract.protected_json(p) for p in (cloud.ROOT/'devstate/cloud-root').glob('health-*.json')] ready=next(r for r in reports if r['completed'] is True and r['readiness_present'] is True) cloud.require(ready['consumed']==0 and ready['ledger_faults']==0,'unused healthy root runtime required') identity=ready['pins']['general']['identity'];settings={k:identity[k] for k in ('tenant_id','agent_id','asset_id')} gate=cloud.bootstrap.rpc('server.conf',cloud.server,dict(kind='gate',**{k:settings[k] for k in ('tenant_id','agent_id')})) cloud.require(gate['unresolved']==0,'central unresolved job') device=cloud.Backend().call('inventory.get_device',{k:settings[k] for k in ('tenant_id','asset_id')}) scopes=[] for name,pin in ready['pins'].items(): policy_hash=pin['policy_sha256' if name=='general' else 'provider_stack_sha256'] cloud.require('helper.policy.sha256:'+policy_hash in device['capabilities'],'measured helper capability missing') scope={k:identity[k] for k in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')} scope.update(principals=['simulated-testprincipal-a'],helper_policy_sha256=policy_hash, acceptance_evidence_id='cloud-stable-readiness:'+ready['runtime_sha256'], allowed_services=['rmm-mvp-test.service'] if name=='general' else [], allow_root_scripts=name=='general',allow_reboot=False) if name=='apt': scope['apt']=dict(allow_native_acceptance=True,allow_execute=True,runtime_sha256=ready['runtime_sha256'], apt_config_sha256=ready['apt_config_sha256'], provider_sha256=ready['runtime']['binaries']['/usr/lib/rmm-apt-transaction/apt_transaction.py']['sha256'], hook_sha256=ready['runtime']['binaries']['/usr/lib/rmm-apt-transaction/hook']['sha256']) scopes.append(scope) policy=dict(schema_version=1,profile='development',expires_at=(dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=2)).isoformat(),scopes=scopes) previous=(cloud.ROOT/'devstate/cloud-root/compose-before-root.yaml').read_bytes() payload=dict(id=str(uuid.uuid4()),policy=policy,compose=(cloud.ROOT/'deploy/server.compose.yaml').read_text(), previous_compose_sha256=hashlib.sha256(previous).hexdigest()) result=cloud.bootstrap.rpc('server.conf',install_policy,payload) cloud.contract.write_private(cloud.ROOT/'devstate/cloud-root'/('policy-'+payload['id']+'.json'),dict(result,policy=policy)) print({k:result[k] for k in ('deployed','expires_at','approvals_created')}) cloud.require(result['deployed'],'deployment unconfirmed; inspect retained server config, never repeat bootstrap') def close_policy(payload): import datetime as dt p=Path('/opt/rust-discovery/devstate/root-policy/policy.json') require(not p.is_symlink() and p.stat().st_uid==10001 and p.stat().st_mode&0o777==0o600,'unsafe policy') raw=p.read_bytes();require(hashlib.sha256(raw).hexdigest()==payload['expected_sha256'],'policy drift') backup=Path(payload['backup']) require(backup.parent==Path('/opt/rust-discovery/devstate') and backup.name.startswith('root-policy-bootstrap-') and not backup.is_symlink() and backup.stat().st_mode&0o777==0o700,'known private backup required') retained=backup/'policy-before-close.json' fd=os.open(retained,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) with os.fdopen(fd,'wb') as f:f.write(raw);f.flush();os.fsync(f.fileno()) policy=json.loads(raw);policy['expires_at']=dt.datetime.now(dt.timezone.utc).isoformat() next_path=p.with_suffix('.closed-next') fd=os.open(next_path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) with os.fdopen(fd,'w') as f: json.dump(policy,f);f.flush();os.fsync(f.fileno());os.fchown(f.fileno(),10001,10001) os.replace(next_path,p) return dict(closed=True,expires_at=policy['expires_at'],policy_sha256=hashlib.sha256(p.read_bytes()).hexdigest(),approvals_created=False) require=cloud.require if __name__=='__main__': try:main() except Exception: print('CLOUD_ROOT_POLICY_INCOMPLETE; no automatic repeat');raise SystemExit(2) from None