"""Agent phase permits only this run's model gateway IP and TCP port.""" import contextlib from dataclasses import replace import ipaddress import json import os from pathlib import Path import textwrap from harbor.models.task.config import NetworkPolicy from harbor.trial.trial import Trial def install_policy(): host = str(ipaddress.IPv4Address(os.environ['BENCH_GATEWAY_HOST'])) port = int(os.environ['COLLECTION_RELAY_PORT']) if not 1 <= port <= 65535: raise ValueError('Invalid model gateway port') original_plan = Trial._network_plan original_phase = Trial._phase_network_policy def network_plan(self, *args, **kwargs): return replace(original_plan(self, *args, **kwargs), agent_phase=NetworkPolicy(network_mode='allowlist', allowed_hosts=[host])) @contextlib.asynccontextmanager async def network_phase(self, environment, *, baseline_policy, phase_policy): async with original_phase(self, environment, baseline_policy=baseline_policy, phase_policy=phase_policy): controlled = phase_policy.network_mode.value == 'allowlist' if controlled: assert phase_policy.allowed_hosts == [host] rules = textwrap.dedent('''\ set -e nft -f - <<'NFT' add table inet benchmark_isolation add chain inet benchmark_isolation output { type filter hook output priority 10; policy drop; } add rule inet benchmark_isolation output udp dport 53 drop add rule inet benchmark_isolation output tcp dport 53 drop add rule inet benchmark_isolation output oifname "lo" accept insert rule inet gost_egress output ip daddr GATEWAY_HOST tcp dport GATEWAY_PORT return add rule inet benchmark_isolation output ip daddr GATEWAY_HOST tcp dport GATEWAY_PORT accept add table netdev benchmark_isolation_l2 add chain netdev benchmark_isolation_l2 output { type filter hook egress device "eth0" priority 10; policy drop; } add rule netdev benchmark_isolation_l2 output ether type arp accept add rule netdev benchmark_isolation_l2 output ether type ip ip daddr GATEWAY_HOST ip protocol tcp tcp dport GATEWAY_PORT accept add rule netdev benchmark_isolation_l2 output counter drop NFT nft list table inet benchmark_isolation nft list table netdev benchmark_isolation_l2 ''').replace('GATEWAY_HOST', host).replace('GATEWAY_PORT', str(port)) result = await environment.service_exec(service=environment._EGRESS_CONTROL_SERVICE_NAME, command=rules, user='root', timeout_sec=20) audit = Path(os.environ['BENCH_OUTPUT']) / 'network_audits' audit.mkdir(exist_ok=True) (audit / (self.config.trial_name + '.json')).write_text(json.dumps({ 'policy': phase_policy.model_dump(mode='json'), 'rules': result.stdout, 'stderr': result.stderr, 'return_code': result.return_code})) if result.return_code: raise RuntimeError('Cannot enforce agent isolation: ' + str(result.stdout) + '\n' + str(result.stderr)) try: yield finally: if controlled: result = await environment.service_exec(service=environment._EGRESS_CONTROL_SERVICE_NAME, command='nft delete table inet benchmark_isolation; nft delete table netdev benchmark_isolation_l2', user='root', timeout_sec=20) if result.return_code: raise RuntimeError('Cannot remove agent phase firewall') Trial._network_plan = network_plan Trial._phase_network_policy = network_phase