File size: 14,715 Bytes
0e239c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""Restore an exact, hash-bound Docker build context into a new directory."""
import argparse
from contextlib import contextmanager
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
import tarfile
import tempfile


def digest(path):
    value = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            value.update(block)
    return value.hexdigest()


def relative(name):
    path = PurePosixPath(name)
    if (not name or path.is_absolute() or '..' in path.parts or '.' in name.split('/')
            or '\\' in name or str(path) != name):
        raise ValueError('Unsafe context member: ' + name)
    return path


def declared_container_links(manifest, entries, tar):
    """Allow only exact Git-bound links to a declared paired container checkout."""
    absolute = {name: row for name, row in entries.items()
                if row.get('kind') == 'symlink' and PurePosixPath(row['target']).is_absolute()}
    if not absolute:
        return {}
    if manifest.get('schema_version', 1) < 3 or 'instance.json' not in entries:
        raise ValueError('Absolute source link requires a version 3 instance binding')
    member = tar.getmember('instance.json'); row = entries['instance.json']
    if not member.isfile() or member.size != row['bytes'] or member.size > 2 * 1024 * 1024:
        raise ValueError('Invalid source link declaration')
    data = tar.extractfile(member).read()
    if hashlib.sha256(data).hexdigest() != row['sha256']:
        raise ValueError('Source link declaration hash mismatch')
    instance = json.loads(data)
    repositories = {r['key']: r for r in instance['repositories']}
    allowed = {}
    for repo in repositories.values():
        path = PurePosixPath(repo['path'])
        if not path.is_absolute() or path.parts[:2] != ('/', 'testbed') or '..' in path.parts or '.git' in path.parts:
            raise ValueError('Invalid declared repository path')
        for link in repo.get('workspace_links', []):
            target = repositories[link['target_repository']]['path']
            if target == repo['path'] or link['original_target'] != target:
                raise ValueError('Container link does not bind a distinct paired repository')
            blob = target.encode()
            oid = hashlib.sha1(b'blob ' + str(len(blob)).encode() + b'\0' + blob).hexdigest()
            if oid != link['expected_blob']:
                raise ValueError('Container link differs from its original Git blob')
            name = str(PurePosixPath(repo['path'].lstrip('/')) / relative(link['path']))
            if name in allowed:
                raise ValueError('Duplicate container link declaration')
            allowed[name] = target
    if any(allowed.get(name) != row['target'] for name, row in absolute.items()):
        raise ValueError('Undeclared absolute context link')
    return {name: row['target'].lstrip('/') for name, row in absolute.items()}


def check_virtual_links(entries, container_links):
    """Resolve link graphs without touching an absolute container path on the host."""
    links = {name: row['target'] for name, row in entries.items() if row.get('kind') == 'symlink'}
    for name in links:
        pending = list(PurePosixPath(name).parts); stack = []; followed = 0
        while pending:
            part = pending.pop(0)
            if part in ('', '.'):
                continue
            if part == '..':
                if not stack:
                    raise ValueError('Context link escapes output')
                stack.pop(); continue
            stack.append(part); prefix = '/'.join(stack)
            if prefix in links:
                followed += 1
                if followed > 40:
                    raise ValueError('Cyclic or excessive context link graph')
                target = links[prefix]
                if PurePosixPath(target).is_absolute():
                    if prefix not in container_links:
                        raise ValueError('Undeclared absolute context link')
                    stack = []; target = container_links[prefix]
                else:
                    stack.pop()
                pending = list(PurePosixPath(target).parts) + pending


@contextmanager
def archive_stream(root, reference):
    parts=reference.get('parts')
    if parts is not None:
        if not isinstance(parts,list) or not parts:
            raise ValueError('Archive parts must be nonempty')
        with tempfile.TemporaryFile() as output:
            total=0;whole=hashlib.sha256()
            for part in parts:
                source=root/relative(part['path'])
                if source.is_symlink() or part['offset']!=total or source.stat().st_size!=part['bytes']:
                    raise ValueError('Archive part path/order/size mismatch')
                actual=hashlib.sha256()
                with source.open('rb') as stream:
                    for block in iter(lambda:stream.read(1024*1024),b''):
                        actual.update(block);whole.update(block);output.write(block);total+=len(block)
                if actual.hexdigest()!=part['sha256']:
                    raise ValueError('Archive part hash mismatch')
            if total!=reference['bytes'] or whole.hexdigest()!=reference['sha256']:
                raise ValueError('Reconstructed archive hash/size mismatch')
            output.seek(0)
            yield output
    else:
        source=root/relative(reference['path'])
        if source.is_symlink() or source.stat().st_size!=reference['bytes'] or digest(source)!=reference['sha256']:
            raise ValueError('Context archive hash/size mismatch')
        with source.open('rb') as stream:yield stream


def materialize(manifest_path, output, verify_only=False):
    manifest_path, output = Path(manifest_path), Path(output) if output is not None else None
    if output is not None and (output.exists() or output.is_symlink()):
        raise FileExistsError(output)
    manifest = json.loads(manifest_path.read_text())
    reference = manifest['archive']
    entries = {str(relative(row['path'])): row for row in manifest['files']}
    if len(entries) != len(manifest['files']):
        raise ValueError('Duplicate manifest members')
    for name in entries:
        if any(str(parent) in entries for parent in PurePosixPath(name).parents):
            raise ValueError('File/directory context collision')
    with archive_stream(manifest_path.parent,reference) as source, tarfile.open(fileobj=source,mode='r:gz') as tar:
        members = tar.getmembers()
        names = [str(relative(member.name)) for member in members]
        if len(names) != len(set(names)) or set(names) != set(entries):
            raise ValueError('Unlisted, missing or duplicate archive members')
        container_links = declared_container_links(manifest, entries, tar)
        for member in members:
            row = entries[member.name]
            if member.mode != row['mode'] or not 0 <= member.mode <= 0o777:
                raise ValueError('Context member type/size/mode mismatch')
            if row.get('kind','file')=='symlink':
                target=row['target']
                if (not member.issym() or member.linkname!=target or not target
                        or (PurePosixPath(target).is_absolute() and member.name not in container_links)
                        or '\\' in target or '\x00' in target):
                    raise ValueError('Unsafe or changed context link')
                data=target.encode()
                if len(data)!=row['bytes']:
                    raise ValueError('Context link size mismatch')
                actual=hashlib.sha256(data).hexdigest()
            elif row.get('kind','file')=='file' and member.isfile() and member.size==row['bytes']:
                actual_hash=hashlib.sha256()
                with tar.extractfile(member) as stream:
                    for block in iter(lambda:stream.read(1024*1024),b''):actual_hash.update(block)
                actual=actual_hash.hexdigest()
            else:
                raise ValueError('Unsupported or changed context member')
            if actual != row['sha256']:
                raise ValueError('Context member hash mismatch: ' + member.name)
        check_virtual_links(entries, container_links)
        if verify_only:
            return {'files':len(entries),'archive_sha256':reference['sha256'],'state':'ARCHIVE_VERIFIED'}
        output.mkdir(parents=True, exist_ok=False)
        try:
            for member in members:(output/member.name).parent.mkdir(parents=True,exist_ok=True)
            for member in members:
                if member.isfile():
                    target=output/member.name
                    with tar.extractfile(member) as source,target.open('xb') as destination:shutil.copyfileobj(source,destination)
                    target.chmod(member.mode)
            # No regular-file write occurs after creating any source link.
            for member in members:
                if member.issym():(output/member.name).symlink_to(member.linkname)
        except BaseException:
            shutil.rmtree(output)
            raise
    return {'files': len(entries), 'symlinks':sum(row.get('kind')=='symlink' for row in entries.values()),
            'declared_container_symlinks': len(container_links), 'archive_sha256': reference['sha256'], 'output': str(output)}



# crossswe repair publication context compatibility v1
def descriptor_ref(folder, reference):
    path = folder / relative(reference['path'])
    if any(p.is_symlink() for p in (path, *path.parents)) or not path.is_file():
        raise ValueError('Unsafe descriptor reference')
    if path.stat().st_size != reference['bytes'] or digest(path) != reference['sha256']:
        raise ValueError('Descriptor reference hash/size mismatch')
    return path


def current_context(root, instance_id):
    folder = root / 'environments' / relative(instance_id)
    image_path = folder / 'image.json'
    if any(p.is_symlink() for p in (image_path, *image_path.parents)):
        raise ValueError('Unsafe image descriptor path')
    image = json.loads(image_path.read_text())
    if image['instance_id'] != instance_id:
        raise ValueError('Image descriptor instance differs')
    manifest = descriptor_ref(folder, image['context_manifest'])
    recipe = None
    if image.get('recipe'):
        recipe = json.loads(descriptor_ref(folder, image['recipe']).read_text())
        import re
        if (recipe.get('kind') != 'immutable-parent-delta'
                or not re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}', recipe.get('parent_image_ref', ''))
                or recipe['actual_context'] != image['context_manifest']
                or descriptor_ref(folder, recipe['actual_context']) != manifest):
            raise ValueError('Invalid immutable parent/delta recipe')
        parent = json.loads(descriptor_ref(folder, recipe['parent_image_descriptor']).read_text())
        if parent.get('image_ref') != recipe['parent_image_ref']:
            raise ValueError('Recipe parent descriptor identity differs')
        descriptor_ref(folder, parent['context_manifest'])
        descriptor_ref(folder, recipe['source_authority'])
        descriptor_ref(folder, recipe['build_receipt'])
    # Every parent descriptor uses environment-root-relative refs, including an
    # exact historical descriptor stored below history/. Never rebase its refs
    # to the history directory.
    recipe_chain(folder, image)
    return manifest, recipe


def recipe_chain(folder, image, seen=None):
    seen = set() if seen is None else seen
    identity = image['image_ref']
    if identity in seen or len(seen) >= 40:
        raise ValueError('Cyclic or excessive recipe chain')
    seen.add(identity)
    if image.get('provenance_only'):
        if image.get('registry_digest') != 'sha256:e6c20a1727d4eb758737a9c2710a2e0a805bc534fc056929d7ddb2279b55437c' or identity != 'silinchen0617/crossrepo-bench@sha256:e6c20a1727d4eb758737a9c2710a2e0a805bc534fc056929d7ddb2279b55437c':
            raise ValueError('Unsupported provenance-only immutable parent')
        context = descriptor_ref(folder, image['context_manifest'])
        for reference in image['verified_provenance'].values():
            descriptor_ref(folder, reference)
        original = json.loads(descriptor_ref(folder, image['original_descriptor']).read_text())
        if original['registry_digest'] != 'sha256:dd0cf3223f7e9524c4c21aafce54a1b59a7e53288027a1332ddeb1577cad6dda':
            raise ValueError('Historical original parent differs')
        return [{'image_ref': identity, 'context_manifest': str(context), 'context_kind': 'verified-registry-parent-reference'}] + recipe_chain(folder, original, seen)
    context = descriptor_ref(folder, image['context_manifest'])
    result = [{'image_ref': identity, 'context_manifest': str(context),
               'context_kind': 'delta' if image.get('recipe') else 'full'}]
    if image.get('recipe'):
        recipe = json.loads(descriptor_ref(folder, image['recipe']).read_text())
        parent = json.loads(descriptor_ref(folder, recipe['parent_image_descriptor']).read_text())
        if parent['image_ref'] != recipe['parent_image_ref'] or recipe['actual_context'] != image['context_manifest']:
            raise ValueError('Recipe chain identity differs')
        result.extend(recipe_chain(folder, parent, seen))
    return result


def verify_manifest(manifest_path):
    return materialize(manifest_path, None, verify_only=True)


def materialize_image(root, instance_id, output):
    manifest, recipe = current_context(Path(root), instance_id)
    result = materialize(manifest, output)
    result['context_manifest'] = str(manifest)
    result['context_kind'] = 'delta' if recipe else 'full'
    if recipe:
        result['parent_image_ref'] = recipe['parent_image_ref']
        result['source_authority_full_build_context'] = recipe['source_authority_full_build_context']
        result['recipe_note'] = 'Build this actual delta with its pinned parent; historical full context remains preserved.'
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--instance-id', required=True)
    parser.add_argument('--output-dir', type=Path, required=True)
    args = parser.parse_args()
    if Path(args.instance_id).name != args.instance_id or args.instance_id in ('','.', '..'):
        parser.error('Use a canonical instance ID')
    root = Path(__file__).resolve().parents[1]
    print(json.dumps(materialize_image(root, args.instance_id, args.output_dir)))


if __name__ == '__main__':
    main()