Files
rust-discovery/deploy/script_console_policy_scope.py
T
2026-11-14 18:48:48 +01:00

553 lines
42 KiB
Python

#!/usr/bin/env python3
"""One short, exact development Root-policy scope; never a job/approval tool.
prepare-local reads a Root-accepted native attestation, no target. open/read/close
use only the existing server SSH transport. A SEPARATE explicit provision case
can add only root:execute to one existing development automation actor. Scope
open never provisions. No VM, token/session, service or approval operation.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import stat
import uuid
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / 'devstate/script-console-policy-scope'
TENANT = '11111111-1111-4111-8111-111111111111'
SIMULATED = 'simulated-testprincipal-a'
OLD_POLICY_SHA = 'cf15cbb68b590475df6def28e7dcffb7d88e0ca2d2555a06174fb654eeff05f4'
INSTALL_CASE = '2e27c312-58cc-444d-92a6-863a11ac6ffd'
AUTOMATION_RIGHTS = ['inventory:read', 'logs:read', 'operations:read', 'operations:plan',
'operations:submit', 'jobs:cancel', 'scripts:execute']
SUPPORT = {
'deploy/remote_client_bootstrap.py': '785c43a51dfe3f93e39798dbd7611c353752ae2fc64b22e41ba168e221620d30',
'deploy/vm_access_check.py': '5c8107ea9151a9f498b2530cdc61c1a7a6d745aff853a9b05710f3395838c0dd',
}
def require(value, code):
if not value:
raise RuntimeError(code)
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def encode(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def digest(value):
return isinstance(value, str) and re.fullmatch('[a-f0-9]{64}', value) is not None
def protected(path, limit=8 * 1024 * 1024):
value = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(value.st_mode) and value.st_uid == os.getuid()
and stat.S_IMODE(value.st_mode) == 0o600 and value.st_nlink == 1 and value.st_size <= limit,
'private owned local evidence')
return path.read_bytes()
def private_directory(path):
value = path.lstat()
require(not path.is_symlink() and stat.S_ISDIR(value.st_mode) and value.st_uid == os.getuid()
and stat.S_IMODE(value.st_mode) == 0o700, 'private owned local case directory')
def create(path, raw):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as out:
out.write(raw); out.flush(); os.fsync(out.fileno())
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def accepted_native(path, expected):
"""Accepted digest is an explicit Root-reviewed evidence input, not a grant."""
raw = protected(path)
require(digest(expected) and sha(raw) == expected, 'explicit accepted attestation bytes')
attested = json.loads(raw)
require(attested['case_id'] == INSTALL_CASE and attested['verified_preservation'] is True
and attested['verified_normal_signed_sync'] is True and attested['stored_heartbeat_advances'] == 2
and attested['specific_inventory_queue_convergence'] is True and attested['tenant_rls_denial'] is True
and attested['read_only'] is True and attested['rmm_jobs'] is False and attested['approvals'] is False
and attested['full_job_accepted'] is False and len(attested['sample_sha256']) == 3,
'accepted three-sample preservation and normal Sync qualification')
intent = json.loads(protected(path.parent / 'intent.json'))
require(intent['type'] == 'rmm.script-console.read-only-post-attestation-v1'
and intent['case_id'] == INSTALL_CASE and intent['runner_sha256'] == attested['runner_sha256'],
'same attested observation and installation provenance')
samples = []
for number, expected_sample in enumerate(attested['sample_sha256']):
sample_raw = protected(path.parent / ('sample-' + str(number) + '.json'))
require(digest(expected_sample) and sha(sample_raw) == expected_sample, 'original accepted sample bytes')
samples.append(json.loads(sample_raw))
pin = samples[-1]['vm']['full_pin']
require(pin['schema_version'] == 2 and pin['profile'] == 'full_maintenance_v1'
and digest(pin['policy_sha256']) and digest(pin['helper_binary_sha256']), 'actual native Full policy/code pin')
identity = pin['identity']
target = {key: identity[key] for key in ('tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version')}
require(target['tenant_id'] == TENANT and all(str(uuid.UUID(target[key])) == target[key]
for key in ('tenant_id', 'asset_id', 'agent_id'))
and all(type(target[key]) is int and target[key] > 0 for key in ('enrollment_generation', 'assignment_version')),
'exact qualified cloud target/generations')
for sample in samples:
native = sample['vm']; stored = sample['server']; current = stored['installation']
require(native['case_id'] == INSTALL_CASE and native['full_pin'] == pin
and native['verified_state_preservation'] is True and native['root_unresolved'] == 0
and native['read_only'] is True and native['product_state_writes'] is False
and native['rmm_jobs'] is False and native['approvals'] is False
and native['processes']['full']['sha256'] == pin['helper_binary_sha256']
and native['processes']['full']['uids'] == ['0'] * 4
and stored['central_root_scope_closed'] is True and current['sync_ready'] is True
and current['helper_sync_ready'] is True and current['revoked_at'] is None,
'accepted actual native root process and closed stored server state')
needed = ('rmm.sync.v1', 'helper.root.v1', 'root:run_script', 'run_script', 'script.full_maintenance/1',
'helper.policy.sha256:' + pin['policy_sha256'], 'helper.binary.sha256:' + pin['helper_binary_sha256'])
require(all(cap in current['capabilities'] for cap in needed), 'accepted actual Full capability publication')
require(all(intent['install']['target'][key] == target[key] for key in ('tenant_id', 'asset_id', 'agent_id')),
'accepted installation targets agree')
return {'target': target, 'full_policy_sha256': pin['policy_sha256'],
'helper_binary_sha256': pin['helper_binary_sha256'], 'boot_id': samples[-1]['vm']['boot_id'],
'connection_generation': samples[-1]['vm']['generation'], 'attestation_sha256': expected,
'attestation_runner_sha256': attested['runner_sha256'], 'sample_sha256': attested['sample_sha256']}
def remote(p):
"""Fixed server-only operations. Policy data is public; no private key/token."""
import datetime as dt
import fcntl
import http.client
import socket
import ssl
import stat
import subprocess
os.umask(0o077)
require(os.geteuid() == 0 and p['action'] in ('open', 'read', 'close', 'provision-mcp-root'), 'fixed server bootstrap operation')
intent = p['intent']; ident = str(uuid.UUID(intent['id']))
require(ident == intent['id'] and intent['type'] in ('rmm.script-console.policy-scope.v1',
'rmm.script-console.mcp-root-provision.v1'), 'canonical own policy intent')
provision = intent['type'] == 'rmm.script-console.mcp-root-provision.v1'
require(p['action'] in ('provision-mcp-root', 'read') if provision else p['action'] in ('open', 'read', 'close'),
'separate provision and scope operations; no automatic side effects')
root = Path('/opt/rust-discovery'); directory = root / 'devstate/root-policy'; policy_path = directory / 'policy.json'
case = root / 'devstate' / (('script-console-mcp-root-provision-' if provision else 'script-console-policy-scope-') + ident)
compose = ['docker', 'compose', '--env-file', str(root / 'devstate/.env'), '-f', str(root / 'deploy/server.compose.yaml')]
old_hash = 'cf15cbb68b590475df6def28e7dcffb7d88e0ca2d2555a06174fb654eeff05f4'
def enc(value): return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def hash_bytes(raw): return hashlib.sha256(raw).hexdigest()
def now(): return dt.datetime.now(dt.timezone.utc)
def stamp(value):
parsed = dt.datetime.fromisoformat(value.replace('Z', '+00:00'))
require(parsed.utcoffset() is not None, 'explicit UTC/timezone bound')
return parsed
def run(args, timeout=15, **kwargs):
result = subprocess.run(args, capture_output=True, timeout=timeout, **kwargs)
require(result.returncode == 0, 'fixed server command incomplete; private details withheld')
return result.stdout
def syncdir(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try: os.fsync(fd)
finally: os.close(fd)
def once(path, raw, uid=0, gid=0, mode=0o600, times=None):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
with os.fdopen(fd, 'wb') as out:
out.write(raw); out.flush(); os.fchown(out.fileno(), uid, gid); os.fchmod(out.fileno(), mode)
if times is not None: os.utime(out.fileno(), ns=times)
os.fsync(out.fileno())
syncdir(path.parent)
def owned(path, directory=False):
value = path.lstat()
require(not path.is_symlink() and value.st_uid == 0 and stat.S_IMODE(value.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(value.st_mode) if directory else stat.S_ISREG(value.st_mode) and value.st_nlink == 1),
'own protected policy history')
return value
def load(path):
value = owned(path); require(value.st_size <= 8 * 1024 * 1024, 'bounded history receipt')
return json.loads(path.read_bytes())
def read_policy():
parent = directory.lstat()
require(not directory.is_symlink() and stat.S_ISDIR(parent.st_mode) and parent.st_uid == 10001
and not parent.st_mode & 0o022, 'preserved protected policy parent')
fd = os.open(policy_path, os.O_RDONLY | os.O_NOFOLLOW)
try:
value = os.fstat(fd)
require(stat.S_ISREG(value.st_mode) and value.st_uid == 10001 and stat.S_IMODE(value.st_mode) == 0o600
and value.st_nlink == 1 and 0 < value.st_size <= 65536, 'protected bounded current policy')
raw = os.read(fd, 65537); after = os.fstat(fd); named = policy_path.lstat()
require(len(raw) == value.st_size and (value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
== (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns)
and (named.st_dev, named.st_ino) == (value.st_dev, value.st_ino), 'same complete named policy through read')
metadata = {'device': value.st_dev, 'inode': value.st_ino, 'uid': value.st_uid, 'gid': value.st_gid,
'mode': stat.S_IMODE(value.st_mode), 'bytes': value.st_size, 'atime_ns': value.st_atime_ns,
'mtime_ns': value.st_mtime_ns, 'ctime_ns': value.st_ctime_ns}
return raw, metadata
finally: os.close(fd)
def summary(raw, metadata):
out = {'sha256': hash_bytes(raw), 'metadata': metadata}
try:
policy = json.loads(raw)
out.update(schema_version=policy['schema_version'], profile=policy['profile'], expires_at=policy['expires_at'],
scope_count=len(policy['scopes']), expired=stamp(policy['expires_at']) <= now())
except Exception as error: out['parse_error_class'] = type(error).__name__
return out
def candidate():
raw = base64.b64decode(intent['candidate_bytes_b64'], validate=True)
require(len(raw) <= 65536 and hash_bytes(raw) == intent['candidate_sha256'], 'immutable exact candidate bytes')
body = json.loads(raw); target = intent['qualification']['target']
require(set(body) == {'schema_version', 'profile', 'expires_at', 'scopes'} and body['schema_version'] == 2
and type(body['schema_version']) is int and body['profile'] == 'development'
and body['expires_at'] == intent['expires_at'] and len(body['scopes']) == 1, 'one schema2 development scope')
expected = dict(target, principals=intent['principals'], helper_policy_sha256=intent['qualification']['full_policy_sha256'],
helper_binary_sha256=intent['qualification']['helper_binary_sha256'],
acceptance_evidence_id='script-console-full-linux-attested:' + intent['qualification']['attestation_sha256'],
allowed_services=[], allow_root_scripts=True, allowed_script_profiles=['full_maintenance_v1'], allow_reboot=False)
require(body['scopes'] == [expected] and 'apt' not in expected and 'root_logs' not in expected,
'exact target/principals/Full pins; no service/APT/log/reboot scope')
require(stamp(intent['expires_at']) - stamp(intent['created_at']) == dt.timedelta(seconds=900), 'fixed fifteen-minute intent')
return raw
def server_gate():
target = intent['qualification']['target']; tenant = str(uuid.UUID(target['tenant_id'])); agent = str(uuid.UUID(target['agent_id']))
require(tenant == '11111111-1111-4111-8111-111111111111' and tenant == target['tenant_id'] and agent == target['agent_id'], 'fixed target UUIDs')
scope = "tenant_id='" + tenant + "' AND agent_id='" + agent + "'"
# Only fixed public names, roles, permissions, capability/status fields.
principals = intent['principals']; automation = 'automation:' + tenant
require(principals == [automation, 'simulated-testprincipal-a'], 'exact existing MCP creator and simulated UI approver IDs')
selected = ','.join("'" + name + "'" for name in principals)
query = ("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object('observed_at',now(),"
"'installation',(SELECT json_build_object('tenant_id',tenant_id,'asset_id',asset_id,'agent_id',agent_id,"
"'enrollment_generation',enrollment_generation,'assignment_version',assignment_version,'capabilities',capabilities,"
"'connection_generation',connection_generation,'connection_boot_id',connection_boot_id,'last_contact_at',last_contact_at,"
"'certificate_sha256',certificate_sha256,'last_authenticated_certificate_sha256',last_authenticated_certificate_sha256,"
"'revoked_at',revoked_at,'sync_ready',sync_ready,'helper_sync_ready',helper_sync_ready,'restore_blocked',restore_blocked,"
"'sequence_regressed',sequence_regressed,'sync_recovery_required',sync_recovery_required) FROM agent_installations WHERE " + scope + "),"
"'memberships',(SELECT COALESCE(json_agg(q ORDER BY principal),'[]'::json) FROM (SELECT principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='" + tenant + "' AND principal IN (" + selected + ")) q),"
"'jobs',(SELECT count(*) FROM jobs WHERE " + scope + "),"
"'outbox',(SELECT count(*) FROM outbox o JOIN jobs j USING(tenant_id,job_id,attempt_id) WHERE " + scope.replace('tenant_id=', 'j.tenant_id=').replace('agent_id=', 'j.agent_id=') + "),"
"'permits',(SELECT count(*) FROM execution_permits e JOIN jobs j USING(tenant_id,job_id,attempt_id) WHERE " + scope.replace('tenant_id=', 'j.tenant_id=').replace('agent_id=', 'j.agent_id=') + "),"
"'unresolved',(SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "' AND state NOT IN ('succeeded','failed','cancelled','expired')),"
"'migrations',(SELECT json_agg(version ORDER BY version) FROM _sqlx_migrations WHERE success)); COMMIT;")
data = json.loads(run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'postgres', '-d', 'rmm'], input=query.encode()))
installed = data['installation']
require(installed is not None and all(installed[key] == value for key, value in target.items()), 'same stored enrolled target/generations')
require(data['migrations'] == list(range(1, 15)), 'actual additive migration14 server prerequisite')
require([data[key] for key in ('jobs', 'outbox', 'permits')] == [30, 30, 26], 'same target-scoped closed30/30/26 before scope open')
require(data['unresolved'] == 0 and installed['revoked_at'] is None and installed['sync_ready'] is True
and installed['helper_sync_ready'] is True and all(installed[key] is False for key in
('restore_blocked', 'sequence_regressed', 'sync_recovery_required'))
and installed['connection_boot_id'] == intent['qualification']['boot_id']
and installed['connection_generation'] >= intent['qualification']['connection_generation']
and installed['certificate_sha256'] == installed['last_authenticated_certificate_sha256']
and 0 <= (now() - stamp(installed['last_contact_at'])).total_seconds() <= 45, 'fresh authenticated ready stored Cloud client')
needed = ('rmm.sync.v1', 'helper.root.v1', 'root:run_script', 'run_script', 'script.full_maintenance/1',
'helper.policy.sha256:' + intent['qualification']['full_policy_sha256'],
'helper.binary.sha256:' + intent['qualification']['helper_binary_sha256'])
require(all(value in installed['capabilities'] for value in needed), 'fresh stored Full policy/code capability binding')
rows = {row['principal']: row for row in data['memberships']}
require(set(rows) == set(principals), 'all explicitly bound existing principals')
for name in principals:
row = rows[name]; permissions = {'root:execute', 'scripts:execute', 'operations:plan', 'operations:submit', 'operations:read'}
permissions.add('plans:approve' if name == 'simulated-testprincipal-a' else 'operations:plan')
require(row['revoked_at'] is None and row['kind'] == ('test_human' if name == 'simulated-testprincipal-a' else 'automation')
and permissions <= set(row['permissions']), 'existing principal lacks required scope; never mutate memberships')
if name == automation:
exact = ['inventory:read', 'logs:read', 'operations:read', 'operations:plan',
'operations:submit', 'jobs:cancel', 'scripts:execute', 'root:execute']
require(row['permissions'] == exact, 'exact provisioned automation rights; no approval/revoke/SYSTEM authority')
return data
def roles_and_auth():
out = {}
names = ('RMM_PROFILE', 'RMM_DEV_AUTH', 'RMM_SERVER_ROLE', 'RMM_UI_ORIGIN', 'RMM_DEV_ROOT_ENABLED',
'RMM_DEV_ROOT_POLICY_FILE', 'RMM_DEV_SYSTEM_ENABLED', 'RMM_DEV_SYSTEM_POLICY_FILE',
'RMM_DEV_DELIVERY_FAULTS', 'RMM_DEV_DELIVERY_FAULTS_FILE')
select = ' '.join('(eq $key "' + name + '")' for name in names)
template = '{{range .Config.Env}}{{$key := index (split . "=") 0}}{{if or ' + select + '}}{{println .}}{{end}}{{end}}'
for role in ('api', 'gateway'):
cid = run(compose + ['ps', '-q', role]).decode().strip(); require(cid and '\n' not in cid, 'one actual role')
image = run(['docker', 'inspect', cid, '--format', '{{.Image}}']).decode().strip()
require(image == intent['expected_server_image'], 'exact Root-reviewed deployed server image')
env = {}
for line in run(['docker', 'inspect', cid, '--format', template]).decode().splitlines():
if not line:
continue
key, separator, value = line.partition('=')
require(separator == '=' and key in names and key not in env, 'strict unique selected public environment field')
env[key] = value
require(env.get('RMM_PROFILE') == 'development' and env.get('RMM_DEV_AUTH') == 'true'
and env.get('RMM_SERVER_ROLE') == role and env.get('RMM_UI_ORIGIN') == 'https://localhost:18443'
and env.get('RMM_DEV_ROOT_ENABLED') == 'true' and env.get('RMM_DEV_ROOT_POLICY_FILE') == '/root-policy/policy.json'
and env.get('RMM_DEV_SYSTEM_ENABLED') is None and env.get('RMM_DEV_SYSTEM_POLICY_FILE') is None
and env.get('RMM_DEV_DELIVERY_FAULTS') == 'false' and env.get('RMM_DEV_DELIVERY_FAULTS_FILE') is None,
'unchanged existing dev/test roles/flags; no auth or server flag changes')
mounts = json.loads(run(['docker', 'inspect', cid, '--format', '{{json .Mounts}}']))
policy_mounts = [mount for mount in mounts if mount['Destination'] == '/root-policy']
require(len(policy_mounts) == 1 and policy_mounts[0]['Type'] == 'bind' and policy_mounts[0]['RW'] is False
and policy_mounts[0]['Source'] == str(directory), 'actual unchanged read-only Root policy mount')
out[role] = {'container_id': cid, 'image_id': image, 'settings': env, 'policy_mount': policy_mounts[0]}
class HTTPS(http.client.HTTPSConnection):
def connect(self):
self.sock = self._context.wrap_socket(socket.create_connection(('127.0.0.1', 18443), timeout=5), server_hostname=self.host)
client = HTTPS('localhost', 18443, timeout=5, context=ssl.create_default_context(cafile=str(root / 'devstate/api-pki/ca.pem')))
try:
client.request('GET', '/auth/config'); response = client.getresponse(); raw = response.read(4097)
require(response.status == 200 and len(raw) <= 4096 and json.loads(raw) ==
{'oidc_configured': False, 'oidc_login_url': None, 'dev_login_enabled': True}, 'honest private dev/test auth config')
finally: client.close()
return out
def provision_state():
tenant = '11111111-1111-4111-8111-111111111111'; actor = 'automation:' + tenant
query = ("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object('actor',"
"(SELECT row_to_json(q) FROM (SELECT tenant_id,principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='" + tenant + "' AND principal='" + actor + "') q),"
"'jobs',(SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "'),"
"'outbox',(SELECT count(*) FROM outbox WHERE tenant_id='" + tenant + "'),"
"'permits',(SELECT count(*) FROM execution_permits WHERE tenant_id='" + tenant + "'),"
"'unresolved',(SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "' AND state NOT IN ('succeeded','failed','cancelled','expired')),"
"'other_memberships_sha256',(SELECT encode(sha256(convert_to(coalesce(string_agg(to_jsonb(m)::text,E'\\n' ORDER BY tenant_id,principal),''),'UTF8')),'hex') FROM memberships m WHERE NOT(tenant_id='" + tenant + "' AND principal='" + actor + "'))); COMMIT;")
return json.loads(run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'postgres', '-d', 'rmm'], input=query.encode()))
if provision:
before_rights = ['inventory:read', 'logs:read', 'operations:read', 'operations:plan',
'operations:submit', 'jobs:cancel', 'scripts:execute']
actor = 'automation:11111111-1111-4111-8111-111111111111'
tenant = '11111111-1111-4111-8111-111111111111'
expected_actor = {'tenant_id': tenant, 'principal': actor, 'kind': 'automation',
'permissions': before_rights, 'revoked_at': None}
require(intent['actor_before'] == expected_actor and intent['actor_after'] == dict(expected_actor,
permissions=before_rights + ['root:execute']) and intent['old_policy_sha256'] == old_hash
and hash_bytes(enc(intent)) == p['intent_sha256'], 'exact one existing actor/rights transition')
if p['action'] == 'read':
out = {'id': ident, 'read_only': True, 'case_present': case.exists(), 'retry_allowed': False}
for key, fn in (('database', provision_state), ('roles', roles_and_auth)):
try: out[key] = fn()
except Exception as error: out[key] = {'read_error_class': type(error).__name__}
try:
current, metadata = read_policy(); out['current_policy'] = summary(current, metadata)
except Exception as error: out['policy_read_error_class'] = type(error).__name__
if case.exists():
owned(case, True)
for name in ('intent.json', 'before.json', 'provision-entered.json', 'sql-result.json', 'after.json', 'provision-result.json'):
if (case / name).exists():
try: out[name] = load(case / name)
except Exception as error: out[name] = {'read_error_class': type(error).__name__}
if (case / 'intent.json').exists(): require(load(case / 'intent.json') == intent, 'same remote provision intent')
return out
lock = os.open(root / 'devstate/.script-console-policy-scope.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
try:
require(not case.exists() and not case.is_symlink() and stamp(intent['created_at']) <= now()
< stamp(intent['provision_before']) <= now() + dt.timedelta(seconds=900), 'new short-lived explicit provision case')
roles = roles_and_auth(); current, metadata = read_policy(); body = json.loads(current)
require(hash_bytes(current) == old_hash and body['schema_version'] == 1 and body['profile'] == 'development'
and stamp(body['expires_at']) <= now(), 'same exact expired closed Root policy before provisioning')
before = provision_state()
require(before['actor'] == expected_actor and {key: before[key] for key in ('jobs', 'outbox', 'permits', 'unresolved')}
== {'jobs': 30, 'outbox': 30, 'permits': 26, 'unresolved': 0}, 'exact current seven-right actor and closed30/30/26')
owned(root / 'devstate', True); case.mkdir(mode=0o700); syncdir(case.parent)
once(case / 'intent.json', enc(intent)); once(case / 'before.json', enc({'database': before,
'roles': roles, 'policy_sha256': old_hash, 'policy_metadata': metadata}))
once(case / 'provision-entered.json', enc({'id': ident, 'intent_sha256': p['intent_sha256'],
'adds_only': 'root:execute', 'no_retry': True}))
latest, _ = read_policy(); require(latest == current, 'closed policy CAS immediately before SQL')
# Exact existing row, tenant context, closed-job predicate and a
# RETURNING count assertion in the transaction. ON_ERROR_STOP means
# count0 aborts before COMMIT; connection close rolls back.
rights_sql = 'ARRAY[' + ','.join("'" + value + "'" for value in before_rights) + ']::text[]'
query = ("BEGIN ISOLATION LEVEL SERIALIZABLE; SET LOCAL app.tenant_id='" + tenant + "'; "
"WITH changed AS (UPDATE memberships SET permissions=array_append(permissions,'root:execute') "
"WHERE tenant_id='" + tenant + "' AND principal='" + actor + "' AND kind='automation' AND revoked_at IS NULL "
"AND permissions=" + rights_sql + " AND (SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "')=30 "
"AND (SELECT count(*) FROM outbox WHERE tenant_id='" + tenant + "')=30 "
"AND (SELECT count(*) FROM execution_permits WHERE tenant_id='" + tenant + "')=26 "
"AND NOT EXISTS(SELECT 1 FROM jobs WHERE tenant_id='" + tenant + "' AND state NOT IN ('succeeded','failed','cancelled','expired')) "
"RETURNING tenant_id,principal,kind,permissions,revoked_at) "
"SELECT json_build_object('changed_count',count(*),'assert_one',1/count(*),'after',(json_agg(changed))->0) FROM changed; COMMIT;")
result = json.loads(run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'postgres', '-d', 'rmm'], input=query.encode()))
require(result == {'changed_count': 1, 'assert_one': 1, 'after': intent['actor_after']}, 'exact committed public actor row')
once(case / 'sql-result.json', enc(result))
after = provision_state(); once(case / 'after.json', enc(after))
require(after == dict(before, actor=intent['actor_after']), 'only this one actor permission changed; all other memberships and counts retained')
latest, latest_metadata = read_policy()
require(latest == current and latest_metadata['inode'] == metadata['inode'] and roles_and_auth() == roles,
'closed policy and server flags/roles unchanged after provisioning')
final = {'id': ident, 'provisioned': True, 'actor': actor, 'added_permission': 'root:execute',
'other_memberships_unchanged': True, 'policy_remains_closed': True, 'jobs_created': False,
'approvals_created': False, 'tokens_or_sessions_created': False, 'automatic_scope_open': False}
once(case / 'provision-result.json', enc(final)); return final
finally: os.close(lock)
raw_candidate = candidate()
require(intent['old_policy_sha256'] == old_hash and hash_bytes(enc(intent)) == p['intent_sha256'], 'own complete immutable policy intent')
if p['action'] == 'read':
out = {'id': ident, 'read_only': True, 'case_present': case.exists(), 'retry_allowed': False}
try:
raw, metadata = read_policy(); out['current_policy'] = summary(raw, metadata)
out['matches_original_closed'] = hash_bytes(raw) == old_hash
out['matches_own_candidate'] = hash_bytes(raw) == intent['candidate_sha256']
except Exception as error: out['policy_read_error_class'] = type(error).__name__
if case.exists():
owned(case, True)
for name in ('intent.json', 'original-metadata.json', 'open-entered.json', 'open-result.json', 'close-entered.json', 'close-result.json'):
if (case / name).exists():
try: out[name] = load(case / name)
except Exception as error: out[name] = {'read_error_class': type(error).__name__}
if (case / 'intent.json').exists(): require(load(case / 'intent.json') == intent, 'same remote original intent')
return out
# Policy writers using this source serialize. Other root maintenance must be
# coordinated; unexpected current bytes/inode always fail the final CAS.
lock = os.open(root / 'devstate/.script-console-policy-scope.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
try:
if p['action'] == 'open':
require(not case.exists() and not case.is_symlink(), 'existing policy case; read only')
require(stamp(intent['created_at']) <= now() < stamp(intent['expires_at']) <= now() + dt.timedelta(seconds=900), 'fresh fixed bounded candidate expiry')
gate = server_gate(); roles = roles_and_auth(); previous, metadata = read_policy()
body = json.loads(previous)
require(hash_bytes(previous) == old_hash and set(body) == {'schema_version', 'profile', 'expires_at', 'scopes'}
and type(body['schema_version']) is int and body['schema_version'] == 1 and body['profile'] == 'development'
and isinstance(body['scopes'], list) and stamp(body['expires_at']) <= now(), 'exact historical closed schema1 policy CAS')
parent = root / 'devstate'; owned(parent, True)
case.mkdir(mode=0o700); syncdir(parent)
once(case / 'intent.json', enc(intent)); once(case / 'original-policy.json', previous)
once(case / 'original-metadata.json', enc(metadata)); once(case / 'before-server.json', enc({'gate': gate, 'roles': roles}))
# Durable one-use marker BEFORE any policy exposure or rename.
once(case / 'open-entered.json', enc({'id': ident, 'intent_sha256': p['intent_sha256'], 'candidate_sha256': intent['candidate_sha256']}))
next_path = directory / ('script-full-' + ident + '.open-next')
once(next_path, raw_candidate, uid=10001, gid=10001)
current, current_metadata = read_policy()
require(hash_bytes(current) == old_hash and current_metadata['device'] == metadata['device']
and current_metadata['inode'] == metadata['inode'] and current_metadata['mtime_ns'] == metadata['mtime_ns'], 'last exact closed policy/inode CAS')
require(now() < stamp(intent['expires_at']), 'candidate still unexpired immediately before exposure')
os.replace(next_path, policy_path); syncdir(directory)
current, current_metadata = read_policy(); require(current == raw_candidate, 'actual exact new policy bytes')
result = {'id': ident, 'opened': True, 'policy_sha256': hash_bytes(current), 'expires_at': intent['expires_at'],
'metadata': current_metadata, 'server_flags_unchanged': roles_and_auth() == roles,
'jobs_created': False, 'approvals_created': False, 'database_mutations': False}
require(result['server_flags_unchanged'], 'same roles and flags after bounded policy replacement')
once(case / 'open-result.json', enc(result)); return result
owned(case, True); require(load(case / 'intent.json') == intent, 'close only original own remote case')
require((case / 'open-entered.json').exists() and not (case / 'close-entered.json').exists(), 'one close after own open; read only on uncertainty')
owned(case / 'original-policy.json'); previous = (case / 'original-policy.json').read_bytes()
metadata = load(case / 'original-metadata.json')
require(hash_bytes(previous) == old_hash and metadata['uid'] == 10001 and metadata['mode'] == 0o600, 'original private closed backup and metadata')
current, current_metadata = read_policy(); require(current == raw_candidate, 'foreign or changed policy; never overwrite')
once(case / 'close-entered.json', enc({'id': ident, 'expected_current_sha256': intent['candidate_sha256'], 'restore_sha256': old_hash}))
next_path = directory / ('script-full-' + ident + '.close-next')
once(next_path, previous, uid=metadata['uid'], gid=metadata['gid'], mode=metadata['mode'], times=(metadata['atime_ns'], metadata['mtime_ns']))
last, last_metadata = read_policy()
require(last == raw_candidate and last_metadata['device'] == current_metadata['device']
and last_metadata['inode'] == current_metadata['inode'], 'last exact own policy/inode CAS')
os.replace(next_path, policy_path); syncdir(directory)
restored, restored_metadata = read_policy()
require(restored == previous and all(restored_metadata[key] == metadata[key] for key in ('uid', 'gid', 'mode', 'bytes', 'mtime_ns'))
and stamp(json.loads(restored)['expires_at']) <= now(), 'exact old bytes/owner/mode/mtime restored and closed')
result = {'id': ident, 'closed': True, 'restored_sha256': hash_bytes(restored), 'metadata': restored_metadata,
'historical_original_inode_retained_in_receipt': True, 'restored_inode_is_atomic_replacement': True,
'jobs_created': False, 'approvals_created': False, 'database_mutations': False}
once(case / 'close-result.json', enc(result)); return result
finally: os.close(lock)
def prepare(args):
qualification = accepted_native(args.attestation.resolve(), args.accepted_attestation_sha)
require(re.fullmatch('sha256:[a-f0-9]{64}', args.expected_server_image) is not None, 'explicit reviewed deployed image ID')
principals = ['automation:' + TENANT, SIMULATED]
created = dt.datetime.now(dt.timezone.utc).replace(microsecond=0); expiry = created + dt.timedelta(minutes=15)
scope = dict(qualification['target'], principals=principals, helper_policy_sha256=qualification['full_policy_sha256'],
helper_binary_sha256=qualification['helper_binary_sha256'],
acceptance_evidence_id='script-console-full-linux-attested:' + qualification['attestation_sha256'],
allowed_services=[], allow_root_scripts=True, allowed_script_profiles=['full_maintenance_v1'], allow_reboot=False)
candidate = encode({'schema_version': 2, 'profile': 'development', 'expires_at': expiry.isoformat(), 'scopes': [scope]})
ident = str(uuid.uuid4()); STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
private_directory(STATE); folder = STATE / ident; folder.mkdir(mode=0o700)
intent = {'type': 'rmm.script-console.policy-scope.v1', 'id': ident, 'runner_sha256': sha(Path(__file__).read_bytes()),
'remote_source_sha256': sha(inspect.getsource(remote).encode()), 'support_sha256': SUPPORT,
'qualification': qualification, 'attestation_path': str(args.attestation.resolve()), 'principals': principals,
'expected_server_image': args.expected_server_image, 'old_policy_sha256': OLD_POLICY_SHA,
'created_at': created.isoformat(), 'expires_at': expiry.isoformat(), 'candidate_sha256': sha(candidate),
'candidate_bytes_b64': base64.b64encode(candidate).decode(), 'no_jobs_or_approvals': True}
create(folder / 'intent.json', encode(intent)); create(folder / 'candidate-policy.json', candidate)
return {'id': ident, 'intent': str(folder / 'intent.json'), 'intent_sha256': sha(encode(intent)),
'candidate_sha256': sha(candidate), 'expires_at': intent['expires_at'], 'target_called': False}
def prepare_actor(args):
require(re.fullmatch('sha256:[a-f0-9]{64}', args.expected_server_image) is not None, 'explicit reviewed deployed image ID')
actor = {'tenant_id': TENANT, 'principal': 'automation:' + TENANT, 'kind': 'automation',
'permissions': AUTOMATION_RIGHTS, 'revoked_at': None}
created = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
ident = str(uuid.uuid4()); STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
private_directory(STATE); folder = STATE / ident; folder.mkdir(mode=0o700)
intent = {'type': 'rmm.script-console.mcp-root-provision.v1', 'id': ident,
'runner_sha256': sha(Path(__file__).read_bytes()), 'remote_source_sha256': sha(inspect.getsource(remote).encode()),
'support_sha256': SUPPORT, 'expected_server_image': args.expected_server_image,
'old_policy_sha256': OLD_POLICY_SHA, 'actor_before': actor,
'actor_after': dict(actor, permissions=AUTOMATION_RIGHTS + ['root:execute']),
'created_at': created.isoformat(), 'provision_before': (created + dt.timedelta(minutes=15)).isoformat(),
'authorization_basis': 'Explicit user AI/MCP Root maintenance objective; separately reviewed development actor provisioning',
'no_jobs_or_approvals': True, 'no_scope_open': True}
create(folder / 'intent.json', encode(intent))
return {'id': ident, 'intent': str(folder / 'intent.json'), 'intent_sha256': sha(encode(intent)),
'adds_only': 'root:execute', 'automatic_scope_open': False, 'target_called': False}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('prepare-local', 'open', 'read', 'close', 'prepare-mcp-root-local', 'provision-mcp-root'))
parser.add_argument('--id'); parser.add_argument('--attestation', type=Path)
parser.add_argument('--accepted-attestation-sha'); parser.add_argument('--expected-server-image')
parser.add_argument('--access-root', type=Path, default=Path('/home/kevin/Schreibtisch/Coding/rust-discovery'))
parser.add_argument('--execute-policy-open', action='store_true'); parser.add_argument('--execute-policy-close', action='store_true')
parser.add_argument('--execute-mcp-root-provision', action='store_true')
args = parser.parse_args(); os.umask(0o077)
require(all(sha((ROOT / name).read_bytes()) == value for name, value in SUPPORT.items()), 'exact existing strict SSH support')
if args.phase == 'prepare-local':
require(args.id is None and args.attestation is not None and args.accepted_attestation_sha is not None
and args.expected_server_image is not None, 'explicit Root accepted native proof and deployed image')
print(json.dumps(prepare(args))); return
if args.phase == 'prepare-mcp-root-local':
require(args.id is None and args.expected_server_image is not None, 'new explicitly reviewed actor provision intent')
print(json.dumps(prepare_actor(args))); return
ident = str(uuid.UUID(args.id)); require(ident == args.id, 'canonical original case UUID')
private_directory(STATE); folder = STATE / ident; private_directory(folder)
intent = json.loads(protected(folder / 'intent.json'))
require(intent['id'] == ident and intent['runner_sha256'] == sha(Path(__file__).read_bytes())
and intent['remote_source_sha256'] == sha(inspect.getsource(remote).encode()) and intent['support_sha256'] == SUPPORT,
'original same-source immutable policy case')
provision = intent['type'] == 'rmm.script-console.mcp-root-provision.v1'
require(args.phase in ('provision-mcp-root', 'read') if provision else args.phase in ('open', 'read', 'close'), 'same original intent operation kind')
if args.phase in ('open', 'close', 'provision-mcp-root'):
allowed = {'open': args.execute_policy_open, 'close': args.execute_policy_close,
'provision-mcp-root': args.execute_mcp_root_provision}[args.phase]
require(allowed, 'explicit separate bounded bootstrap operation')
if args.phase == 'open':
require(accepted_native(Path(intent['attestation_path']), intent['qualification']['attestation_sha256']) == intent['qualification'], 'accepted evidence unchanged before open')
create(folder / (args.phase + '-requested.json'), encode({'id': ident, 'intent_sha256': sha(encode(intent)), 'retry_allowed': False}))
import remote_client_bootstrap as bootstrap
bootstrap.ROOT = args.access_root.resolve(); bootstrap.access.ROOT = bootstrap.ROOT
settings = bootstrap.access.load_config(bootstrap.ROOT / 'credentials/server.conf')
require(settings['address'] in ('88.99.80.202', 'discovery.ease-technologies.de') and settings['username'] == 'root'
and settings.get('port', '22') == '22', 'fixed independently trusted cloud server')
result = bootstrap.rpc('server.conf', remote, {'action': args.phase, 'intent': intent, 'intent_sha256': sha(encode(intent))})
create(folder / (args.phase + '-reply-' + str(uuid.uuid4()) + '.json'), encode(result))
print(json.dumps(result))
if __name__ == '__main__':
try: main()
except Exception as error:
print('SCRIPT_POLICY_SCOPE_INCOMPLETE:' + type(error).__name__ + '; preserve case, read only after any requested mutation')
raise SystemExit(2) from None