Files
rust-discovery/deploy/windows_system_scope_server.py
T
2026-11-16 14:24:44 +01:00

153 lines
12 KiB
Python

#!/usr/bin/env python3
"""Reviewed remote bootstrap source for an explicit 15-minute SYSTEM ceiling.
No CLI dispatch. Root must review the exact public intent and call this through
the existing protected server transport. Never creates/approves jobs. Partial
results are readback-only, never an automatic retry or rollback.
"""
def activate(payload):
import datetime as dt
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import uuid
def require(value, code):
if not value:
raise RuntimeError(code)
require(os.geteuid() == 0, 'SYSTEM_SCOPE_ROOT_BOOTSTRAP')
require(set(payload) == {'operation', 'case_id', 'expected_roles', 'memberships', 'policy'}, 'SYSTEM_SCOPE_INPUT')
require(payload['operation'] == 'windows_system_script_scope_activate_v1', 'SYSTEM_SCOPE_OPERATION')
ident = str(uuid.UUID(payload['case_id']))
require(ident == payload['case_id'], 'SYSTEM_SCOPE_CASE')
tenant = '11111111-1111-4111-8111-111111111111'
agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3'
asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0'
actors = ['automation:' + tenant, 'simulated-testprincipal-a']
root = Path('/opt/rust-discovery')
base = ['docker', 'compose', '--env-file', str(root / 'devstate/.env')]
def run(args, data=None):
return subprocess.run(args, input=data, capture_output=True, check=True, timeout=120).stdout
def enc(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def create(path, data, uid=0, gid=0):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as out:
os.fchown(out.fileno(), uid, gid)
out.write(data); out.flush(); os.fsync(out.fileno())
roles = payload['expected_roles']
require(set(roles) == {'api', 'gateway'}, 'SYSTEM_SCOPE_BOTH_ROLES')
compose_files = None
config_hashes = None
for role in ('api', 'gateway'):
expected = roles[role]
require(set(expected) == {'container_id', 'image', 'environment', 'compose_files_sha256'}, 'SYSTEM_SCOPE_ROLE_WITNESS')
require(re.fullmatch('[a-f0-9]{64}', expected['container_id']) and re.fullmatch('sha256:[a-f0-9]{64}', expected['image']), 'SYSTEM_SCOPE_CONTAINER_ID')
info = json.loads(run(['docker', 'inspect', expected['container_id']]))[0]
require(info['State']['Running'] and info['Image'] == expected['image'], 'SYSTEM_SCOPE_IMAGE_CAS')
selected = {}
names = {'RMM_PROFILE', 'RMM_DEV_AUTH', 'RMM_SERVER_ROLE', 'RMM_UI_ORIGIN', 'RMM_DEV_SYSTEM_ENABLED', 'RMM_DEV_SYSTEM_POLICY_FILE'}
for entry in info['Config']['Env']:
key, _, value = entry.partition('=')
if key in names:
require(key not in selected, 'SYSTEM_SCOPE_UNIQUE_ENV')
selected[key] = value
require(selected == expected['environment'] and selected == dict(RMM_PROFILE='development', RMM_DEV_AUTH='true', RMM_SERVER_ROLE=role, RMM_UI_ORIGIN='https://localhost:18443'), 'SYSTEM_SCOPE_EXISTING_PRIVATE_DEV_PROFILE')
labels = info['Config']['Labels']
require(labels['com.docker.compose.project'] == 'rust-discovery-server' and labels['com.docker.compose.service'] == role, 'SYSTEM_SCOPE_COMPOSE_ROLE')
files = labels['com.docker.compose.project.config_files'].split(',')
require(files and len(files) <= 12 and all(Path(p).is_absolute() and Path(p).is_relative_to(root) for p in files), 'SYSTEM_SCOPE_COMPOSE_PATHS')
hashes = {}
for value in files:
path = Path(value); m = path.lstat()
require(stat.S_ISREG(m.st_mode) and m.st_uid == 0 and not m.st_mode & 0o022, 'SYSTEM_SCOPE_PROTECTED_COMPOSE')
hashes[value] = hashlib.sha256(path.read_bytes()).hexdigest()
require(hashes == expected['compose_files_sha256'], 'SYSTEM_SCOPE_COMPOSE_CAS')
if compose_files is None:
compose_files = files; config_hashes = hashes
require(files == compose_files and hashes == config_hashes, 'SYSTEM_SCOPE_SAME_COMPOSE_PAIR')
# Bind mounts are deliberately additive; no existing policy/TLS/data
# mount or published port is changed by the generated overlay.
require(not any(m['Destination'] == '/system-policy' for m in info['Mounts']), 'SYSTEM_SCOPE_PREVIOUS_SYSTEM_MOUNT')
compose = base[:]
for path in compose_files:
compose += ['-f', path]
for role in ('api', 'gateway'):
require(run(compose + ['ps', '-q', role]).decode().strip() == roles[role]['container_id'], 'SYSTEM_SCOPE_CURRENT_CONTAINER_CAS')
policy = payload['policy']
require(set(policy) == {'schema_version', 'profile', 'expires_at', 'scopes'} and policy['schema_version'] == 3 and policy['profile'] == 'development' and len(policy['scopes']) == 1, 'SYSTEM_SCOPE_NARROW_POLICY')
now = dt.datetime.now(dt.timezone.utc)
expiry = dt.datetime.fromisoformat(policy['expires_at'].replace('Z', '+00:00'))
require(dt.timedelta(minutes=5) <= expiry - now <= dt.timedelta(minutes=15), 'SYSTEM_SCOPE_FINITE_WINDOW')
scope = policy['scopes'][0]
require(set(scope) == {'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'principals', 'helper_policy_sha256', 'helper_binary_sha256', 'acceptance_evidence_id', 'allowed_services', 'max_runtime_seconds', 'allowed_script_profiles'}, 'SYSTEM_SCOPE_FIELDS')
require(scope['tenant_id'] == tenant and scope['asset_id'] == asset and scope['agent_id'] == agent and scope['enrollment_generation'] == scope['assignment_version'] == 1 and scope['principals'] == actors and scope['allowed_services'] == [] and scope['max_runtime_seconds'] == 30 and scope['allowed_script_profiles'] == ['full_maintenance_v1'], 'SYSTEM_SCOPE_ONLY_FULL_SCRIPT')
require(all(re.fullmatch('[a-f0-9]{64}', scope[k]) for k in ('helper_policy_sha256', 'helper_binary_sha256')) and str(uuid.UUID(scope['acceptance_evidence_id'])) == scope['acceptance_evidence_id'], 'SYSTEM_SCOPE_NATIVE_PINS')
memberships = payload['memberships']
require([row['principal'] for row in memberships] == actors, 'SYSTEM_SCOPE_EXISTING_ACTORS')
for n, row in enumerate(memberships):
require(set(row) == {'tenant_id', 'principal', 'kind', 'permissions', 'revoked_at'} and row['tenant_id'] == tenant and row['kind'] == ('automation' if n == 0 else 'test_human') and row['revoked_at'] is None and 'scripts:execute' in row['permissions'] and 'system:execute' not in row['permissions'], 'SYSTEM_SCOPE_MEMBERSHIP_CAS_INPUT')
require(len(set(row['permissions'])) == len(row['permissions']) and all(re.fullmatch('[a-z_:]+', p) for p in row['permissions']), 'SYSTEM_SCOPE_PERMISSION_FORMAT')
sql_read = ("BEGIN READ ONLY; SELECT json_build_object('ready',sync_ready,'helper_ready',helper_sync_ready,'blocked',restore_blocked,'fresh',last_contact_at>clock_timestamp()-interval '45 seconds','same_certificate',certificate_sha256=last_authenticated_certificate_sha256,'capabilities',capabilities) FROM agent_installations WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND asset_id='" + asset + "' AND enrollment_generation=1 AND assignment_version=1 AND revoked_at IS NULL; COMMIT;")
observed = json.loads(run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql_read.encode()))
require(observed['ready'] and observed['helper_ready'] and not observed['blocked'] and observed['fresh'] and observed['same_certificate'], 'SYSTEM_SCOPE_CURRENT_AUTHENTICATED_PAIR')
needed = {'windows.base/1', 'rmm.sync.v1', 'helper.system.v1', 'system:run_script', 'script.full_maintenance/1', 'helper.binary.sha256:' + scope['helper_binary_sha256'], 'helper.policy.sha256:' + scope['helper_policy_sha256']}
require(needed <= set(observed['capabilities']) and 'linux.base/1' not in observed['capabilities'], 'SYSTEM_SCOPE_ACTUAL_QUALIFIED_CAPABILITIES')
# Resolve only public image names; never build, pull or alter a deployed image.
configured = json.loads(run(compose + ['config', '--format', 'json']))['services']
for role in ('api', 'gateway'):
actual = run(['docker', 'image', 'inspect', configured[role]['image'], '--format', '{{.Id}}']).decode().strip()
require(actual == roles[role]['image'], 'SYSTEM_SCOPE_NO_IMAGE_CHANGE')
lock = os.open(root / 'devstate/.windows-system-scope.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
try:
parent = root / 'devstate/windows-system-policy'
if not parent.exists(): parent.mkdir(mode=0o700)
m = parent.lstat(); require(stat.S_ISDIR(m.st_mode) and m.st_uid == 0 and m.st_mode & 0o777 == 0o700, 'SYSTEM_SCOPE_PRIVATE_PARENT')
case = parent / ident
case.mkdir(mode=0o700) # create-once: lost response means readback only
create(case / 'intent.json', enc(payload))
key = (root / 'devstate/jobs/ed25519.pem').lstat() # metadata only, never read signing key
require(stat.S_ISREG(key.st_mode) and not key.st_mode & 0o077, 'SYSTEM_SCOPE_JOB_KEY_OWNER')
mounted = case / 'mounted'; mounted.mkdir(mode=0o700); os.chown(mounted, key.st_uid, key.st_gid)
raw = enc(policy); require(len(raw) <= 65536, 'SYSTEM_SCOPE_POLICY_LIMIT')
create(mounted / 'policy.json', raw, key.st_uid, key.st_gid)
overlay = {'services': {role: {'environment': {'RMM_DEV_SYSTEM_ENABLED': 'true', 'RMM_DEV_SYSTEM_POLICY_FILE': '/system-policy/policy.json'}, 'volumes': [str(mounted) + ':/system-policy:ro']} for role in ('api', 'gateway')}}
overlay_path = case / 'system-policy.compose.json'; create(overlay_path, enc(overlay))
sql = "BEGIN; LOCK TABLE memberships,jobs,outbox,execution_permits,authorizations IN SHARE ROW EXCLUSIVE MODE; DO $scope$ BEGIN IF EXISTS(SELECT 1 FROM jobs WHERE tenant_id='" + tenant + "' AND state NOT IN ('succeeded','failed','cancelled','expired')) THEN RAISE EXCEPTION 'SYSTEM_SCOPE_INFLIGHT_JOB'; END IF;"
for row in memberships:
permissions = 'ARRAY[' + ','.join("'" + p + "'" for p in row['permissions']) + ']::text[]'
where = "tenant_id='" + tenant + "' AND principal='" + row['principal'] + "' AND kind='" + row['kind'] + "' AND revoked_at IS NULL AND permissions=" + permissions
sql += " IF (SELECT count(*) FROM memberships WHERE " + where + ")<>1 THEN RAISE EXCEPTION 'SYSTEM_SCOPE_MEMBERSHIP_CAS'; END IF; UPDATE memberships SET permissions=permissions||ARRAY['system:execute'] WHERE " + where + ';'
sql += " END $scope$; SELECT json_build_object('memberships_updated',2,'jobs_created',0,'approvals_created',0); COMMIT;"
create(case / 'permissions-entered.json', b'{"retry_allowed":false}')
reply = run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql.encode())
create(case / 'permissions-result.json', reply)
create(case / 'recreate-entered.json', b'{"retry_allowed":false}')
run(compose + ['-f', str(overlay_path), 'up', '-d', '--no-deps', '--no-build', '--pull', 'never', 'api', 'gateway'])
after = {}
for role in ('api', 'gateway'):
cid = run(compose + ['-f', str(overlay_path), 'ps', '-q', role]).decode().strip()
info = json.loads(run(['docker', 'inspect', cid]))[0]
require(info['Image'] == roles[role]['image'] and info['State']['Running'], 'SYSTEM_SCOPE_ROLE_RUNNING')
mount = [m for m in info['Mounts'] if m['Destination'] == '/system-policy']
require(len(mount) == 1 and mount[0]['Type'] == 'bind' and not mount[0]['RW'] and mount[0]['Source'] == str(mounted), 'SYSTEM_SCOPE_READ_ONLY_MOUNT')
after[role] = dict(container_id=cid, image=info['Image'])
result = dict(schema_version=1, activated=True, case_id=ident, expires_at=policy['expires_at'], policy_sha256=hashlib.sha256(raw).hexdigest(), roles=after, jobs_created=False, approvals_created=False, system_target_job_executed=False, automatic_retry=False)
create(case / 'activated.json', enc(result))
return result
finally:
os.close(lock)