367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
216 lines
12 KiB
Python
216 lines
12 KiB
Python
"""Stage an explicitly selected C++ render profile without publishing it.
|
|
|
|
This only selects/copies a reviewed build input. Appearance semantics and actual
|
|
client acceptance belong to the caller's existing render-profile evidence.
|
|
"""
|
|
import argparse,hashlib,json,os,stat
|
|
from pathlib import Path
|
|
from codec_build_cache import write_changed
|
|
MAX_BYTES=16*1024*1024
|
|
|
|
def _reject_windows_reparse_chain(path):
|
|
for part in (path, *path.parents):
|
|
attributes = getattr(part.lstat(), 'st_file_attributes', None)
|
|
if attributes is None or attributes & 0x400:
|
|
raise ValueError('Render header must not traverse Windows reparse points')
|
|
|
|
|
|
def _open_header_nofollow(path):
|
|
if os.name != 'nt':
|
|
return os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
import ctypes
|
|
from ctypes import wintypes
|
|
import msvcrt
|
|
_reject_windows_reparse_chain(path)
|
|
before = path.lstat()
|
|
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
|
kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
|
|
wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
|
kernel.CreateFileW.restype = wintypes.HANDLE
|
|
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
kernel.GetFileInformationByHandleEx.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
|
|
kernel.GetFileInformationByHandleEx.restype = wintypes.BOOL
|
|
class AttributeTag(ctypes.Structure):
|
|
_fields_ = [('attributes', wintypes.DWORD), ('tag', wintypes.DWORD)]
|
|
# OPEN_REPARSE_POINT prevents following the final component; no write/delete sharing.
|
|
handle = kernel.CreateFileW(str(path), 0x80000000, 1, None, 3, 0x00200000, None)
|
|
if handle == ctypes.c_void_p(-1).value:
|
|
raise ctypes.WinError(ctypes.get_last_error())
|
|
try:
|
|
info = AttributeTag()
|
|
if not kernel.GetFileInformationByHandleEx(handle, 9, ctypes.byref(info), ctypes.sizeof(info)):
|
|
raise ctypes.WinError(ctypes.get_last_error())
|
|
if info.attributes & 0x400:
|
|
raise ValueError('Render header is a Windows reparse point')
|
|
fd = msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY)
|
|
handle = None
|
|
after = os.fstat(fd)
|
|
if (before.st_dev, before.st_ino, before.st_size) != (after.st_dev, after.st_ino, after.st_size):
|
|
os.close(fd)
|
|
raise ValueError('Render header identity changed before open')
|
|
return fd
|
|
finally:
|
|
if handle is not None:
|
|
kernel.CloseHandle(handle)
|
|
|
|
|
|
def stage_render_profile(header,output,canonical_output):
|
|
if header is None:return None
|
|
output=Path(output).absolute();canonical_output=Path(canonical_output).resolve()
|
|
if output.resolve()==canonical_output:
|
|
raise ValueError('Render overrides require a separate output directory')
|
|
if output.resolve()!=output or any(c in str(output) for c in ('\0','\n','\r')):
|
|
raise ValueError('Render output must be a nonsymlink isolated directory')
|
|
header=Path(header).absolute()
|
|
if header.resolve(strict=True)!=header or any(c in str(header) for c in ('\0','\n','\r')):
|
|
raise ValueError('Render header must be a nonsymlink regular file')
|
|
if not stat.S_ISREG(header.lstat().st_mode):
|
|
raise ValueError('Render header must be a regular file')
|
|
fd=_open_header_nofollow(header)
|
|
try:
|
|
info=os.fstat(fd)
|
|
if not stat.S_ISREG(info.st_mode) or not 0<info.st_size<=MAX_BYTES:
|
|
raise ValueError('Render header must be a bounded regular file')
|
|
with os.fdopen(fd,'rb',closefd=False) as source:data=source.read(MAX_BYTES+1)
|
|
if len(data)!=info.st_size or len(data)>MAX_BYTES or b'\0' in data:
|
|
raise ValueError('Render header changed or is not bounded C++ text')
|
|
text=data.decode('utf-8')
|
|
finally:os.close(fd)
|
|
output.mkdir(parents=True,exist_ok=True)
|
|
staged=output/'staged-item-render-profile.hpp'
|
|
if staged.is_symlink() or (staged.exists() and not staged.is_file()):
|
|
raise ValueError('Staged render header is not a regular file')
|
|
# Preserve admitted bytes on Windows as well as POSIX (no newline translation).
|
|
if not staged.exists() or staged.read_bytes()!=data:
|
|
staged.write_bytes(data)
|
|
digest=hashlib.sha256(data).hexdigest()
|
|
if hashlib.sha256(staged.read_bytes()).hexdigest()!=digest:
|
|
raise ValueError('Staged render header differs from selected bytes')
|
|
result={'kind':'isolated-item-render-profile','isolated_only':True,
|
|
'header':{'path':str(header),'sha256':digest,'bytes':len(data)},
|
|
'compiled_header':{'path':str(staged),'sha256':digest},
|
|
'canonical_header_modified':False,'native_appearance_verified':False}
|
|
write_changed(output/'item-render-profile-override.json',json.dumps(result,indent=2)+'\n')
|
|
return result
|
|
|
|
# Factory source builds must select the accepted package and render profile as
|
|
# one pinned base. Large generated inputs remain in the portable base bundle.
|
|
SOURCE_ROOT=Path(__file__).resolve().parents[1]
|
|
DEFAULT_BASE_MANIFEST=SOURCE_ROOT/'ops/data/item-build-base-20261118.json'
|
|
DEFAULT_BASE_ROOT=SOURCE_ROOT/'base-inputs/Forever-Base-20261118'
|
|
|
|
def _pinned_base_file(root,pin,limit):
|
|
import re
|
|
from pathlib import PurePosixPath
|
|
if not isinstance(pin,dict) or set(pin)!={'path','sha256','bytes'}:
|
|
raise ValueError('Base input requires path, SHA256 and byte count')
|
|
relative=PurePosixPath(pin['path'])
|
|
if (not relative.parts or relative.is_absolute() or '..' in relative.parts or
|
|
'\\' in pin['path'] or relative.as_posix()!=pin['path'] or
|
|
not re.fullmatch('[0-9a-f]{64}',pin['sha256']) or
|
|
type(pin['bytes'])is not int or not 0<pin['bytes']<=limit):
|
|
raise ValueError('Base input must be a bounded portable relative path/hash')
|
|
path=root.joinpath(*relative.parts)
|
|
try:
|
|
if path.resolve(strict=True)!=path or not stat.S_ISREG(path.lstat().st_mode):
|
|
raise ValueError('Base input escaped or traversed a symlink')
|
|
fd=_open_header_nofollow(path)
|
|
try:
|
|
info=os.fstat(fd);digest=hashlib.sha256();count=0
|
|
with os.fdopen(fd,'rb',closefd=False)as stream:
|
|
while chunk:=stream.read(1024*1024):
|
|
count+=len(chunk)
|
|
if count>limit:raise ValueError('Base input size bound')
|
|
digest.update(chunk)
|
|
if count!=info.st_size or count!=pin['bytes'] or digest.hexdigest()!=pin['sha256']:
|
|
raise ValueError('Pinned base input changed: '+pin['path'])
|
|
finally:os.close(fd)
|
|
except OSError as error:
|
|
raise ValueError('Accepted base input missing; supply the portable source-input bundle: '+str(path))from error
|
|
return path
|
|
|
|
def load_build_base(manifest=None,root=None,*,source_root=SOURCE_ROOT):
|
|
manifest=Path(manifest or DEFAULT_BASE_MANIFEST).resolve(strict=True)
|
|
root=Path(root or DEFAULT_BASE_ROOT).resolve()
|
|
data=manifest.read_bytes()
|
|
if len(data)>65536:raise ValueError('Base manifest size bound')
|
|
proof=json.loads(data)
|
|
if (proof.get('schema')!=1 or proof.get('kind')!='accepted-item-build-base' or
|
|
proof.get('metadata_encoding')!='compact-v1' or
|
|
not isinstance(proof.get('base_id'),str) or not proof['base_id'] or
|
|
not isinstance(proof.get('source_pins'),list) or not proof['source_pins'] or
|
|
set(proof.get('inputs',{}))!={'render_header','render_profile','item_package','metadata_header','random_property_header','working_registry','working_codec','working_delta'}):
|
|
raise ValueError('Unsupported accepted item build base manifest')
|
|
files={name:_pinned_base_file(root,pin,128*1024*1024)for name,pin in proof['inputs'].items()}
|
|
for pin in proof.get('source_pins',[]):_pinned_base_file(Path(source_root).resolve(),pin,4*1024*1024)
|
|
from item_render_profile import header as render_header
|
|
profile=json.loads(files['render_profile'].read_text())
|
|
if render_header(profile).encode()!=files['render_header'].read_bytes():
|
|
raise ValueError('Base render header is not reproduced by its pinned profile')
|
|
return {'kind':'accepted-item-build-base','base_id':proof['base_id'],
|
|
'manifest':{'path':str(manifest),'sha256':hashlib.sha256(data).hexdigest()},
|
|
'root':str(root),'metadata_encoding':proof['metadata_encoding'],'inputs':{name:{**proof['inputs'][name],'path':str(path)}for name,path in files.items()}}
|
|
|
|
def resolve_base_package(base,output):
|
|
# Hash the original package before relocating only its three context paths.
|
|
inputs=base['inputs'];original=Path(inputs['item_package']['path']);raw=original.read_bytes()
|
|
if hashlib.sha256(raw).hexdigest()!=inputs['item_package']['sha256']:
|
|
raise ValueError('Original accepted base package changed')
|
|
package=json.loads(raw);relocations=[]
|
|
for section,field,key,hash_field in [
|
|
('working_wire_baseline','path','working_registry','sha256'),
|
|
('working_wire_baseline','codec_path','working_codec','codec_sha256'),
|
|
('working_wire_delta','path','working_delta','sha256')]:
|
|
meta=package[section];pin=inputs[key]
|
|
if meta[hash_field]!=pin['sha256']:raise ValueError('Base package provenance pin differs')
|
|
relocations.append({'field':section+'.'+field,'original':meta[field],'resolved':pin['path'],'sha256':pin['sha256']})
|
|
meta[field]=pin['path']
|
|
data=(json.dumps(package,ensure_ascii=False,separators=(',',':'))+'\n').encode()
|
|
output=Path(output);output.mkdir(parents=True,exist_ok=True);target=output/'base-resolved-package.json'
|
|
if target.is_symlink():raise ValueError('Resolved base package must not be a symlink')
|
|
target.write_bytes(data)
|
|
receipt={'kind':'base-package-context-relocation','original_sha256':inputs['item_package']['sha256'],
|
|
'resolved_sha256':hashlib.sha256(data).hexdigest(),'resolved_path':str(target.resolve()),
|
|
'relocations':relocations,'record_bodies_modified':False,'original_package_modified':False}
|
|
write_changed(output/'base-package-context-relocation.json',json.dumps(receipt,indent=2)+'\n')
|
|
return receipt
|
|
|
|
def stage_build_base(manifest,root,output,canonical_output):
|
|
import shutil
|
|
base=load_build_base(manifest,root)
|
|
profile=stage_render_profile(base['inputs']['render_header']['path'],output,canonical_output)
|
|
if profile['header']['sha256']!=base['inputs']['render_header']['sha256']:
|
|
raise ValueError('Base render header changed during staging')
|
|
include=Path(output).absolute()/'base-include/gateway';include.mkdir(parents=True,exist_ok=True)
|
|
for key,name in [('metadata_header','item_sparse_compat.hpp'),('random_property_header','item_random_property_profile.hpp')]:
|
|
pin=base['inputs'][key];target=include/name
|
|
if target.is_symlink() or(target.exists()and not target.is_file()):raise ValueError('Invalid base staged include')
|
|
temporary=target.with_suffix('.hpp.new')
|
|
if temporary.exists()or temporary.is_symlink():raise ValueError('Base staging temporary already exists')
|
|
try:
|
|
with os.fdopen(_open_header_nofollow(Path(pin['path'])),'rb')as source,temporary.open('xb')as destination:
|
|
shutil.copyfileobj(source,destination,1024*1024)
|
|
_pinned_base_file(include,{'path':temporary.name,'sha256':pin['sha256'],'bytes':pin['bytes']},128*1024*1024)
|
|
temporary.replace(target)
|
|
finally:
|
|
if temporary.exists():temporary.unlink()
|
|
profile['base_inputs']=base;profile['compiled_include']=str(include.parent)
|
|
write_changed(Path(output)/'item-render-profile-override.json',json.dumps(profile,indent=2)+'\n')
|
|
return profile
|
|
|
|
def compiler_flags(profile):
|
|
return [] if profile is None else ['-DGW_ITEM_RENDER_PROFILE_HEADER='+json.dumps(profile['compiled_header']['path'])]
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--header',type=Path)
|
|
p.add_argument('--base-manifest',type=Path)
|
|
p.add_argument('--base-root',type=Path)
|
|
p.add_argument('--output-directory',required=True,type=Path)
|
|
p.add_argument('--canonical-output',required=True,type=Path)
|
|
a=p.parse_args()
|
|
if a.header and(a.base_manifest or a.base_root):p.error('Choose explicit isolated header or accepted base inputs')
|
|
result=stage_render_profile(a.header,a.output_directory,a.canonical_output)if a.header else stage_build_base(a.base_manifest,a.base_root,a.output_directory,a.canonical_output)
|
|
print(json.dumps(result))
|
|
if __name__=='__main__':main()
|