@tnunamak/dalan 0.0.0-stage → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Trusted source producer and namespace-init supervisor for one resource envelope."""
|
|
3
|
+
import ctypes
|
|
4
|
+
import hashlib
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import selectors
|
|
9
|
+
import signal
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tarfile
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def send(value):
|
|
18
|
+
print(json.dumps(value, separators=(',', ':')), flush=True)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if sys.argv[1] != '--inside':
|
|
22
|
+
if sys.version_info < (3, 12):
|
|
23
|
+
raise RuntimeError('Python 3.12+ with safe tar extraction required')
|
|
24
|
+
config = json.loads(sys.argv[1])
|
|
25
|
+
node = config['node']
|
|
26
|
+
npm = os.path.abspath(os.path.join(os.path.dirname(node), '../lib/node_modules/npm'))
|
|
27
|
+
read_fd, write_fd = os.pipe()
|
|
28
|
+
config_fd=os.memfd_create('dot-host-config')
|
|
29
|
+
guest_config = dict(config)
|
|
30
|
+
if config['dependencies']:
|
|
31
|
+
guest_config['dependencies'] = {key: value for key, value in config['dependencies'].items() if key != 'treePath'}
|
|
32
|
+
os.write(config_fd,json.dumps(guest_config).encode())
|
|
33
|
+
os.lseek(config_fd,0,0)
|
|
34
|
+
extra_fds=[config_fd]
|
|
35
|
+
# No source tree is bound into the guest: masked originals cannot be reached
|
|
36
|
+
# via an alternate /input path. Archive data is streamed, never buffered whole.
|
|
37
|
+
binds = [part for name in ['/usr', '/lib', '/lib64', '/etc/alternatives'] if os.path.exists(name) for part in ['--ro-bind', name, name]]
|
|
38
|
+
command = ['/usr/bin/bwrap', '--unshare-user', '--unshare-pid', '--unshare-net', '--unshare-ipc', '--unshare-uts', '--unshare-cgroup',
|
|
39
|
+
'--disable-userns', '--as-pid-1', '--die-with-parent', '--new-session', *binds,
|
|
40
|
+
'--symlink', 'usr/bin', '/bin', '--ro-bind', node, '/runtime/node',
|
|
41
|
+
'--ro-bind', os.path.abspath(__file__), '/supervisor.py', '--ro-bind-data', str(config_fd), '/config.json',
|
|
42
|
+
'--ro-bind', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'host-budget-seccomp.py'), '/host-budget-seccomp.py',
|
|
43
|
+
'--ro-bind', sys.argv[2], '/cgroup', '--size', str(config['budgets']['disk_write_bytes']), '--tmpfs', '/budget',
|
|
44
|
+
'--dir', '/budget/workspace', '--dir', '/budget/tmp', '--dir', '/budget/home/.tmp', '--dir', '/budget/cache', '--dir', '/budget/bin',
|
|
45
|
+
'--symlink', '/budget/workspace', '/workspace', '--symlink', '/budget/tmp', '/tmp', '--symlink', '/budget/cache', '/cache',
|
|
46
|
+
'--dir', '/home', '--symlink', '/budget/home', '/home/worker']
|
|
47
|
+
if os.path.isdir(npm):
|
|
48
|
+
command += ['--ro-bind', npm, '/runtime/npm']
|
|
49
|
+
if config['dependencies']:
|
|
50
|
+
command += ['--ro-bind', config['dependencies']['treePath'], '/budget/workspace/node_modules']
|
|
51
|
+
# Empty sensitive files and host-approved source overlays stay read-only.
|
|
52
|
+
for name in config['maskPaths']:
|
|
53
|
+
empty=os.memfd_create('dot-host-mask')
|
|
54
|
+
extra_fds.append(empty)
|
|
55
|
+
command += ['--ro-bind-data', str(empty), '/budget/workspace/' + name]
|
|
56
|
+
# The namespace has only `lo`, but the NAME localhost needs files too. Bridge-generated, host-data-free and read-only:
|
|
57
|
+
# public names still fail at once because there is no resolver and no route.
|
|
58
|
+
for target, body in (('/etc/hosts', b'127.0.0.1 localhost\n::1 localhost\n'), ('/etc/nsswitch.conf', b'hosts: files\n')):
|
|
59
|
+
name_fd=os.memfd_create('dot-host-name')
|
|
60
|
+
os.write(name_fd,body)
|
|
61
|
+
os.lseek(name_fd,0,0)
|
|
62
|
+
extra_fds.append(name_fd)
|
|
63
|
+
command += ['--ro-bind-data', str(name_fd), target]
|
|
64
|
+
for entry in config['sourceExemptions']:
|
|
65
|
+
command += ['--ro-bind', entry['hostPath'], '/budget/workspace/' + entry['path']]
|
|
66
|
+
# No devpts allocator: checks are non-interactive and must not consume the
|
|
67
|
+
# host's global PTY pool. Shared-memory files use the same bounded tmpfs.
|
|
68
|
+
command += ['--dir', '/dev']
|
|
69
|
+
for device in ['null', 'zero', 'full', 'random', 'urandom']:
|
|
70
|
+
command += ['--dev-bind', '/dev/' + device, '/dev/' + device]
|
|
71
|
+
command += ['--symlink', '/proc/self/fd', '/dev/fd', '--symlink', '/proc/self/fd/0', '/dev/stdin',
|
|
72
|
+
'--symlink', '/proc/self/fd/1', '/dev/stdout', '--symlink', '/proc/self/fd/2', '/dev/stderr',
|
|
73
|
+
'--symlink', '/budget/tmp', '/dev/shm',
|
|
74
|
+
'--proc', '/proc', '--remount-ro', '/proc', '--remount-ro', '/', '--clearenv',
|
|
75
|
+
'--setenv', 'PATH', '/budget/bin:/runtime:/usr/bin:/bin', '--setenv', 'HOME', '/home/worker', '--setenv', 'TMPDIR', '/tmp',
|
|
76
|
+
'--setenv', 'XDG_CACHE_HOME', '/cache/xdg', '--setenv', 'npm_config_cache', '/cache/npm', '--setenv', 'UV_CACHE_DIR', '/cache/uv',
|
|
77
|
+
'--setenv', 'CARGO_HOME', '/cache/cargo', '--setenv', 'GOPATH', '/cache/go', '--setenv', 'GOMODCACHE', '/cache/go/pkg/mod',
|
|
78
|
+
'--', '/usr/bin/python3', '/supervisor.py', '--inside', str(read_fd)]
|
|
79
|
+
child = subprocess.Popen(command, pass_fds=[read_fd,*extra_fds], stdin=sys.stdin)
|
|
80
|
+
os.close(read_fd)
|
|
81
|
+
for descriptor in extra_fds:
|
|
82
|
+
os.close(descriptor)
|
|
83
|
+
excluded = set(config['maskPaths']) | {e['path'] for e in config['sourceExemptions']}
|
|
84
|
+
|
|
85
|
+
def include(info):
|
|
86
|
+
name = info.name.removeprefix('./').rstrip('/')
|
|
87
|
+
if '.git' in name.split('/') or 'node_modules' in name.split('/') or name in excluded:
|
|
88
|
+
return None
|
|
89
|
+
if not (info.isfile() or info.isdir() or info.issym()):
|
|
90
|
+
raise ValueError('unsupported source file type: ' + name)
|
|
91
|
+
return info
|
|
92
|
+
|
|
93
|
+
def produce():
|
|
94
|
+
try:
|
|
95
|
+
with os.fdopen(write_fd, 'wb') as output:
|
|
96
|
+
with tarfile.open(fileobj=output, mode='w|', dereference=False) as archive:
|
|
97
|
+
archive.add(config['dir'], arcname='.', filter=include)
|
|
98
|
+
except (BrokenPipeError, OSError):
|
|
99
|
+
pass # The guest may already have hit memory/storage/time admission.
|
|
100
|
+
|
|
101
|
+
producer = threading.Thread(target=produce, daemon=True)
|
|
102
|
+
producer.start()
|
|
103
|
+
sys.exit(child.wait())
|
|
104
|
+
|
|
105
|
+
# Namespace PID 1 cannot be signalled by descendants without installed handlers.
|
|
106
|
+
# Non-dumpable state also denies /proc/1/fd access and ptrace of the receipt pipe.
|
|
107
|
+
if os.getpid() != 1 or ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) != 0:
|
|
108
|
+
raise RuntimeError('protected namespace-init supervisor required')
|
|
109
|
+
with open('/config.json', encoding='utf-8') as stream:
|
|
110
|
+
config = json.load(stream)
|
|
111
|
+
budgets = config['budgets']
|
|
112
|
+
started = time.monotonic()
|
|
113
|
+
error = None
|
|
114
|
+
output_total = 0
|
|
115
|
+
results = []
|
|
116
|
+
cancelled = False
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def fields(name):
|
|
120
|
+
with open('/cgroup/' + name, encoding='utf-8') as stream:
|
|
121
|
+
return {parts[0]: int(parts[1]) for line in stream if len(parts := line.split()) == 2}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def usage():
|
|
125
|
+
capacity = os.statvfs('/budget')
|
|
126
|
+
return {'cpu_ms': fields('cpu.stat')['usage_usec'] / 1000,
|
|
127
|
+
'memory_bytes': int(open('/cgroup/memory.peak').read()),
|
|
128
|
+
'processes': int(open('/cgroup/pids.peak').read()),
|
|
129
|
+
'disk_write_bytes': (capacity.f_blocks - capacity.f_bfree) * capacity.f_frsize,
|
|
130
|
+
'output_bytes': output_total}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def inspect():
|
|
134
|
+
global error
|
|
135
|
+
used = usage()
|
|
136
|
+
which = ('disk_write' if used['disk_write_bytes'] >= budgets['disk_write_bytes'] else
|
|
137
|
+
'memory' if fields('memory.events').get('max', 0) else
|
|
138
|
+
'processes' if fields('pids.events').get('max', 0) else
|
|
139
|
+
'cpu' if used['cpu_ms'] >= budgets['cpu_ms'] else None)
|
|
140
|
+
if which and error is None:
|
|
141
|
+
error = 'budget exceeded: ' + which
|
|
142
|
+
return used
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def stop_descendants():
|
|
146
|
+
# /proc is this new PID namespace, whose only trusted member is PID 1.
|
|
147
|
+
# Signal only these job PIDs, never a host process group or shared service.
|
|
148
|
+
for entry in os.listdir('/proc'):
|
|
149
|
+
if entry.isdecimal() and int(entry) != 1:
|
|
150
|
+
try:
|
|
151
|
+
os.kill(int(entry), signal.SIGKILL)
|
|
152
|
+
except ProcessLookupError:
|
|
153
|
+
pass
|
|
154
|
+
while True:
|
|
155
|
+
try:
|
|
156
|
+
os.waitpid(-1, 0)
|
|
157
|
+
except ChildProcessError:
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
with os.fdopen(int(sys.argv[2]), 'rb') as source:
|
|
163
|
+
with tarfile.open(fileobj=source, mode='r|') as archive:
|
|
164
|
+
archive.extractall('/workspace', filter='data')
|
|
165
|
+
dependencies = config['dependencies']
|
|
166
|
+
if dependencies:
|
|
167
|
+
for name, key in [('package-lock.json', 'lock_sha256'), ('package.json', 'manifest_sha256')]:
|
|
168
|
+
with open('/workspace/' + name, 'rb') as stream:
|
|
169
|
+
if hashlib.sha256(stream.read()).hexdigest() != dependencies[key]:
|
|
170
|
+
raise ValueError('dependencies_invalid: copied dependency inputs changed')
|
|
171
|
+
elif os.path.lexists('/workspace/package-lock.json'):
|
|
172
|
+
raise ValueError('dependencies_invalid: copied lock appeared after admission')
|
|
173
|
+
for name in ['npm', 'npx']:
|
|
174
|
+
file = '/budget/bin/' + name
|
|
175
|
+
with open(file, 'w') as stream:
|
|
176
|
+
stream.write('#!/bin/sh\nexec /runtime/node /runtime/npm/bin/' + name + '-cli.js "$@"\n')
|
|
177
|
+
os.chmod(file, 0o755)
|
|
178
|
+
with open('/budget/bin/systemctl', 'w') as stream:
|
|
179
|
+
stream.write('#!/bin/sh\n[ "$1" = "--user" ] && [ "$2" = "list-units" ]\n')
|
|
180
|
+
os.chmod('/budget/bin/systemctl', 0o755)
|
|
181
|
+
import importlib.util
|
|
182
|
+
seccomp_spec = importlib.util.spec_from_file_location('host_budget_seccomp', '/host-budget-seccomp.py')
|
|
183
|
+
seccomp = importlib.util.module_from_spec(seccomp_spec)
|
|
184
|
+
seccomp_spec.loader.exec_module(seccomp)
|
|
185
|
+
seccomp.install()
|
|
186
|
+
for phase in config['phases']:
|
|
187
|
+
inspect()
|
|
188
|
+
if error:
|
|
189
|
+
break
|
|
190
|
+
begin = time.monotonic()
|
|
191
|
+
chunks = bytearray()
|
|
192
|
+
pending = bytearray()
|
|
193
|
+
last_report = time.monotonic()
|
|
194
|
+
child = subprocess.Popen(phase['argv'], cwd='/workspace', stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
|
|
195
|
+
send({'event': 'started', 'phase': phase['name']})
|
|
196
|
+
announced = False
|
|
197
|
+
selector = selectors.DefaultSelector()
|
|
198
|
+
selector.register(child.stdout, selectors.EVENT_READ, 'output')
|
|
199
|
+
selector.register(child.stderr, selectors.EVENT_READ, 'output')
|
|
200
|
+
selector.register(sys.stdin, selectors.EVENT_READ, 'control')
|
|
201
|
+
while child.poll() is None:
|
|
202
|
+
inspect()
|
|
203
|
+
for key, _ in selector.select(0.01):
|
|
204
|
+
chunk = os.read(key.fileobj.fileno(), 65536)
|
|
205
|
+
if key.data == 'control':
|
|
206
|
+
cancelled = bool(chunk)
|
|
207
|
+
error = error or ('cancelled' if chunk else 'supervisor interrupted')
|
|
208
|
+
selector.unregister(key.fileobj)
|
|
209
|
+
elif not chunk:
|
|
210
|
+
selector.unregister(key.fileobj)
|
|
211
|
+
else:
|
|
212
|
+
if not announced:
|
|
213
|
+
send({'event': 'output_started', 'phase': phase['name']})
|
|
214
|
+
announced = True
|
|
215
|
+
room = max(0, budgets['output_bytes'] - output_total)
|
|
216
|
+
chunks.extend(chunk[:room])
|
|
217
|
+
pending.extend(chunk[:room])
|
|
218
|
+
output_total += len(chunk)
|
|
219
|
+
if output_total > budgets['output_bytes']:
|
|
220
|
+
error = error or 'budget exceeded: output'
|
|
221
|
+
now = time.monotonic()
|
|
222
|
+
if now - last_report >= 0.1:
|
|
223
|
+
send({'event': 'partial', 'phase': phase['name'], 'output': base64.b64encode(pending).decode(), 'usage': usage()})
|
|
224
|
+
pending.clear()
|
|
225
|
+
last_report = now
|
|
226
|
+
if error:
|
|
227
|
+
break
|
|
228
|
+
# Kill/reap daemonized children before the next phase or final receipt.
|
|
229
|
+
code = child.poll()
|
|
230
|
+
stop_descendants()
|
|
231
|
+
for stream in [child.stdout, child.stderr]:
|
|
232
|
+
tail = stream.read(65536)
|
|
233
|
+
room = max(0, budgets['output_bytes'] - output_total)
|
|
234
|
+
chunks.extend(tail[:room])
|
|
235
|
+
pending.extend(tail[:room])
|
|
236
|
+
output_total += len(tail)
|
|
237
|
+
stream.close()
|
|
238
|
+
if output_total > budgets['output_bytes']:
|
|
239
|
+
error = error or 'budget exceeded: output'
|
|
240
|
+
if code is not None and code != 0:
|
|
241
|
+
note = b'\nHost check restriction: file watching is unavailable; seccomp denies inotify_init and inotify_init1 (EPERM).\n'
|
|
242
|
+
chunks.extend(note[:max(0, budgets['output_bytes'] - output_total)])
|
|
243
|
+
pending.extend(note[:max(0, budgets['output_bytes'] - output_total)])
|
|
244
|
+
selector.close()
|
|
245
|
+
inspect()
|
|
246
|
+
send({'event': 'partial', 'phase': phase['name'], 'output': base64.b64encode(pending).decode(), 'usage': usage()})
|
|
247
|
+
results.append({'name': phase['name'], 'exit': {'code': code if code is not None and code >= 0 else 125},
|
|
248
|
+
'output': base64.b64encode(chunks).decode(), 'duration_ms': round((time.monotonic() - begin) * 1000)})
|
|
249
|
+
if error or code != 0:
|
|
250
|
+
break
|
|
251
|
+
except OSError as problem:
|
|
252
|
+
error = 'budget exceeded: disk_write' if problem.errno == 28 else 'host preparation failed: ' + str(problem)
|
|
253
|
+
except Exception as problem:
|
|
254
|
+
error = 'host preparation failed: ' + str(problem)
|
|
255
|
+
stop_descendants()
|
|
256
|
+
used = inspect()
|
|
257
|
+
send({'event': 'result', 'result': {'error': error, 'cancelled': cancelled, 'exit': results[-1]['exit'] if results else {'code': 125},
|
|
258
|
+
'phases': results, 'usage': used, 'duration_ms': round((time.monotonic() - started) * 1000)}})
|
|
259
|
+
sys.exit(125 if error else 0)
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { readEnv } from './env.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import {resolvePreparedNodeModules} from './prepared-node-modules.mjs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {prepareHostReceipts,assertHostReceiptIsolation,readVerifiedHostStop} from './host-budget-receipts.mjs';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
|
|
9
|
+
// One active envelope per Unix user, shared by every bridge process. The systemd
|
|
10
|
+
// unit name is an atomic reservation; it disappears only after its tree stops.
|
|
11
|
+
export const HOST_UNIT = 'dot-bridge-host-check.service';
|
|
12
|
+
export const HOST_BUDGET_CEILINGS = Object.freeze({ cpu_ms: 120000, wall_ms: 180000, memory_bytes: 1024 ** 3, processes: 128, disk_write_bytes: 256 * 1024 ** 2, output_bytes: 1024 ** 2 });
|
|
13
|
+
const minima = { cpu_ms: 50, wall_ms: 100, memory_bytes: 128 * 1024 ** 2, processes: 16, disk_write_bytes: 1024 ** 2, output_bytes: 1024 };
|
|
14
|
+
const service = fileURLToPath(new URL('./host-budget-service.mjs', import.meta.url));
|
|
15
|
+
const stopRecorder = fileURLToPath(new URL('./host-budget-stop.mjs', import.meta.url));
|
|
16
|
+
const cgroupReader = fileURLToPath(new URL('./host-cgroup.mjs', import.meta.url));
|
|
17
|
+
const processSignaler = fileURLToPath(new URL('./signal-sandbox-processes.py', import.meta.url));
|
|
18
|
+
|
|
19
|
+
export function resolveHostStopEvidence(receipts, pipeStop) {
|
|
20
|
+
const evidence=receipts?readVerifiedHostStop({receiptDir:receipts.receiptDir,checkRunId:receipts.checkRunId}):pipeStop;
|
|
21
|
+
if(!evidence) return null;
|
|
22
|
+
return {...evidence,verified:evidence.verified===true&&Array.isArray(evidence.remaining_pids)&&evidence.remaining_pids.length===0};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function parseHostBudget(value) {
|
|
26
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 6) throw new Error('host_budget requires cpu_ms, wall_ms, memory_bytes, processes, disk_write_bytes, output_bytes');
|
|
27
|
+
const result = {};
|
|
28
|
+
for (const key of Object.keys(HOST_BUDGET_CEILINGS)) {
|
|
29
|
+
if (!Number.isSafeInteger(value[key]) || value[key] < minima[key] || value[key] > HOST_BUDGET_CEILINGS[key]) throw new Error(`invalid host_budget.${key}: expected ${minima[key]}..${HOST_BUDGET_CEILINGS[key]}`);
|
|
30
|
+
result[key] = value[key];
|
|
31
|
+
}
|
|
32
|
+
for(const key of ['memory_bytes','disk_write_bytes']) if(result[key]%4096!==0) throw new Error(`invalid host_budget.${key}: expected a multiple of 4096`);
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const propertyArg = value => '"' + value.replaceAll('%', '%%').replaceAll('\\', '\\\\').replaceAll('"', '\\"') + '"';
|
|
37
|
+
|
|
38
|
+
export const provesHostNotStarted = ({ spawnError, pid, stopped }) => !!(spawnError && !pid && !stopped);
|
|
39
|
+
|
|
40
|
+
export async function runHostBudget(options) {
|
|
41
|
+
let spawned=false;
|
|
42
|
+
try { return await runHostBudgetAttempt(options,()=>{spawned=true;}); }
|
|
43
|
+
catch(error) { if(spawned) error.hostInvoked=true;throw error; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sourceExemptions = [], checkRunId, receiptDir, cancelled = () => false, onStarted, onOutputStarted, enabled = readEnv('DALAN_HOST_CHECKS') === '1' }, onSpawned) {
|
|
47
|
+
if (!enabled) throw new Error('host_execution_disabled: set DALAN_HOST_CHECKS=1 to opt in');
|
|
48
|
+
if (process.platform !== 'linux') throw new Error(`host budget backend unavailable on ${process.platform}`);
|
|
49
|
+
budgets = parseHostBudget(budgets);
|
|
50
|
+
if (!Array.isArray(phases) || !phases.length || phases.length > 2 || phases.some(p => !['install', 'check'].includes(p.name) || !Array.isArray(p.argv) || !p.argv.length || p.argv.some(a => typeof a !== 'string' || a.includes('\0')))) throw new Error('invalid host phases');
|
|
51
|
+
const receipts=prepareHostReceipts({checkRunId,receiptDir});
|
|
52
|
+
const workingDir=fs.realpathSync(dir);
|
|
53
|
+
const dependencies=resolvePreparedNodeModules(workingDir);
|
|
54
|
+
const protectedPaths=['node_modules','package.json','package-lock.json'];
|
|
55
|
+
const overlaps=(a,b)=>a===b||a.startsWith(b+'/')||b.startsWith(a+'/');
|
|
56
|
+
for(const name of [...maskPaths,...sourceExemptions.map(entry=>entry.path)]) {
|
|
57
|
+
if(typeof name!=='string'||!name||path.posix.normalize(name)!==name||name.startsWith('/')||name==='..'||name.startsWith('../')||protectedPaths.some(p=>overlaps(name,p))) throw new Error('dependencies_invalid: overlay overlaps dependency inputs');
|
|
58
|
+
}
|
|
59
|
+
if(dependencies) for(const entry of sourceExemptions) {
|
|
60
|
+
const host=fs.realpathSync(entry.hostPath), tree=fs.realpathSync(dependencies.treePath);
|
|
61
|
+
if(host===tree||host.startsWith(tree+path.sep)||tree.startsWith(host+path.sep)) throw new Error('dependencies_invalid: overlay exposes dependency tree');
|
|
62
|
+
}
|
|
63
|
+
if(receipts) {
|
|
64
|
+
assertHostReceiptIsolation(receipts.receiptDir,[workingDir,'/usr','/lib','/lib64','/etc/alternatives',process.execPath,
|
|
65
|
+
path.resolve(path.dirname(process.execPath),'../lib/node_modules/npm'),service,stopRecorder,
|
|
66
|
+
cgroupReader,processSignaler,
|
|
67
|
+
fileURLToPath(new URL('./host-budget-storage.py',import.meta.url)),fileURLToPath(new URL('./host-budget-seccomp.py',import.meta.url)),
|
|
68
|
+
...sourceExemptions.map(entry=>entry.hostPath),...(dependencies?[dependencies.treePath]:[])]);
|
|
69
|
+
}
|
|
70
|
+
const config = { dir: workingDir, budgets, phases, maskPaths, sourceExemptions, dependencies, node: process.execPath, ...(receipts?{receipts}:{}) };
|
|
71
|
+
const serialized = JSON.stringify(config);
|
|
72
|
+
if (Buffer.byteLength(serialized) > 65536) throw new Error('host budget configuration exceeds 64 KiB');
|
|
73
|
+
const properties = [
|
|
74
|
+
'Type=exec', 'Nice=10', `MemoryMax=${budgets.memory_bytes}`, 'MemorySwapMax=0', `TasksMax=${budgets.processes}`,
|
|
75
|
+
'CPUQuota=100%', 'CPUQuotaPeriodSec=10ms', `RuntimeMaxSec=${budgets.wall_ms}ms`,
|
|
76
|
+
'KillMode=control-group', 'KillSignal=SIGKILL', 'TimeoutStopSec=1s', 'SendSIGKILL=yes', 'OOMPolicy=continue',
|
|
77
|
+
'LimitCORE=0', 'UMask=0077',
|
|
78
|
+
`ExecStopPost=${[process.execPath, stopRecorder,...(receipts?['--check-run-id',receipts.checkRunId,'--receipt-dir',receipts.receiptDir]:[])].map(propertyArg).join(' ')}`,
|
|
79
|
+
];
|
|
80
|
+
const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${HOST_UNIT}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
|
|
81
|
+
const started=performance.now();
|
|
82
|
+
const child = spawn('/usr/bin/systemd-run', args, { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
83
|
+
onSpawned();
|
|
84
|
+
child.stdin.write(serialized+'\n');
|
|
85
|
+
let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false;
|
|
86
|
+
const launched = [];
|
|
87
|
+
const partial = new Map();
|
|
88
|
+
let partialUsage = null;
|
|
89
|
+
const cancel = () => { if(!cancellationSent){cancellationSent=true;child.stdin.write('cancel\n');} };
|
|
90
|
+
// Trusted supervisor messages only: guest stdout/stderr never reach this pipe
|
|
91
|
+
// directly. Still cap transport before parsing, including a broken supervisor.
|
|
92
|
+
// Output appears once in partial frames and once in the final receipt; the
|
|
93
|
+
// fixed allowance covers 10 reports per second at the maximum wall budget.
|
|
94
|
+
const transportCap = budgets.output_bytes * 3 + 1048576;
|
|
95
|
+
let received = 0;
|
|
96
|
+
child.stdout.on('data', chunk => {
|
|
97
|
+
received += chunk.length;
|
|
98
|
+
if (received > transportCap) { cancel(); return; }
|
|
99
|
+
buffer += chunk.toString('utf8');
|
|
100
|
+
for (;;) {
|
|
101
|
+
const end = buffer.indexOf('\n');
|
|
102
|
+
if (end < 0) break;
|
|
103
|
+
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
|
104
|
+
try {
|
|
105
|
+
const event = JSON.parse(line);
|
|
106
|
+
if (event.event === 'pid') pid = event.pid;
|
|
107
|
+
if (event.event === 'started' && phases.some(p => p.name === event.phase)) {
|
|
108
|
+
launched.push(event.phase);
|
|
109
|
+
if (onStarted) Promise.resolve(onStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
|
|
110
|
+
}
|
|
111
|
+
if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
|
|
112
|
+
if (event.event === 'partial' && launched.includes(event.phase)) {
|
|
113
|
+
const chunks = partial.get(event.phase) ?? [];
|
|
114
|
+
chunks.push(Buffer.from(event.output, 'base64'));
|
|
115
|
+
partial.set(event.phase, chunks);
|
|
116
|
+
partialUsage = event.usage;
|
|
117
|
+
}
|
|
118
|
+
if (event.event === 'result') message = event.result;
|
|
119
|
+
if (event.event === 'stopped') stopped = event.stop;
|
|
120
|
+
} catch { diagnostic = 'invalid supervisor response'; }
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
child.stderr.on('data', chunk => { if (diagnostic.length < 8192) diagnostic += chunk.toString('utf8').slice(0, 8192 - diagnostic.length); });
|
|
124
|
+
child.stdin.on('error', () => {});
|
|
125
|
+
const poll = setInterval(() => { if (cancelled()) cancel(); }, 50);
|
|
126
|
+
const exit = await new Promise(resolve => { child.once('error', e => resolve({ code: null, error: e.message })); child.once('close', (code, signal) => resolve({ code, signal })); });
|
|
127
|
+
clearInterval(poll);
|
|
128
|
+
child.stdin.end();
|
|
129
|
+
if (callbackError) throw callbackError;
|
|
130
|
+
// ExecStopPost runs after systemd has killed/reaped every process in the unit,
|
|
131
|
+
// even on OOM, RuntimeMaxSec, or loss of the main supervisor. No PID sweep or
|
|
132
|
+
// application TTL can release a still-running reservation.
|
|
133
|
+
const stopEvidence=resolveHostStopEvidence(receipts,stopped);
|
|
134
|
+
const stop = { verified: stopEvidence?.verified === true, reason: stopEvidence?.verified ? 'systemd_control_group_stopped' : 'service_stop_not_observed', service_result: stopped?.result ?? null, invocation_id: stopEvidence?.invocationId ?? stopped?.invocation_id ?? null, remaining_pids: stopEvidence?.remaining_pids ?? stopped?.remaining_pids ?? null, oom_kill: stopped?.oom_kill ?? null };
|
|
135
|
+
let error = message?.error ?? null;
|
|
136
|
+
if (stopped?.oom_kill > 0 || stopped?.result === 'oom-kill') error = 'budget exceeded: memory';
|
|
137
|
+
else if (stopped?.result === 'timeout') error = 'budget exceeded: wall';
|
|
138
|
+
else if (stopped && !message) error = stopped.result === 'signal' ? 'supervisor interrupted' : `host preparation failed: ${diagnostic.trim() || stopped.exit_status || 'supervisor exited without a receipt'}`;
|
|
139
|
+
else if (!stopped) error = pid ? 'host budget stop unverified: no service stop receipt' : `host budget admission failed: ${diagnostic.trim() || exit.error || 'service unavailable or busy'}`;
|
|
140
|
+
if (stopped && !stop.verified) error = 'host budget stop unverified';
|
|
141
|
+
const phaseResults = launched.map(name => {
|
|
142
|
+
const p = (message?.phases ?? []).find(result => result.name === name);
|
|
143
|
+
return p ? { ...p, bytes: Buffer.from(p.output, 'base64'), stop } : { name, exit: { code: 125 }, output: '', bytes: Buffer.concat(partial.get(name) ?? []), stop };
|
|
144
|
+
});
|
|
145
|
+
const bytes = Buffer.concat(phaseResults.map(p => p.bytes)).subarray(0, budgets.output_bytes);
|
|
146
|
+
const notStarted=provesHostNotStarted({spawnError:exit.error,pid,stopped}); // stderr is not trusted for this decision.
|
|
147
|
+
const usage = message?.usage ? { ...partialUsage, ...message.usage } : partialUsage;
|
|
148
|
+
return { dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
|
|
149
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
// cgroup.procs lists direct membership only. Walk child cgroups so the stop
|
|
5
|
+
// receipt covers the whole systemd unit, including nested scopes.
|
|
6
|
+
export function readCgroupProcesses(root, selfPid = process.pid) {
|
|
7
|
+
const processes = new Set();
|
|
8
|
+
const visit = directory => {
|
|
9
|
+
const entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
10
|
+
for (const line of fs.readFileSync(path.join(directory, 'cgroup.procs'), 'utf8').split('\n')) {
|
|
11
|
+
if (line === '') continue;
|
|
12
|
+
// Fail closed: a line that is not a positive integer is unreadable evidence, not an absent process.
|
|
13
|
+
const pid = /^[1-9][0-9]*$/.test(line) ? Number(line) : NaN;
|
|
14
|
+
if (!Number.isSafeInteger(pid)) throw new Error('unreadable cgroup.procs entry');
|
|
15
|
+
if (pid !== selfPid) processes.add(pid);
|
|
16
|
+
}
|
|
17
|
+
for (const entry of entries) {
|
|
18
|
+
if (entry.isDirectory()) visit(path.join(directory, entry.name));
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
visit(root);
|
|
22
|
+
return [...processes].sort((a, b) => a - b);
|
|
23
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
const policyFile = () => defaultPath(os.homedir(),'.config/dot-bridge/host-check-allowlist.json');
|
|
7
|
+
const repoPattern = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
8
|
+
const checkPattern = /^[A-Za-z0-9_.-]{1,64}(?:\/[A-Za-z0-9_.-]{1,64})*$/;
|
|
9
|
+
|
|
10
|
+
// The file is a separate owner-controlled activation capability. Invalid or
|
|
11
|
+
// unavailable state denies every check; callers must not cache this result.
|
|
12
|
+
export function readHostCheckAllowlist(file = policyFile(), ownerUid = process.getuid()) {
|
|
13
|
+
try {
|
|
14
|
+
const entry = fs.lstatSync(file);
|
|
15
|
+
if (!entry.isFile() || entry.isSymbolicLink() || entry.uid !== ownerUid || (entry.mode & 0o777) !== 0o600) return null;
|
|
16
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
17
|
+
try {
|
|
18
|
+
const stat = fs.fstatSync(fd);
|
|
19
|
+
if (!stat.isFile() || stat.uid !== ownerUid || (stat.mode & 0o777) !== 0o600 || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size > 65536) return null;
|
|
20
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
21
|
+
const count = fs.readSync(fd, bytes, 0, bytes.length, 0);
|
|
22
|
+
if (count > 65536) return null;
|
|
23
|
+
const value = JSON.parse(bytes.subarray(0, count).toString('utf8'));
|
|
24
|
+
if (!value || Array.isArray(value) || typeof value !== 'object' || Object.keys(value).sort().join(',') !== 'checks,version' || value.version !== 1 || !Array.isArray(value.checks)) return null;
|
|
25
|
+
const pairs = new Set();
|
|
26
|
+
for (const pair of value.checks) {
|
|
27
|
+
if (!pair || Array.isArray(pair) || typeof pair !== 'object' || Object.keys(pair).sort().join(',') !== 'check_id,repo' ||
|
|
28
|
+
typeof pair.repo !== 'string' || !repoPattern.test(pair.repo) || pair.repo.split('/').some(part => part === '.' || part === '..' || part.includes('..')) ||
|
|
29
|
+
typeof pair.check_id !== 'string' || !checkPattern.test(pair.check_id) || pair.check_id.split('/').some(part => part === '.' || part === '..' || part.includes('..'))) return null;
|
|
30
|
+
const key = `${pair.repo}\0${pair.check_id}`;
|
|
31
|
+
if (pairs.has(key)) return null;
|
|
32
|
+
pairs.add(key);
|
|
33
|
+
}
|
|
34
|
+
return pairs;
|
|
35
|
+
} finally { fs.closeSync(fd); }
|
|
36
|
+
} catch { return null; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function hostCheckPairAllowed(repo, checkId) {
|
|
40
|
+
const pairs = readHostCheckAllowlist();
|
|
41
|
+
return !!pairs && pairs.has(`${repo}\0${checkId}`);
|
|
42
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { readEnv } from './env.mjs';
|
|
2
|
+
import { sensitivePolicyPaths } from './submission-policy.mjs';
|
|
3
|
+
import { ownerCheck } from './projects.mjs';
|
|
4
|
+
import { parseHostBudget } from './host-budget.mjs';
|
|
5
|
+
import { hostCheckPairAllowed } from './host-check-allowlist.mjs';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
|
|
8
|
+
export const RESOURCE_LIMITS_UNAVAILABLE='resource_limits_unavailable: host checks are disabled; an operator must set DALAN_HOST_CHECKS=1 and each check must declare host_budget';
|
|
9
|
+
|
|
10
|
+
const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
11
|
+
|
|
12
|
+
export function hostCheckAuthorization(repo, checkId, expectedSpec = null) {
|
|
13
|
+
if (!hostCheckPairAllowed(repo, checkId)) return { refusal: 'host_check_not_allowlisted: owner allowlist does not permit this repository/check pair' };
|
|
14
|
+
let spec;
|
|
15
|
+
try { spec = ownerCheck(repo, checkId); } catch { return { refusal: 'host_check_owner_definition_unavailable: owner check configuration is invalid or unavailable' }; }
|
|
16
|
+
if (!spec) return { refusal: 'host_check_owner_definition_required: this check has no current owner-configured definition' };
|
|
17
|
+
if (!spec.host_budget) return { refusal: 'host_budget_missing: declare host_budget in owner configuration' };
|
|
18
|
+
try { parseHostBudget(spec.host_budget); } catch { return { refusal: 'host_budget_missing: declare a valid host_budget in owner configuration' }; }
|
|
19
|
+
if (expectedSpec && !same(spec, expectedSpec)) return { refusal: 'host_check_definition_changed: owner definition changed after resolution' };
|
|
20
|
+
return { spec };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null) {
|
|
24
|
+
const scope=assignment.scope_paths;
|
|
25
|
+
const narrow=Array.isArray(scope)&&scope.length&&!scope.some(p=>p.replace(/^\.\//,'').replace(/\/$/,'')==='.');
|
|
26
|
+
if(narrow||assignment.scope_excluded?.length) {
|
|
27
|
+
return 'scope_paths_read_isolation_unavailable: this executor exposes the whole checkout; a check needs an owner-approved repository-wide read grant';
|
|
28
|
+
}
|
|
29
|
+
if(sensitivePolicyPaths().error) return 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks';
|
|
30
|
+
if(readEnv('DALAN_HOST_CHECKS')!=='1') return RESOURCE_LIMITS_UNAVAILABLE;
|
|
31
|
+
if(repo!==null&&checkId!==null) {
|
|
32
|
+
const authorization=hostCheckAuthorization(repo,checkId,expectedSpec);
|
|
33
|
+
if(authorization.refusal) return authorization.refusal;
|
|
34
|
+
}
|
|
35
|
+
if(process.platform!=='linux') return `resource_limits_unavailable: no enforced host budget backend on ${process.platform}`;
|
|
36
|
+
if(!fs.existsSync('/usr/bin/systemd-run')||!fs.existsSync('/usr/bin/python3')||!fs.existsSync('/sys/fs/cgroup/cgroup.controllers')) return 'resource_limits_unavailable: Python 3.12+, systemd user services and unified cgroups are required';
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { adminSocketPathError } from './admin-socket.mjs';
|
|
4
|
+
|
|
5
|
+
export async function bridgeHealth({ socketPath, drainerFile, now = Date.now() }) {
|
|
6
|
+
const socketPathError = adminSocketPathError(socketPath);
|
|
7
|
+
if (socketPathError) throw socketPathError;
|
|
8
|
+
const status = await new Promise((resolve, reject) => {
|
|
9
|
+
const req = http.get({ socketPath, path: '/status' }, res => {
|
|
10
|
+
let body = '';
|
|
11
|
+
res.on('data', bytes => {
|
|
12
|
+
body += bytes;
|
|
13
|
+
if (Buffer.byteLength(body) > 1024 * 1024) req.destroy(new Error('status response too large'));
|
|
14
|
+
});
|
|
15
|
+
res.on('end', () => {
|
|
16
|
+
try { if (res.statusCode !== 200) throw new Error('bridge status unavailable'); resolve(JSON.parse(body)); }
|
|
17
|
+
catch (error) { reject(error); }
|
|
18
|
+
});
|
|
19
|
+
res.on('error', reject);
|
|
20
|
+
res.on('aborted', () => reject(new Error('bridge status response aborted')));
|
|
21
|
+
});
|
|
22
|
+
const deadline = setTimeout(() => req.destroy(new Error('bridge status timeout')), 5000);
|
|
23
|
+
req.on('close', () => clearTimeout(deadline));
|
|
24
|
+
req.on('error', reject);
|
|
25
|
+
});
|
|
26
|
+
if (!Array.isArray(status.counts) || status.counts.some(row => typeof row.status !== 'string' || !Number.isInteger(row.count) || row.count < 0) || typeof status.paused !== 'boolean' || !Number.isInteger(status.claimed_outer_count) || status.claimed_outer_count < 0) throw new Error('invalid bridge health evidence');
|
|
27
|
+
if (drainerFile) {
|
|
28
|
+
const drainer = JSON.parse(fs.readFileSync(drainerFile, 'utf8'));
|
|
29
|
+
const observed = Date.parse(drainer.observed_at);
|
|
30
|
+
if (drainer.healthy !== true || !Number.isFinite(observed) || now - observed > 150000 || observed > now + 30000) throw new Error('drainer evidence unhealthy or stale');
|
|
31
|
+
}
|
|
32
|
+
// Idle supply, ordinary policy refusals and intentional pause are healthy.
|
|
33
|
+
return { healthy: true, observed_at: new Date(now).toISOString() };
|
|
34
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import {spawnSync} from 'node:child_process';
|
|
3
|
+
import {readHostStart,writeHostReverify,readVerifiedHostStop,validBootId} from './host-budget-receipts.mjs';
|
|
4
|
+
import {readCgroupProcesses} from './host-cgroup.mjs';
|
|
5
|
+
import {HOST_UNIT} from './host-budget.mjs';
|
|
6
|
+
|
|
7
|
+
const currentBootId=()=>fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();
|
|
8
|
+
// Only "inactive" or "failed" shows the unit is gone. Any other answer, error or timeout counts as still active.
|
|
9
|
+
function hostUnitInactive() {
|
|
10
|
+
const r=spawnSync('/usr/bin/systemctl',['--user','is-active',HOST_UNIT],{encoding:'utf8',timeout:5000});
|
|
11
|
+
return !r.error&&['inactive','failed'].includes((r.stdout??'').trim());
|
|
12
|
+
}
|
|
13
|
+
// A missing cgroup directory means no process remains. Any other read error propagates and keeps the stop unverified.
|
|
14
|
+
function scanCgroup(dir) {
|
|
15
|
+
try {fs.lstatSync(dir);} catch(error) {if(error.code==='ENOENT') return [];throw error;}
|
|
16
|
+
return readCgroupProcesses(dir);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// A stop that was recorded unverified, or never recorded, is permanent unless fresh evidence shows nothing of the unit can run.
|
|
20
|
+
// Accepted proof, and nothing else:
|
|
21
|
+
// (a) the boot id now differs from the one in the start receipt: a reboot ended every process;
|
|
22
|
+
// (b) the same boot, the unit is no longer active, and a fresh scan of the recorded cgroup finds no process in its whole tree.
|
|
23
|
+
// A missing or unreadable boot id, any read error or any surviving process leaves the stop unverified.
|
|
24
|
+
// The original stop receipt is never changed; the proof goes into a separate link-once record.
|
|
25
|
+
export function reverifyHostStop({receiptDir,checkRunId},{bootId=currentBootId,unitInactive=hostUnitInactive,scan=scanCgroup}={}) {
|
|
26
|
+
try {
|
|
27
|
+
const existing=readVerifiedHostStop({receiptDir,checkRunId});
|
|
28
|
+
if(existing) return existing;
|
|
29
|
+
const start=readHostStart({receiptDir,checkRunId});
|
|
30
|
+
if(!start||start.notStarted||!validBootId(start.boot_id)) return null;
|
|
31
|
+
const now=bootId();
|
|
32
|
+
if(!validBootId(now)) return null;
|
|
33
|
+
let basis;
|
|
34
|
+
if(now!==start.boot_id) basis='boot_changed';
|
|
35
|
+
else if(typeof start.cgroup==='string'&&unitInactive()===true) {
|
|
36
|
+
const remaining=scan('/sys/fs/cgroup'+start.cgroup);
|
|
37
|
+
if(Array.isArray(remaining)&&remaining.length===0) basis='cgroup_empty';
|
|
38
|
+
}
|
|
39
|
+
if(!basis) return null;
|
|
40
|
+
try {writeHostReverify({receiptDir,checkRunId,invocationId:start.invocationId,basis,bootId:start.boot_id,currentBootId:now});}
|
|
41
|
+
catch(error) {if(error?.code!=='EEXIST') return null;}
|
|
42
|
+
return readVerifiedHostStop({receiptDir,checkRunId});
|
|
43
|
+
} catch {return null;}
|
|
44
|
+
}
|