398 lines
25 KiB
Python
398 lines
25 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only by default. Explicit future dev/test UI acceptance, never autofreedom.
|
|
|
|
This harness never starts/stops a VM service outside approved RMM jobs, edits target policy, prepares APT
|
|
baselines over SSH, resets journals, approves over HTTP/SQL, or retries effects.
|
|
Unwired fault/reboot/planning adapters are reported pending_protocol, not passed.
|
|
"""
|
|
import argparse
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import ssl
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.modules.setdefault('vm_mvp_acceptance', sys.modules[__name__])
|
|
STATE = ROOT / 'devstate'
|
|
CA = STATE / 'pki/ca.pem'
|
|
ORIGIN = 'https://rmm-dev.internal:18443'
|
|
UNIT = 'rmm-mvp-test.service'
|
|
HELLO = "printf '%s\\n' 'Hello World'\n"
|
|
SERVICE_SETUP = """set -eu
|
|
unit=/etc/systemd/system/rmm-mvp-test.service
|
|
test -f "$unit"
|
|
test ! -L "$unit"
|
|
test ! -s "$unit"
|
|
test "$(stat -c '%u:%a:%h' "$unit")" = '0:600:1'
|
|
printf '%s' '[Unit]
|
|
Description=RMM explicitly approved temporary MVP test service
|
|
[Service]
|
|
Type=simple
|
|
User=rmm-agent
|
|
Group=rmm-agent
|
|
ExecStart=/usr/bin/sleep infinity
|
|
Restart=no
|
|
NoNewPrivileges=true
|
|
ProtectSystem=strict
|
|
ProtectHome=true
|
|
PrivateTmp=true
|
|
' > "$unit"
|
|
chmod 0644 "$unit"
|
|
systemctl daemon-reload
|
|
test "$(systemctl show --property=LoadState --value rmm-mvp-test.service)" = loaded
|
|
printf '%s\\n' 'RMM test unit prepared'
|
|
"""
|
|
TERMINAL = {'succeeded', 'failed', 'cancelled', 'expired'}
|
|
BASIC = ('hello', 'refresh_inventory', 'query_logs', 'service_setup', 'service_start', 'service_stop')
|
|
ADVANCED = ('apt_native_install', 'apt_native_update', 'ensure_package', 'apply_updates',
|
|
'duplicate_offer', 'lost_result_ack', 'cancel_queued', 'expired_offline', 'reboot_last')
|
|
EXECUTABLE = BASIC + ADVANCED
|
|
PENDING = {} # Routes are defined. Missing deployment/measurements are runtime blockers.
|
|
|
|
|
|
class GuardError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def require(value, code):
|
|
if not value:
|
|
raise GuardError(code)
|
|
|
|
|
|
def now():
|
|
return dt.datetime.now(dt.timezone.utc)
|
|
|
|
|
|
def timestamp(value):
|
|
require(isinstance(value, str), 'timestamp_type')
|
|
# Rust/chrono emits RFC3339 nanoseconds. Python 3.10 accepts only up to
|
|
# microseconds in fixed fractional widths. Retain the raw evidence; pad or
|
|
# truncate only the comparison, including variable-width PostgreSQL times.
|
|
comparable = re.sub(r'\.(\d+)(?=Z$|[+-]\d{2}:\d{2}$)',
|
|
lambda match: '.'+(match[1]+'000000')[:6], value)
|
|
parsed = dt.datetime.fromisoformat(comparable.replace('Z', '+00:00'))
|
|
require(parsed.utcoffset() is not None, 'timestamp_timezone_required')
|
|
return parsed
|
|
|
|
|
|
def strict_object(pairs):
|
|
result = {}
|
|
for key, value in pairs:
|
|
require(key not in result, 'duplicate_json_field')
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def protected_json(path):
|
|
path = Path(path)
|
|
require(not path.is_symlink() and not path.parent.is_symlink(), 'protected_file_symlink')
|
|
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
|
with os.fdopen(fd, 'rb') as stream:
|
|
metadata = os.fstat(stream.fileno())
|
|
require(stat.S_ISREG(metadata.st_mode) and metadata.st_uid == os.getuid()
|
|
and metadata.st_mode & 0o777 == 0o600 and metadata.st_size <= 1024 * 1024,
|
|
'protected_file_owner_mode_size')
|
|
return json.loads(stream.read(), object_pairs_hook=strict_object)
|
|
|
|
|
|
def write_private(path, value):
|
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
json.dump(value, stream, indent=2); stream.flush(); os.fsync(stream.fileno())
|
|
|
|
|
|
def config(value):
|
|
require(set(value) == {'profile', 'origin', 'connect_address', 'ca_file', 'tenant_id', 'asset_id', 'agent_id', 'agent_uid'}, 'config_fields')
|
|
require(value['profile'] == 'dev/test' and value['origin'] == ORIGIN
|
|
and value['connect_address'] == '127.0.0.1:18443' and Path(value['ca_file']) == CA,
|
|
'dev_test_loopback_verified_tls_only')
|
|
for name in ('tenant_id', 'asset_id', 'agent_id'):
|
|
require(str(uuid.UUID(value[name])) == value[name], 'canonical_fixed_uuid_required')
|
|
require(type(value['agent_uid']) is int and value['agent_uid'] > 0, 'network_agent_must_be_nonroot')
|
|
return value
|
|
|
|
|
|
def default_config():
|
|
installed = protected_json(STATE / 'vm-jobs/bootstrap.json')
|
|
return config(dict(profile='dev/test', origin=ORIGIN, connect_address='127.0.0.1:18443', ca_file=str(CA),
|
|
tenant_id='11111111-1111-4111-8111-111111111111', asset_id=installed['asset_id'],
|
|
agent_id=installed['agent_id'], agent_uid=installed['agent_uid']))
|
|
|
|
|
|
def schedule(start, deadline):
|
|
require(start.tzinfo is not None and deadline.tzinfo is not None
|
|
and start < deadline and deadline > now() and deadline - start <= dt.timedelta(hours=1),
|
|
'fixed_bounded_future_deadline_required')
|
|
return dict(not_before=start.isoformat(), start_before=deadline.isoformat(), offline_policy='wait_until_deadline')
|
|
|
|
|
|
def case_input(name, settings, start=None, planning=None):
|
|
require(name in EXECUTABLE, 'unknown_case')
|
|
if name in ADVANCED:
|
|
from vm_mvp_adapters import advanced_input
|
|
return advanced_input(name, settings, start or now(), planning)
|
|
start = start or now()
|
|
action, identity, timeout = name, 'agent_service', 60
|
|
parameters = {}
|
|
if name in ('hello', 'service_setup'):
|
|
action = 'run_script'
|
|
script, output = (HELLO, 'Hello World\n') if name == 'hello' else (SERVICE_SETUP, 'RMM test unit prepared\n')
|
|
identity = 'agent_service' if name == 'hello' else 'root'
|
|
parameters = dict(variants=[dict(os_family='linux', interpreter='posix_sh', encoding='utf-8', script_utf8=script)], arguments=[], expected_stdout=output)
|
|
elif name == 'refresh_inventory':
|
|
parameters = dict(scope='linux.base')
|
|
elif name == 'query_logs':
|
|
parameters = dict(unit=UNIT, since=(start-dt.timedelta(minutes=5)).isoformat(), until=start.isoformat(), max_lines=50)
|
|
else:
|
|
action, identity, timeout = 'set_service_state', 'root', 180
|
|
parameters = dict(unit=UNIT, state='running' if name == 'service_start' else 'stopped')
|
|
parameters.update(execution_identity=identity, timeout_seconds=timeout, max_output_bytes=65536)
|
|
return dict(tenant_id=settings['tenant_id'], action=action, targets={'asset_ids': [settings['asset_id']]}, parameters=parameters,
|
|
schedule=schedule(start, start+dt.timedelta(minutes=15)), rollout=dict(max_parallel=1, halt_after_failures=1),
|
|
reason='Explicit dev/test VM acceptance · ' + name)
|
|
|
|
|
|
def validate_run_artifact(artifact, settings, cases):
|
|
require(set(artifact) == {'profile', 'tenant_id', 'asset_id', 'agent_id', 'approved_cases', 'expires_at',
|
|
'permission_origin', 'chat_date', 'testsimulation', 'expected_principal'}, 'run_artifact_fields')
|
|
require(artifact['profile'] == 'dev/test' and artifact['testsimulation'] is True
|
|
and artifact['permission_origin'] == 'explicit_chat_user_permission'
|
|
and artifact['chat_date'] == '2026-11-12'
|
|
and artifact['expected_principal'] == 'simulated-testprincipal-a', 'explicit_simulated_chat_permission_required')
|
|
require(all(artifact[key] == settings[key] for key in ('tenant_id', 'asset_id', 'agent_id')), 'run_artifact_target_mismatch')
|
|
require(now() < timestamp(artifact['expires_at']) <= now()+dt.timedelta(hours=1), 'run_artifact_expired_or_unbounded')
|
|
require(isinstance(artifact['approved_cases'], list) and cases and len(set(cases)) == len(cases)
|
|
and set(cases) <= set(artifact['approved_cases']) and set(cases) <= set(EXECUTABLE), 'explicit_fixed_case_scope_required')
|
|
if any(name.startswith('service_') for name in cases):
|
|
require(all(name in cases for name in ('service_setup', 'service_start', 'service_stop'))
|
|
and cases.index('service_setup') < cases.index('service_start') < cases.index('service_stop'),
|
|
'service_setup_start_stop_must_be_fixed_explicit_order')
|
|
require('reboot_last' not in cases or cases[-1] == 'reboot_last', 'reboot_must_be_last')
|
|
|
|
|
|
def safe_states(states):
|
|
require(isinstance(states, list) and all(state in TERMINAL for state in states), 'outstanding_or_unknown_jobs_block_execution')
|
|
|
|
|
|
def validate_apt_manifest(value):
|
|
"""Pure format verification, NEVER evidence that live planning/acceptance ran."""
|
|
fields = {'type', 'schema_version', 'action', 'execution_profile', 'transaction_sha256', 'resolved_apt_transaction',
|
|
'transaction_bytes', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256', 'test_result_id'}
|
|
require(set(value) == fields and value['type'] == 'rmm.apt.helper-action' and value['schema_version'] == 2
|
|
and value['action'] in ('apt-native-acceptance', 'apt-execute') and value['execution_profile'] == 'dev-test', 'apt_manifest_schema')
|
|
raw = value['transaction_bytes']
|
|
require(isinstance(raw, list) and len(raw) <= 65536 and all(type(n) is int and 0 <= n < 256 for n in raw), 'apt_exact_transaction_bytes')
|
|
raw = bytes(raw)
|
|
require(hashlib.sha256(raw).hexdigest() == value['transaction_sha256'], 'apt_transaction_hash')
|
|
transaction = json.loads(raw, object_pairs_hook=strict_object)
|
|
require(transaction == value['resolved_apt_transaction'] and set(transaction) == {'schema_version', 'recipe_id', 'recipe_version', 'platform',
|
|
'resolver_config_version', 'no_reboot', 'status_fingerprint', 'baseline_sha256', 'packages'}, 'apt_full_typed_transaction')
|
|
require(type(transaction['schema_version']) is int and transaction['schema_version'] == 1 and transaction['recipe_version'] == '1' and transaction['platform'] == 'ubuntu-24.04-amd64'
|
|
and transaction['resolver_config_version'] == 'rmm-apt-local-v1' and transaction['no_reboot'] is True, 'apt_fixture_profile_no_reboot')
|
|
pins = {'rmm-apt-fixture-install-1.0': (None, '1.0', '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867'),
|
|
'rmm-apt-fixture-update-1.1': ('1.0', '1.1', 'ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491')}
|
|
require(transaction['recipe_id'] in pins and len(transaction['packages']) == 1, 'apt_fixed_single_package_recipe')
|
|
old, new, pin = pins[transaction['recipe_id']]
|
|
package = transaction['packages'][0]
|
|
require(package == dict(name='rmm-mvp-test', architecture='all', old_version=old, new_version=new, origin='rmm-test',
|
|
sha256=pin, size=20672, archive_path='/var/lib/rmm-apt-transaction/archives/' + pin + '.deb'), 'apt_pinned_fixture_archive')
|
|
for digest in [value[name] for name in ('provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256')] + [transaction['status_fingerprint'], transaction['baseline_sha256']]:
|
|
require(isinstance(digest, str) and re.fullmatch('[a-f0-9]{64}', digest), 'apt_full_measurement_pin_required')
|
|
require(isinstance(value['test_result_id'], str) and re.fullmatch('[A-Za-z0-9_.-]{1,128}', value['test_result_id']), 'apt_test_result_binding')
|
|
return transaction
|
|
|
|
|
|
def validate_reboot_checkpoint(checkpoint, new_boot, final_job):
|
|
# Pure verifier only: reboot/reconnect driver intentionally not invented.
|
|
require(set(checkpoint) == {'tenant_id', 'agent_id', 'asset_id', 'operation_id', 'job_id', 'attempt_id', 'plan_hash', 'old_boot_id'}, 'reboot_checkpoint_fields')
|
|
for field in set(checkpoint)-{'plan_hash'}:
|
|
uuid.UUID(checkpoint[field])
|
|
require(re.fullmatch('[a-f0-9]{64}', checkpoint['plan_hash']) and new_boot != checkpoint['old_boot_id'], 'real_new_boot_required')
|
|
uuid.UUID(new_boot)
|
|
require(final_job.get('job_id') == checkpoint['job_id'] and final_job.get('attempt_id') == checkpoint['attempt_id']
|
|
and final_job.get('state') == 'succeeded' and final_job.get('result', {}).get('evidence', {}).get('new_boot_id') == new_boot,
|
|
'authenticated_bound_reboot_result_required')
|
|
|
|
|
|
class Backend:
|
|
def __init__(self):
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from backend_contract import request
|
|
from local_integration import sql
|
|
self.request, self.sql = request, sql
|
|
self.token = (STATE / 'operator-a.token').read_text().strip()
|
|
self.headers = {'Accept': 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-11-25'}
|
|
self.sequence = 1
|
|
# Standard verified CA and DNS name, no custom trust or invalid-cert flag.
|
|
ssl.create_default_context(cafile=str(CA))
|
|
init = dict(jsonrpc='2.0', id=1, method='initialize', params=dict(protocolVersion='2025-11-25', capabilities={}, clientInfo=dict(name='vm-mvp-readiness', version='1')))
|
|
status, headers, response = self.request('/mcp', 'POST', init, self.token, self.headers)
|
|
require(status == 200 and response['result']['protocolVersion'] == '2025-11-25', 'mcp_initialize_failed')
|
|
session = next((value for key, value in headers.items() if key.lower() == 'mcp-session-id'), None)
|
|
require(session, 'mcp_session_missing')
|
|
self.headers['Mcp-Session-Id'] = session
|
|
require(self.request('/mcp', 'POST', dict(jsonrpc='2.0', method='notifications/initialized'), self.token, self.headers)[0] == 202, 'mcp_initialized_failed')
|
|
|
|
def call(self, name, arguments):
|
|
require(name in ('tenants.list', 'inventory.list_devices', 'inventory.get_device', 'monitoring.get_health', 'operations.plan', 'operations.submit', 'jobs.get', 'jobs.cancel'), 'mcp_tool_not_allowlisted')
|
|
self.sequence += 1
|
|
status, _, response = self.request('/mcp', 'POST', dict(jsonrpc='2.0', id=self.sequence, method='tools/call', params=dict(name=name, arguments=arguments)), self.token, self.headers)
|
|
require(status == 200 and 'result' in response and not response['result'].get('isError'), 'mcp_tool_failed')
|
|
return response['result']['structuredContent']
|
|
|
|
def counts(self, tenant, job):
|
|
uuid.UUID(tenant); uuid.UUID(job)
|
|
return json.loads(self.sql(f"SELECT json_build_array((SELECT count(*) FROM jobs WHERE tenant_id='{tenant}' AND job_id='{job}'),(SELECT count(*) FROM outbox WHERE tenant_id='{tenant}' AND job_id='{job}'),(SELECT count(*) FROM execution_permits WHERE tenant_id='{tenant}' AND job_id='{job}'));"))
|
|
|
|
def outstanding_guard(self, settings):
|
|
agent = str(uuid.UUID(settings['agent_id']))
|
|
safe_states(json.loads(self.sql(f"SELECT coalesce(json_agg(state),'[]'::json) FROM jobs WHERE agent_id='{agent}';")))
|
|
|
|
|
|
def preflight(backend, settings):
|
|
status, _, auth = backend.request('/auth/config')
|
|
require(status == 200 and auth.get('dev_login_enabled') is True, 'actual_dev_test_login_profile_required')
|
|
tenants = backend.call('tenants.list', {})
|
|
require(any(x['tenant_id'] == settings['tenant_id'] for x in tenants['items']), 'tenant_not_visible')
|
|
devices = backend.call('inventory.list_devices', dict(tenant_id=settings['tenant_id']))
|
|
# Detail lookup remains authoritative even if a bounded list is truncated.
|
|
device = backend.call('inventory.get_device', dict(tenant_id=settings['tenant_id'], asset_id=settings['asset_id']))
|
|
require(device['agent_id'] == settings['agent_id'] and device['asset_id'] == settings['asset_id'], 'stored_vm_identity_mismatch')
|
|
backend.call('monitoring.get_health', dict(tenant_id=settings['tenant_id']))
|
|
backend.outstanding_guard(settings)
|
|
from vm_mvp_adapters import planning_from_device, PLANNING_FIELDS
|
|
try:
|
|
planning_from_device(device);planning_status='stored_planning_valid_format_not_native_acceptance'
|
|
except GuardError as error:
|
|
planning_status=str(error)
|
|
return device, dict(mcp_readonly_smoke=True, fixed_vm_resolved=True, list_truncated=devices['truncated'],
|
|
presence=device['presence'], capabilities=device['capabilities'],
|
|
executable_adapters=list(EXECUTABLE), adapter_status={name: ('unsupported_native_fault_injection_safe_replay_available' if name in ('duplicate_offer','lost_result_ack') else 'ready_adapter_runtime_not_configured') for name in EXECUTABLE},
|
|
apt_planning_status=planning_status, required_stored_planning_fields=list(PLANNING_FIELDS),
|
|
certificate_API_fingerprint_available=isinstance(device.get('certificate_sha256'),str), effects_performed=False)
|
|
|
|
|
|
def execute_case(backend, settings, artifact, name, folder, runtime=None):
|
|
if name in ADVANCED or name in ('service_setup','service_start','service_stop'):
|
|
from vm_mvp_adapters import execute_advanced
|
|
return execute_advanced(backend, settings, artifact, name, folder, runtime)
|
|
backend.outstanding_guard(settings)
|
|
device = backend.call('inventory.get_device', dict(tenant_id=settings['tenant_id'], asset_id=settings['asset_id']))
|
|
require(device['presence'] == 'online' and 0 <= (now()-timestamp(device['last_contact_at'])).total_seconds() < 90, 'fresh_live_agent_required')
|
|
plan_input = case_input(name, settings)
|
|
if runtime is not None: runtime.require_action(plan_input)
|
|
required = {plan_input['action'], 'rmm.sync.v1'}
|
|
if plan_input['parameters']['execution_identity'] == 'root':
|
|
required |= {'helper.root.v1', 'root:' + plan_input['action']}
|
|
require(any(re.fullmatch('helper.policy.sha256:[a-f0-9]{64}', c) for c in device['capabilities']), 'helper_policy_digest_missing')
|
|
require(required <= set(device['capabilities']), 'actual_negotiated_capability_missing')
|
|
plan = backend.call('operations.plan', dict(tenant_id=settings['tenant_id'], input=plan_input))
|
|
require(hashlib.sha256(bytes(plan['plan_payload_bytes'])).hexdigest() == plan['plan_hash'] and len(plan['jobs']) == 1, 'stored_plan_hash_or_target_count')
|
|
job = plan['jobs'][0]
|
|
require(job['agent_id'] == settings['agent_id'] and job['asset_id'] == settings['asset_id'], 'plan_target_changed')
|
|
expected = dict(profile='dev/test', case=name, tenant_id=settings['tenant_id'], agent_id=settings['agent_id'], asset_id=settings['asset_id'],
|
|
plan_hash=plan['plan_hash'], plan_payload_bytes=plan['plan_payload_bytes'], job_payload=job['payload'], job_payload_hash=job['job_payload_hash'],
|
|
expected_principal=artifact['expected_principal'])
|
|
pending = backend.call('operations.submit', dict(tenant_id=settings['tenant_id'], plan_id=plan['plan_id'], idempotency_key='mvp-' + uuid.uuid4().hex))
|
|
require(pending['approval_state'] == 'pending_approval' and pending['job_count'] == 0 and pending['execution_state'] is None
|
|
and backend.counts(settings['tenant_id'], job['job_id']) == [0, 0, 0], 'preapproval_artifact_invariant')
|
|
expected['operation_id'] = str(uuid.UUID(pending['operation_id']))
|
|
checkpoint = folder / (name + '-checkpoint.json')
|
|
write_private(checkpoint, dict(plan_id=plan['plan_id'], operation_id=expected['operation_id'], job_id=job['job_id'], attempt_id=job['attempt_id'],
|
|
plan_hash=plan['plan_hash'], state='pending_approval', no_retry=True))
|
|
expected_file = folder / (name + '-browser.json'); write_private(expected_file, expected)
|
|
process = subprocess.run([sys.executable, str(ROOT / 'deploy/browser/run_mvp_actions.py'), '--case-file', str(expected_file), '--dev-test-ui-approve'], timeout=120)
|
|
require(process.returncode == 0, 'browser_not_confirmed_preserve_checkpoint_do_not_retry')
|
|
deadline = time.monotonic() + plan_input['parameters']['timeout_seconds'] + 45
|
|
while True:
|
|
result = backend.call('jobs.get', dict(tenant_id=settings['tenant_id'], job_id=job['job_id']))
|
|
if result['state'] in TERMINAL or result['state'] in ('unknown', 'awaiting_reboot'):
|
|
break
|
|
require(time.monotonic() < deadline, 'result_timeout_unknown_no_retry')
|
|
time.sleep(2)
|
|
evidence = result.get('result', {}).get('evidence', {})
|
|
require(result['state'] == 'succeeded' and evidence.get('postconditions_passed') is True, 'job_not_verified_no_retry')
|
|
if name in ('hello', 'service_setup'):
|
|
expected_output = b'Hello World\n' if name == 'hello' else b'RMM test unit prepared\n'
|
|
require(result['result']['exit_code'] == 0 and bytes(result['result']['stdout']) == expected_output, 'exact_script_output')
|
|
if name == 'refresh_inventory':
|
|
require(timestamp(evidence['observed_at']) >= timestamp(plan_input['schedule']['not_before']), 'inventory_not_new')
|
|
if name == 'query_logs':
|
|
require(evidence.get('quality') == 'valid' and len(result['result']['stdout'])+len(result['result']['stderr']) <= 65536, 'bounded_valid_log_evidence_required')
|
|
require(backend.counts(settings['tenant_id'], job['job_id']) == [1, 1, 1], 'exactly_one_job_outbox_grant_required')
|
|
operation = expected['operation_id']
|
|
audit = json.loads(backend.sql(f"SELECT json_build_object('origin',approval_origin,'simulation',testsimulation,'principal',principal,'plan_hash',plan_hash) FROM authorizations WHERE tenant_id='{settings['tenant_id']}' AND operation_id='{operation}';"))
|
|
require(audit == dict(origin='dev_test_browser_simulation', simulation=True, principal=artifact['expected_principal'], plan_hash=plan['plan_hash']), 'simulated_approval_audit_mismatch')
|
|
write_private(folder / (name + '-result.json'), dict(case=name, verified=True, job_id=job['job_id'], attempt_id=job['attempt_id'],
|
|
operation_id=operation, plan_hash=plan['plan_hash'], audit=audit, output_not_published=True))
|
|
|
|
|
|
def main():
|
|
os.umask(0o077)
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--config', type=Path)
|
|
parser.add_argument('--run-realtime-dev-ui-acceptance', action='store_true')
|
|
parser.add_argument('--user-artifact', type=Path)
|
|
parser.add_argument('--create-chat-user-artifact', type=Path)
|
|
parser.add_argument('--wire-verdict', type=Path)
|
|
parser.add_argument('--transport', choices=('wss','https'), default='wss')
|
|
parser.add_argument('--exercise-server-restart', action='store_true')
|
|
parser.add_argument('--exercise-native-renewal', action='store_true')
|
|
parser.add_argument('--case', action='append', choices=tuple(EXECUTABLE)+tuple(PENDING), default=[])
|
|
args = parser.parse_args()
|
|
settings = config(protected_json(args.config)) if args.config else default_config()
|
|
require(settings == default_config(), 'only_preserved_linux_vm_configuration_allowed')
|
|
if args.create_chat_user_artifact:
|
|
require(not args.run_realtime_dev_ui_acceptance and not args.case, 'artifact_creation_is_not_execution')
|
|
path=args.create_chat_user_artifact
|
|
path.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
|
|
require(path.parent.stat().st_mode & 0o777 == 0o700 and STATE in path.resolve().parents, 'private_devstate_artifact_directory_required')
|
|
write_private(path, dict(profile='dev/test', **{key:settings[key] for key in ('tenant_id','asset_id','agent_id')},
|
|
approved_cases=list(EXECUTABLE), expires_at=(now()+dt.timedelta(hours=1)).isoformat(),
|
|
permission_origin='explicit_chat_user_permission',chat_date='2026-11-12',testsimulation=True,
|
|
expected_principal='simulated-testprincipal-a'))
|
|
print('CHAT_PERMISSION_RECORDED: no readiness/proof/capability flags, no VM action')
|
|
return
|
|
artifact = None
|
|
if args.run_realtime_dev_ui_acceptance:
|
|
require(args.user_artifact is not None, 'protected_explicit_user_artifact_required')
|
|
artifact = protected_json(args.user_artifact)
|
|
validate_run_artifact(artifact, settings, args.case)
|
|
else:
|
|
require(not args.case and args.user_artifact is None and not args.exercise_server_restart and not args.exercise_native_renewal, 'case_selection_requires_explicit_run_flag')
|
|
backend = Backend()
|
|
_, report = preflight(backend, settings)
|
|
print(json.dumps(report, indent=2))
|
|
if artifact is not None:
|
|
require(args.wire_verdict is not None, 'current_wire_worker_verdict_required_before_any_native_effect')
|
|
from vm_mvp_runtime import OwnedRuntime
|
|
runtime = OwnedRuntime(settings,backend,protected_json(args.wire_verdict))
|
|
folder = STATE / ('mvp-acceptance-' + uuid.uuid4().hex)
|
|
folder.mkdir(mode=0o700)
|
|
try:
|
|
runtime.acquire(args.transport)
|
|
if args.exercise_server_restart: runtime.restart_server()
|
|
if args.exercise_native_renewal: runtime.native_renewal()
|
|
for name in args.case:
|
|
execute_case(backend, settings, artifact, name, folder, runtime)
|
|
finally:
|
|
runtime.release_if_idle()
|
|
print('SELECTED_CASES_COMPLETED: inspect individual verified/unsupported fault statuses; no full-MVP claim')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception as error:
|
|
# No raw SDK/HTTP/browser/log errors, payloads, argv or credential values.
|
|
print('ACCEPTANCE_INCOMPLETE:' + (str(error) if isinstance(error, GuardError) else type(error).__name__))
|
|
raise SystemExit(2) from None
|