Files

94 lines
4.7 KiB
Python

"""Real local-only gateway, gVisor, persistence and network isolation checks."""
import json
import os
import pathlib
import subprocess
import time
import urllib.error
import urllib.request
import uuid
if os.environ.get('WSL_DISTRO_NAME') != 'WebUp-Local':
raise SystemExit('Run inside WebUp-Local.')
values = dict(line.strip().split('=', 1) for line in open('/etc/webup-local/gateway.env') if '=' in line)
report = {'checks': [], 'passed': False}
def check(condition, name):
if not condition:
raise RuntimeError('Local isolation check failed: ' + name)
report['checks'].append(name)
print('PASS ' + name, flush=True)
def api(path, payload=None, authenticated=True):
headers = {'Content-Type': 'application/json'}
if authenticated:
headers['Authorization'] = 'Bearer ' + values['SANDBOX_TOKEN']
request = urllib.request.Request('http://127.0.0.1:8090' + path, data=None if payload is None else json.dumps(payload).encode(), headers=headers)
with urllib.request.urlopen(request, timeout=145) as response:
return json.load(response)
def kubectl(*args):
return subprocess.check_output(['k3s', 'kubectl', *args], text=True, timeout=60)
project = str(uuid.uuid4())
pod_name = 'dev-' + uuid.UUID(project).hex
try:
try:
api('/health/ready', authenticated=False)
raise RuntimeError('Unauthenticated gateway request was accepted')
except urllib.error.HTTPError as error:
check(error.code == 401, 'gateway rejects unauthenticated requests')
check(api('/health/ready').get('ready'), 'gateway performs actual Kubernetes health query')
path = '/workspaces/' + project + '/tools'
def tool(name, arguments):
return api(path, {'name': name, 'arguments': arguments})
check(tool('write_file', {'path': 'smoke/hello.txt', 'content': 'WebUp local isolated workspace'}).get('written') is not None, 'workspace provisions real PVC and writes file')
check(tool('read_file', {'path': 'smoke/hello.txt'}).get('content') == 'WebUp local isolated workspace', 'workspace file roundtrip')
check('error' in tool('write_file', {'path': '../outside.txt', 'content': 'denied'}), 'file tool rejects parent traversal')
command = '''python3 - <<'PY'
import os,pathlib,socket,json
assert os.getuid()==10001
assert not pathlib.Path('/var/run/secrets/kubernetes.io/serviceaccount/token').exists()
assert not any(k in os.environ for k in ('SANDBOX_TOKEN','RUNTIME_TOKEN','APP_ENCRYPTION_KEY'))
try:
pathlib.Path('/webup-forbidden-write').write_text('denied')
except OSError:
pass
else:
raise AssertionError('Root filesystem was writable')
for host in ('169.254.169.254','10.43.0.1'):
try:
socket.create_connection((host,443),timeout=3).close()
except OSError:
pass
else:
raise AssertionError('Private network reachable: '+host)
socket.create_connection(('example.com',443),timeout=10).close()
print(json.dumps({'uid':os.getuid(),'privateBlocked':True,'publicHttpsReachable':True}))
PY'''
result = tool('run_command', {'command': command})
check(result.get('exitCode') == 0 and not result.get('timedOut'), 'non-root execution, no credentials, read-only root, blocked private network and working public HTTPS')
pod = json.loads(kubectl('-n', 'platform-sandboxes', 'get', 'pod', pod_name, '-o', 'json'))
check(pod['spec']['runtimeClassName'] == 'gvisor', 'workspace requests isolated RuntimeClass')
container = pod['status']['containerStatuses'][0]['containerID'].split('://', 1)[1]
runtime = json.loads(subprocess.check_output(['k3s', 'ctr', '--namespace', 'k8s.io', 'containers', 'info', container], text=True, timeout=20))
actual = runtime.get('Runtime', runtime.get('runtime', {}))
check(actual.get('Name', actual.get('name')) == 'io.containerd.runsc.v1', 'running container actually uses gVisor shim rather than runc')
configuration = json.loads(kubectl('get', '--raw', '/api/v1/nodes/webup-local/proxy/configz'))
check(configuration['kubeletconfig']['podPidsLimit'] == 512, 'kubelet enforces a finite per-pod process limit')
kubectl('-n', 'platform-sandboxes', 'delete', 'pod', pod_name, '--wait=true', '--timeout=45s')
check(tool('read_file', {'path': 'smoke/hello.txt'}).get('content') == 'WebUp local isolated workspace', 'PVC survives workspace pod recreation')
report['passed'] = True
finally:
report['projectId'] = project
report['pod'] = pod_name
report['checkedAtUnix'] = time.time()
target = pathlib.Path('/etc/webup-local/smoke-report.json')
target.write_text(json.dumps(report, indent=2))
host_report = pathlib.Path(__file__).resolve().parents[2] / '.runtime/local-cluster/smoke-report.json'
host_report.write_text(json.dumps(report, indent=2))