72 lines
4.3 KiB
Python
72 lines
4.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Bounded root log acceptance for the one harmless cloud test unit."""
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import uuid
|
|
|
|
import cloud_apt_retry as apt
|
|
import cloud_root_policy
|
|
|
|
cloud=apt.cloud
|
|
|
|
|
|
def open_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,'safe existing policy')
|
|
old=p.read_bytes()
|
|
require(hashlib.sha256(old).hexdigest()==payload['previous_sha256'] and
|
|
dt.datetime.fromisoformat(json.loads(old)['expires_at'])<dt.datetime.now(dt.timezone.utc),'known closed policy')
|
|
policy=payload['policy'];scope=policy['scopes'][0]
|
|
require(policy['schema_version']==1 and policy['profile']=='development' and len(policy['scopes'])==1 and
|
|
dt.datetime.now(dt.timezone.utc)<dt.datetime.fromisoformat(policy['expires_at'])<=dt.datetime.now(dt.timezone.utc)+dt.timedelta(minutes=16) and
|
|
not scope['allowed_services'] and not scope['allow_root_scripts'] and not scope['allow_reboot'] and 'apt' not in scope and
|
|
scope['principals']==['simulated-testprincipal-a'] and
|
|
scope['root_logs']==dict(schema_version=1,allowed_units=['rmm-mvp-test.service'],sensitive_units=[]),'one test-unit read policy only')
|
|
backup=p.parents[1]/('root-policy-bootstrap-'+str(uuid.UUID(payload['id'])));backup.mkdir(mode=0o700)
|
|
def create(path,data,uid=0):
|
|
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
|
|
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno());os.fchown(f.fileno(),uid,uid)
|
|
create(backup/'previous-policy.json',old)
|
|
next_path=p.with_suffix('.logs-next');create(next_path,json.dumps(policy).encode(),10001);os.replace(next_path,p)
|
|
return dict(policy_sha256=hashlib.sha256(p.read_bytes()).hexdigest(),backup=str(backup),approvals_created=False)
|
|
|
|
|
|
def main():
|
|
os.umask(0o077);m=cloud.contract
|
|
require=cloud.require
|
|
require(apt.prior.evidence('gate')['unresolved']==0,'no unresolved cloud attempts')
|
|
installed=m.protected_json(cloud.ROOT/'devstate/remote-vm.json');identity=installed['identity']
|
|
import cloud_root_evidence
|
|
peers=cloud.bootstrap.rpc('linux-vm.conf',cloud_root_evidence.inspect_helpers,dict(identity,tenant_id=cloud.TENANT,general_only=True))
|
|
require(peers['ledger']['faults']==0,'fault-free shared ledger')
|
|
binding=peers['general']['identity']
|
|
scope={k:binding[k] for k in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')}
|
|
scope.update(principals=['simulated-testprincipal-a'],helper_policy_sha256=peers['general']['policy_sha256'],
|
|
acceptance_evidence_id='cloud-general-readiness:bounded-testunit-logs',allowed_services=[],allow_root_scripts=False,allow_reboot=False,
|
|
root_logs=dict(schema_version=1,allowed_units=['rmm-mvp-test.service'],sensitive_units=[]))
|
|
policy=dict(schema_version=1,profile='development',expires_at=(m.now()+dt.timedelta(minutes=15)).isoformat(),scopes=[scope])
|
|
folder=cloud.ROOT/'devstate/cloud-logs';folder.mkdir(mode=0o700,exist_ok=True)
|
|
previous=m.protected_json(apt.STATE/'policy-closed.json')
|
|
record=cloud.bootstrap.rpc('server.conf',open_policy,dict(id=str(uuid.uuid4()),previous_sha256=previous['policy_sha256'],policy=policy))
|
|
m.write_private(folder/'policy-open.json',dict(record,policy=policy))
|
|
process=subprocess.run([sys.executable,str(cloud.ROOT/'deploy/cloud_root_acceptance.py'),'--case','query_logs'],capture_output=True,timeout=600)
|
|
# The child intentionally prints only public contract statuses.
|
|
print(process.stdout.decode(),end='')
|
|
closed=cloud.bootstrap.rpc('server.conf',cloud_root_policy.close_policy,dict(expected_sha256=record['policy_sha256'],backup=record['backup']))
|
|
m.write_private(folder/'policy-closed.json',closed)
|
|
require(process.returncode==0,'bounded log acceptance incomplete; preserve original case')
|
|
print('PASS cloud bounded log collection; test-only read policy closed')
|
|
|
|
|
|
if __name__=='__main__':
|
|
try:main()
|
|
except Exception as error:
|
|
message=str(error)
|
|
print(message if message.startswith('remote bootstrap incomplete: ') else 'CLOUD_LOG_ACCEPTANCE_INCOMPLETE:'+type(error).__name__)
|
|
raise SystemExit(2) from None
|