@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1

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.
@@ -0,0 +1,40 @@
1
+ """Enroll an explicitly selected Linux executor from a Windows/macOS desktop."""
2
+ import re
3
+ import shlex
4
+ import subprocess
5
+ from .installer import ContractError, canonical, loads
6
+
7
+
8
+ # The script is constant. Neither a credential nor a user supplied program is
9
+ # interpolated into it. stdin carries only a short-lived enrollment challenge.
10
+ REMOTE = '''set -eu
11
+ umask 077
12
+ entry=$(mktemp "${TMPDIR:-/tmp}/tedbrain-dpv2-entry.XXXXXX")
13
+ trap 'rm -f "$entry"' EXIT HUP INT TERM
14
+ curl --proto '=https' --fail --silent --show-error --connect-timeout 10 --max-time 60 https://tedbrain.com/pkg/pdkadapt/cli.sh -o "$entry"
15
+ sh "$entry" workstation prepare
16
+ '''
17
+
18
+
19
+ def prepare(destination, proxy, challenge):
20
+ if not isinstance(destination,str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._@:-]{0,254}',destination):
21
+ raise ContractError('SSH destination must be a host alias or user@host')
22
+ try:
23
+ result=subprocess.run(['ssh','-T','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','--',
24
+ destination,'sh -c '+shlex.quote(REMOTE)],
25
+ input=canonical({'proxy':proxy,'challenge':challenge}),capture_output=True,timeout=600)
26
+ except FileNotFoundError:
27
+ raise ContractError('OpenSSH client required for the selected Linux executor') from None
28
+ except subprocess.TimeoutExpired:
29
+ raise ContractError('SSH enrollment response unknown; retry the same workstation request') from None
30
+ if result.returncode:
31
+ raise ContractError('SSH preparation failed; verify the selected host, trusted host key, login and HTTPS access')
32
+ if len(result.stdout)>65536:raise ContractError('invalid SSH enrollment response')
33
+ try:
34
+ value=loads(result.stdout.splitlines()[-1])
35
+ if set(value)!={'connection_id','release_sha256'}:raise ValueError()
36
+ if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',value['connection_id']):raise ValueError()
37
+ if not re.fullmatch('[a-f0-9]{64}',value['release_sha256']):raise ValueError()
38
+ except (ContractError,ValueError,TypeError,KeyError,IndexError):
39
+ raise ContractError('invalid SSH enrollment response') from None
40
+ return value
@@ -0,0 +1,104 @@
1
+ """Durable independent DPV2 worker supervisor.
2
+
3
+ A claimed attempt is launched at most once. A supervisor crash between spawn and
4
+ PID recording is reconciled from its receipt, never handled by spawning again.
5
+ """
6
+ import argparse
7
+ import hashlib
8
+ import fcntl
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from .installer import ContractError, atomic, canonical, loads
16
+ from .jobs import Jobs
17
+ from .workstations import Workstations
18
+ from .executor import live
19
+
20
+
21
+ class Worker:
22
+ def __init__(self, config):
23
+ self.config=config
24
+ self.state=Path(config['state_root']).absolute()
25
+ self.jobs=Jobs(self.state/'jobs.sqlite3')
26
+ self.stations=Workstations(self.state/'workstations.sqlite3')
27
+ self.root=self.state/'executions';self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
28
+ self.version=config['worker_version']
29
+
30
+ def path(self, row):
31
+ return self.root/row['id']/row['attempt']
32
+
33
+ def reconcile(self, row):
34
+ directory=self.path(row);receipt=directory/'result.json';process=directory/'process.json'
35
+ if receipt.is_file():
36
+ if receipt.is_symlink() or receipt.stat().st_size>1048576:raise ContractError('invalid worker receipt')
37
+ raw=receipt.read_bytes();digest=hashlib.sha256(raw).hexdigest()
38
+ observed=directory/'observed-result.json'
39
+ if observed.is_file() and loads(observed.read_bytes()).get('sha256')==digest:return
40
+ result=loads(raw)
41
+ if (result.get('job_id'),result.get('attempt'),result.get('version'))!=(row['id'],row['attempt'],row['version']):
42
+ raise ContractError('worker receipt identity mismatch')
43
+ self.jobs.complete(row['id'],row['attempt'],result['result'],stopped=result['remote_stop_confirmed'] is True,
44
+ checkpoint_schema=result.get('checkpoint_schema'))
45
+ atomic(observed,canonical({'sha256':digest}))
46
+ return
47
+ if process.is_file() and live(loads(process.read_bytes())):return
48
+ if row['state']!='UNKNOWN':
49
+ self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'UNKNOWN',
50
+ 'error':{'code':'WORKER_OUTCOME_UNKNOWN','message':'Execution receipt unavailable; reconcile the original attempt'}},stopped=False)
51
+
52
+ def launch(self, row):
53
+ directory=self.path(row)
54
+ # Exclusive creation is a second guard after the DB claim. Existing
55
+ # attempt state can only be reconciled, including incomplete launches.
56
+ directory.mkdir(parents=True,exist_ok=False,mode=0o700)
57
+ station=self.stations.get(row['subject'],row['workstation'])
58
+ spec={'schema':1,'job':row,'workstation':station,'config':self.config}
59
+ atomic(directory/'input.json',canonical(spec))
60
+ env={k:v for k,v in os.environ.items() if not k.startswith(('ELINK_','VLINK_','TED','PDK','PYTHON','XDG_'))}
61
+ for key,value in self.config['worker_environment'].items():
62
+ if not isinstance(key,str) or not isinstance(value,str):raise ContractError('invalid worker environment')
63
+ env[key]=value
64
+ for key,relative in [('HOME','home'),('TMPDIR','tmp'),('XDG_CACHE_HOME','cache'),('TED_DATA','data')]:
65
+ path=directory/relative;path.mkdir(mode=0o700);env[key]=str(path)
66
+ env.update(PYTHONDONTWRITEBYTECODE='1',PYTHONNOUSERSITE='1',
67
+ TEDBRAIN_SUBJECT=row['subject'],TEDBRAIN_TASK_ID=row['attempt'],
68
+ ELINK_SERVER_URL=self.config['transport']['serve_url'],ELINK_CLIENT_ID=station['connection_id'],
69
+ ELINK_SERVE_TOKEN=Path(self.config['transport']['serve_token_file']).read_text().strip())
70
+ atomic(directory/'launch-intent.json',canonical({'attempt':row['attempt'],'version':self.version}))
71
+ command=[self.config.get('worker_python',sys.executable),'-s','-B','-m','tedbrain_plugin_runtime.engine',str(directory/'input.json')]
72
+ with (directory/'worker.log').open('ab') as log:
73
+ child=subprocess.Popen(command,env=env,stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
74
+ fields=Path('/proc/%d/stat'%child.pid).read_text().rsplit(')',1)[1].split()
75
+ atomic(directory/'process.json',canonical({'pid':child.pid,'start_time':fields[19]}))
76
+ self.jobs.append(row['id'],row['attempt'],{'event':'worker_started','plugin_version':self.version})
77
+
78
+ def tick(self):
79
+ with self.jobs.connection() as db:
80
+ active=[dict(row) for row in db.execute("SELECT * FROM jobs WHERE version=? AND state IN ('RUNNING','CANCELLING','UNKNOWN')",(self.version,))]
81
+ for row in active:self.reconcile(row)
82
+ row=self.jobs.claim(self.version,max_active=self.config.get('max_active_jobs',2))
83
+ if row is not None:
84
+ try:self.launch(row)
85
+ except Exception:
86
+ # Even a local launch failure can occur after the child started.
87
+ # Do not claim that remote work stopped or retry automatically.
88
+ self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'UNKNOWN',
89
+ 'error':{'code':'WORKER_LAUNCH_UNKNOWN','message':'Worker launch requires reconciliation'}},stopped=False)
90
+ return row is not None
91
+
92
+
93
+ def main(argv=None):
94
+ parser=argparse.ArgumentParser();parser.add_argument('--config',type=Path,required=True);parser.add_argument('--once',action='store_true')
95
+ args=parser.parse_args(argv);worker=Worker(loads(args.config.read_bytes()))
96
+ lock=worker.state/('worker-'+worker.version+'.lock')
97
+ with lock.open('a') as stream:
98
+ fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB)
99
+ while True:
100
+ worker.tick()
101
+ if args.once:return 0
102
+ time.sleep(1)
103
+
104
+ if __name__=='__main__':raise SystemExit(main())
@@ -0,0 +1,170 @@
1
+ """DPV2 workstation enrollment with proof read from the isolated executor.
2
+
3
+ Knowing a transport connection ID is insufficient to enroll it. The account
4
+ holder must write the short-lived challenge into that executor's private HOME.
5
+ The service only reads this fixed file; it never writes its own proof remotely.
6
+ """
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import secrets
13
+ import sqlite3
14
+ import subprocess
15
+ import time
16
+ from .installer import ContractError, canonical, loads
17
+ from .jobs import Conflict, NotFound
18
+
19
+
20
+ class Unavailable(ContractError):
21
+ pass
22
+
23
+
24
+ class Workstations:
25
+ def __init__(self, path):
26
+ self.path = Path(path)
27
+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
28
+ if self.path.is_symlink():
29
+ raise ContractError('workstation database symlink refused')
30
+ with sqlite3.connect(self.path) as db:
31
+ db.executescript('''
32
+ CREATE TABLE IF NOT EXISTS challenges(
33
+ id TEXT PRIMARY KEY, subject TEXT NOT NULL, nonce TEXT NOT NULL,
34
+ label TEXT NOT NULL, expires REAL NOT NULL, station TEXT, request_key TEXT);
35
+ CREATE TABLE IF NOT EXISTS stations(
36
+ id TEXT PRIMARY KEY, subject TEXT NOT NULL, connection TEXT NOT NULL UNIQUE,
37
+ label TEXT NOT NULL, release TEXT NOT NULL, updated REAL NOT NULL, home TEXT NOT NULL);
38
+ ''')
39
+ if 'request_key' not in [r[1] for r in db.execute('PRAGMA table_info(challenges)')]:
40
+ db.execute('ALTER TABLE challenges ADD COLUMN request_key TEXT')
41
+ db.execute('CREATE UNIQUE INDEX IF NOT EXISTS challenge_requests ON challenges(subject,request_key)')
42
+ if 'home' not in [r[1] for r in db.execute('PRAGMA table_info(stations)')]:
43
+ db.execute("ALTER TABLE stations ADD COLUMN home TEXT NOT NULL DEFAULT ''")
44
+ self.path.chmod(0o600)
45
+
46
+ def challenge(self, subject, label, key=None):
47
+ if not isinstance(label, str) or not 1 <= len(label) <= 80 or any(ord(c) < 32 for c in label):
48
+ raise ContractError('workstation label required (1..80 characters)')
49
+ identifier, nonce = secrets.token_hex(16), secrets.token_hex(32)
50
+ expires = time.time() + 600
51
+ with sqlite3.connect(self.path,timeout=30) as db:
52
+ db.execute('BEGIN IMMEDIATE')
53
+ if key:
54
+ old=db.execute('SELECT id,nonce,label,expires FROM challenges WHERE subject=? AND request_key=?',(subject,key)).fetchone()
55
+ if old:
56
+ if old[2]!=label:raise Conflict('enrollment key belongs to another request')
57
+ if old[3]<=time.time():raise Conflict('workstation challenge expired')
58
+ identifier,nonce,_,expires=old
59
+ else:
60
+ db.execute('INSERT INTO challenges VALUES(?,?,?,?,?,NULL,?)',(identifier,subject,nonce,label,expires,key))
61
+ else:
62
+ db.execute('INSERT INTO challenges VALUES(?,?,?,?,?,NULL,NULL)',(identifier,subject,nonce,label,expires))
63
+ return {'challenge_id': identifier, 'nonce': nonce, 'expires_at': expires,
64
+ 'relative_path': '.ted/tedbrain/dpv2-binding/' + identifier + '.json'}
65
+
66
+ def confirm(self, subject, identifier, connection, verifier):
67
+ if not re.fullmatch('[a-f0-9]{32}', identifier or ''):
68
+ raise ContractError('invalid challenge identifier')
69
+ if not isinstance(connection, str) or not re.fullmatch('[A-Za-z0-9_-]{8,128}', connection):
70
+ raise ContractError('invalid workstation connection')
71
+ with sqlite3.connect(self.path) as db:
72
+ row = db.execute('SELECT subject,nonce,label,expires,station FROM challenges WHERE id=?', (identifier,)).fetchone()
73
+ if not row or row[0] != subject:
74
+ raise NotFound('challenge not found')
75
+ if row[3] <= time.time():
76
+ raise Conflict('workstation challenge expired')
77
+ if row[4]:
78
+ station = self.get(subject, row[4])
79
+ if station['connection_id'] != connection:
80
+ raise Conflict('challenge already bound to another connection')
81
+ return self.public(station)
82
+ proof = verifier(connection, identifier)
83
+ if not isinstance(proof, dict) or proof.get('protocol') != 1 or proof.get('platform') != 'linux-x64':
84
+ raise Conflict('unsupported workstation executor')
85
+ if not secrets.compare_digest(str(proof.get('nonce', '')), row[1]):
86
+ raise Conflict('workstation ownership proof rejected')
87
+ release = proof.get('release_sha256', '')
88
+ if not isinstance(release, str) or not re.fullmatch('[a-f0-9]{64}', release):
89
+ raise Conflict('workstation release identity missing')
90
+ home=proof.get('home','')
91
+ if not isinstance(home,str) or not Path(home).is_absolute() or not home.endswith('/workstations/'+release+'/home') or any(ord(c)<32 for c in home):
92
+ raise Conflict('workstation private HOME identity missing')
93
+ # Serialize ownership changes after the remote read. Recheck expiry and
94
+ # consumption under the write lock; a different subject cannot steal it.
95
+ with sqlite3.connect(self.path, timeout=30) as db:
96
+ db.execute('BEGIN IMMEDIATE')
97
+ current = db.execute('SELECT expires,station FROM challenges WHERE id=?', (identifier,)).fetchone()
98
+ if current is None or current[0] <= time.time():
99
+ raise Conflict('workstation challenge expired')
100
+ previous = db.execute('SELECT id,subject FROM stations WHERE connection=?', (connection,)).fetchone()
101
+ if previous and previous[1] != subject:
102
+ raise Conflict('workstation already belongs to another account')
103
+ station = previous[0] if previous else secrets.token_hex(16)
104
+ if current[1] and current[1] != station:
105
+ raise Conflict('challenge already consumed')
106
+ db.execute('INSERT OR REPLACE INTO stations VALUES(?,?,?,?,?,?,?)',
107
+ (station, subject, connection, row[2], release, time.time(),home))
108
+ db.execute('UPDATE challenges SET station=? WHERE id=?', (station, identifier))
109
+ return self.public(self.get(subject, station))
110
+
111
+ def get(self, subject, identifier):
112
+ with sqlite3.connect(self.path) as db:
113
+ row = db.execute('SELECT * FROM stations WHERE id=? AND subject=?', (identifier, subject)).fetchone()
114
+ if row is None:
115
+ raise NotFound('workstation not found')
116
+ return dict(zip(('workstation_id', 'subject', 'connection_id', 'label', 'release_sha256', 'updated', 'home'), row), state='ready')
117
+
118
+ @staticmethod
119
+ def public(station):
120
+ return {key: station[key] for key in ('workstation_id', 'label', 'state', 'release_sha256')}
121
+
122
+ def list(self, subject):
123
+ with sqlite3.connect(self.path) as db:
124
+ identifiers = [r[0] for r in db.execute('SELECT id FROM stations WHERE subject=? ORDER BY updated', (subject,))]
125
+ return [self.public(self.get(subject, identifier)) for identifier in identifiers]
126
+
127
+
128
+ class EnrollmentReader:
129
+ """Only the server-configured DPV2 serve endpoint can read a proof file."""
130
+ def __init__(self, config):
131
+ self.config = config
132
+
133
+ def __call__(self, connection, challenge):
134
+ if not re.fullmatch('[a-f0-9]{32}', challenge):
135
+ raise ContractError('invalid challenge')
136
+ config = self.config
137
+ binary = Path(config['elink_binary'])
138
+ secret = Path(config['serve_token_file'])
139
+ if not binary.is_absolute() or not binary.is_file() or not secret.is_file() or secret.is_symlink():
140
+ raise Unavailable('DPV2 transport configuration unavailable')
141
+ if secret.stat().st_mode & 0o077:
142
+ raise Unavailable('DPV2 serve token must be private')
143
+ # The service endpoint is configuration, never an API input. Explicit
144
+ # connection and serve URL prevent fallback to a global V1 daemon.
145
+ from urllib.parse import urlsplit
146
+ parsed = urlsplit(config['serve_url'])
147
+ if parsed.scheme != 'http' or parsed.hostname not in ('127.0.0.1', '::1') or parsed.username or parsed.query or parsed.fragment:
148
+ raise Unavailable('DPV2 serve must be an explicit loopback endpoint')
149
+ env = {k: v for k, v in os.environ.items() if not k.startswith(('ELINK_', 'VLINK_', 'TEDBRAIN_'))}
150
+ env.update(ELINK_SERVER_URL=config['serve_url'], ELINK_CLIENT_ID=connection,
151
+ ELINK_SERVE_TOKEN=secret.read_text().strip())
152
+ script = ('set -eu\nfile="$HOME/.ted/tedbrain/dpv2-binding/' + challenge + '.json"\n'
153
+ 'test -f "$file" && test ! -L "$file"\n'
154
+ 'test "$(wc -c < "$file")" -le 4096\n'
155
+ "printf '%s\\n' \"$HOME\"\n"
156
+ 'cat "$file"\n')
157
+ try:
158
+ result = subprocess.run([str(binary), 'forward', 'bash', '-'], input=script.encode(),
159
+ env=env, capture_output=True, timeout=20)
160
+ except (OSError, subprocess.TimeoutExpired):
161
+ raise Unavailable('workstation proof could not be read') from None
162
+ if result.returncode or len(result.stdout) > 4096:
163
+ raise Conflict('workstation proof missing or unreadable')
164
+ raw_home,separator,payload=result.stdout.partition(b'\n')
165
+ if not separator:raise Conflict('workstation HOME response missing')
166
+ proof = loads(payload)
167
+ proof['home']=raw_home.decode('utf8')
168
+ if proof.get('release_sha256') not in config['executor_releases']:
169
+ raise Conflict('workstation executor release is not supported')
170
+ return proof