Files
rust-discovery/tools/dev_mcp_script_scope.py
T
2026-11-18 16:21:12 +01:00

85 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""Manage scoped MCP planning on one existing Linux or Windows script-helper rule."""
import argparse
import fcntl
import inspect
import json
from pathlib import Path
import re
import stat
import subprocess
import uuid
from dev_linux_helper_rollover import POLICY, encoded, protected, replace, require
from dev_stage import ssh_prefix
def configure(path, platform, binding, action):
signer = (path.parent.parent / 'jobs/ed25519.pem').lstat()
require(stat.S_ISREG(signer.st_mode), 'Expected a regular job signer file')
owner = signer.st_uid
lock = path.with_name('operator.lock')
protected(path, owner)
lock_info = lock.lstat()
require(stat.S_ISREG(lock_info.st_mode) and lock_info.st_uid in (0, owner)
and not lock_info.st_mode & 0o022,
'Invalid operator.lock')
with lock.open('rb') as guard:
fcntl.flock(guard, fcntl.LOCK_EX)
info = protected(path, owner)
require(stat.S_IMODE(info.st_mode) == 0o600 and info.st_size <= 65536,
'Invalid managed policy file')
policy = json.loads(path.read_bytes())
require(policy['schema_version'] == 1, 'Unknown policy format')
matches = [scope for scope in policy[platform]
if all(scope.get(key) == value for key, value in binding.items())]
require(len(matches) == 1, 'Expected exactly one matching existing device rule')
scope = matches[0]
require(scope.get('allowed_script_profiles') == ['full_maintenance_v1']
and (platform != 'linux' or scope.get('allow_root_scripts') is True)
and all(re.fullmatch(r'[0-9a-f]{64}', scope.get(key) or '')
for key in ('helper_binary_sha256', 'helper_policy_sha256')),
'Rule does not describe a pinned administrator script helper')
principals = scope['principals']
require(isinstance(principals, list) and 1 <= len(principals) <= 64
and len(principals) == len(set(principals)),
'Invalid rule principals')
marker = 'mcp:scoped'
enabled = marker in principals
changed = action != 'check' and enabled != (action == 'enable')
if changed:
if action == 'enable':
require(len(principals) < 64, 'Rule principal list is full')
principals.append(marker)
else:
require(len(principals) > 1, 'Removing the last principal would invalidate this rule')
principals.remove(marker)
data = encoded(policy)
require(len(data) <= 65536, 'Managed policy exceeds the server size limit')
replace(path, data)
return {**binding, 'platform': platform, 'scoped_mcp_planning': marker in principals,
'changed': changed}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('check', 'enable', 'disable'))
parser.add_argument('--platform', required=True, choices=('linux', 'windows'))
for field in ('tenant', 'asset', 'agent'):
parser.add_argument('--' + field, required=True, type=uuid.UUID)
parser.add_argument('--evidence', required=True, help='acceptance_evidence_id of the existing device rule')
args = parser.parse_args()
binding = dict(tenant_id=str(args.tenant), asset_id=str(args.asset), agent_id=str(args.agent),
acceptance_evidence_id=args.evidence)
# Send the same locked atomic file operations as helper rollover through the pinned SSH profile.
program = 'import fcntl,json,os,re,stat,tempfile\nfrom pathlib import Path\n'
for helper in (require, protected, encoded, replace, configure):
program += inspect.getsource(helper) + '\n'
params = (args.platform, binding, args.action)
program += f'print(json.dumps(configure(Path({str(POLICY)!r}), *{params!r})))\n'
subprocess.run([*ssh_prefix('server'), 'python3 -I -'], input=program, text=True, check=True)
if __name__ == '__main__':
main()