File size: 4,749 Bytes
b1a18a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""Native Harbor git loading; only credentials and provenance are local glue."""
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path
import shlex
import tempfile

ROOT = Path(__file__).resolve().parent

def contract_files():
    """Fingerprint launch/config, generators and the complete OCI build context."""
    paths = {*ROOT.glob('*.py'), *ROOT.glob('*.toml'), ROOT/'uv.lock', ROOT/'task-source.json'}
    paths.update(p for p in (ROOT/'images').rglob('*') if p.is_file())
    return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
            for p in sorted(paths)}


def contract_digest():
    return hashlib.sha256(json.dumps(contract_files(), sort_keys=True).encode()).hexdigest()


def verify_local_source():
    """Verify committed source directly, without trusting untracked checkout files."""
    import subprocess
    source = json.loads((ROOT/'task-source.json').read_text())
    repository = ROOT/'.state/task-registry-repo'
    files = subprocess.check_output(['git', '-C', str(repository), 'ls-tree', '-r',
                                     '--name-only', source['commit'], 'tasks'], text=True).splitlines()
    manifest = {}
    for name in files:
        _, task, relative = name.split('/', 2)
        content = subprocess.check_output(['git', '-C', str(repository), 'show', source['commit']+':'+name])
        manifest.setdefault(task, {})[relative] = hashlib.sha256(content).hexdigest()
    assert manifest == source['task_manifest'], 'Pinned git contents differ from manifest'
    for name, expected in source.get('build_manifest', {}).items():
        content = subprocess.check_output(['git', '-C', str(repository), 'show', source['commit']+':'+name])
        assert hashlib.sha256(content).hexdigest() == expected, name
        assert (ROOT/'images/dependencies'/Path(name).name).read_bytes() == content, name
    registry = subprocess.check_output(['git', '-C', str(repository), 'show', source['commit']+':registry.json'])
    assert hashlib.sha256(registry).hexdigest() == source['registry_sha256']
    for task in manifest:
        original = ROOT.parent/('data/prime-tasks' if task.startswith('ds2-') else 'data/harbor')/task
        for name in ('instruction.md', 'tests/test.sh', 'tests/test_outputs.py', 'solution/solve.sh', 'environment/setup.sh'):
            assert hashlib.sha256((original/name).read_bytes()).hexdigest() == manifest[task][name], (task, name)
    return manifest


def source_config(dataset='workspace-four@1'):
    from verifiers.v1.tasksets.harbor.taskset import HarborConfig
    source = json.loads((ROOT/'task-source.json').read_text())
    assert len(source['commit']) == 40
    return HarborConfig(id='harbor', dataset=dataset,
        repo=source['repo']+'@'+source['commit'], registry_path=source['registry_path'],
        ignore_timeouts=False)

@contextmanager
def git_credentials():
    """Short-lived, repository-scoped SSH credentials in controller only."""
    key = os.environ.pop('TASK_REGISTRY_SSH_KEY', None)
    hosts = os.environ.pop('TASK_REGISTRY_KNOWN_HOSTS', None)
    if not key:
        yield
        return
    assert hosts, 'Pinned GitHub host keys required'
    previous = os.environ.get('GIT_SSH_COMMAND')
    with tempfile.TemporaryDirectory(prefix='task-registry-auth-') as temp:
        key_path=Path(temp)/'key'; key_path.write_text(key); key_path.chmod(0o600)
        known=Path(temp)/'known_hosts'; known.write_text(hosts)
        os.environ['GIT_SSH_COMMAND'] = ('ssh -o BatchMode=yes -o IdentitiesOnly=yes '
            '-o StrictHostKeyChecking=yes -o UserKnownHostsFile='+shlex.quote(str(known))+
            ' -i '+shlex.quote(str(key_path)))
        try:
            yield
        finally:
            if previous is None: os.environ.pop('GIT_SSH_COMMAND', None)
            else: os.environ['GIT_SSH_COMMAND'] = previous

def load_tasks(dataset='workspace-four@1'):
    from verifiers.v1.tasksets.harbor.taskset import HarborTaskset
    with git_credentials():
        tasks = list(HarborTaskset(source_config(dataset)).load())
    expected = json.loads((ROOT/'task-source.json').read_text())['task_manifest']
    actual = task_manifest(tasks)
    assert actual == {name: expected[name] for name in actual}, 'Cached task content differs from pinned manifest'
    assert set(actual) == (set(expected) if dataset == 'workspace-four@1' else {n for n in expected if n.startswith('ds2-')}), 'Unexpected cohort'
    return tasks

def task_manifest(tasks):
    return {task.data.name: {str(p.relative_to(Path(task.data.task_dir))):
        hashlib.sha256(p.read_bytes()).hexdigest()
        for p in sorted(Path(task.data.task_dir).rglob('*')) if p.is_file()}
        for task in tasks}