Iomatex_OS/offline/git_delivery.py

352 lines
16 KiB
Python

#!/usr/bin/env python3
"""Small Edge snapshot + on-demand, hash-checked downloads from our Git only.
APT method protocol: https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/
"""
import base64
from concurrent.futures import ThreadPoolExecutor
import fcntl
import gzip
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import pwd
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import urllib.parse
import urllib.request
HOST = 'git.it-screen.com'
STATE = Path('/var/lib/iomatex/packages')
AUTH = Path('/etc/iomatex/git-credentials.json')
CACHE = Path('/userdata/iomatex-apt-cache')
DEBIAN = 'third_party/debian/bullseye-arm64'
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
raise ValueError('Git download redirect refused')
def safe_path(value):
p = PurePosixPath(value)
if p.is_absolute() or '..' in p.parts or not p.parts or any(c in value for c in '\r\n\\'):
raise ValueError('Unsafe repository path')
return p.as_posix()
def repo_name(url):
u = urllib.parse.urlparse(url)
if u.scheme != 'https' or u.netloc != HOST or u.query or u.fragment:
raise ValueError('Only HTTPS repositories on our Git are allowed')
name = u.path.strip('/').removesuffix('.git')
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name):
raise ValueError('Invalid repository')
return name
def auth_from_env():
user, password = os.environ.get('IOMATEX_GIT_USERNAME'), os.environ.get('IOMATEX_GIT_PASSWORD')
if user and password:
return {'username': user, 'password': password}
return json.loads(AUTH.read_text())
def open_git(repo, endpoint, auth):
url = 'https://' + HOST + '/api/v1/repos/' + repo + '/' + endpoint
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
return urllib.request.build_opener(NoRedirect).open(req, timeout=120)
def raw_endpoint(path, commit):
if not re.fullmatch('[a-f0-9]{40}', commit):
raise ValueError('Download must be pinned to a commit')
return 'raw/' + urllib.parse.quote(safe_path(path), safe='/') + '?ref=' + commit
def blob_hash(data):
return hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
def write_json(path, value, mode=0o644):
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent)
try:
with os.fdopen(fd, 'w') as f:
json.dump(value, f)
os.chmod(tmp, mode)
os.replace(tmp, path)
finally:
Path(tmp).unlink(missing_ok=True)
def platform_check():
if os.geteuid() != 0:
raise PermissionError('Run as root')
if subprocess.check_output(['dpkg', '--print-architecture'], text=True).strip() != 'arm64' or 'VERSION_CODENAME=bullseye' not in Path('/etc/os-release').read_text():
raise ValueError('Supported image: Debian 11 Bullseye arm64')
def is_payload(path):
return path.endswith(('.deb', '.tar.gz')) or path == 'stage_itscreen/itscreen'
def check_existing(dest):
if (dest / '.git').exists():
changed = subprocess.check_output(['git', '-C', str(dest), 'status', '--porcelain', '--untracked-files=no'], text=True)
if changed.strip():
raise ValueError('Existing checkout has tracked local changes; preserve them before updating')
elif (dest / '.iomatex-source.json').exists():
for entry in json.loads((dest / '.iomatex-source.json').read_text())['files']:
p = dest / entry['path']
if p.is_file() and blob_hash(p.read_bytes()) != entry['sha']:
raise ValueError('Local change in snapshot: ' + entry['path'])
elif dest.exists() and any(dest.iterdir()):
raise ValueError('Refusing to replace an unidentified nonempty directory')
def bootstrap(url, branch, checkout):
platform_check()
repo = repo_name(url)
requested = Path(checkout)
dest = requested.resolve()
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
raise ValueError('Use a dedicated absolute installer subdirectory')
check_existing(dest)
if (dest / '.git').exists():
origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip()
if repo_name(origin) != repo:
raise ValueError('Existing checkout origin mismatch')
auth = auth_from_env()
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
commit = json.load(r)['commit']['id']
with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r:
tree = json.load(r)
if tree.get('truncated'):
raise ValueError('Git returned an incomplete repository tree')
files = []
for item in tree['tree']:
path = safe_path(item['path'])
if item['type'] == 'tree' or is_payload(path):
continue
if item['type'] != 'blob' or item['mode'] not in ('100644', '100755'):
raise ValueError('Unsupported Git tree member: ' + path)
files.append({k: item[k] for k in ('path', 'sha', 'mode')})
dest.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.iomatex-install-', dir=dest.parent) as tmp:
staged = Path(tmp) / 'snapshot'
staged.mkdir()
def download(entry):
with open_git(repo, raw_endpoint(entry['path'], commit), auth) as r:
data = r.read()
if blob_hash(data) != entry['sha']:
raise ValueError('Git blob checksum mismatch: ' + entry['path'])
p = staged / entry['path']
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)
p.chmod(int(entry['mode'][-3:], 8))
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
with ThreadPoolExecutor(max_workers=6) as pool:
list(pool.map(download, files))
source = {'repo': repo, 'commit': commit, 'branch': branch, 'files': files}
write_json(staged / '.iomatex-source.json', source)
# Validate all metadata before replacing an existing installation snapshot.
catalog(staged)
previous = Path(tmp) / 'previous'
if dest.exists():
# Keep untracked operator files/state/logs, never carry the old Git pack or payloads.
tracked = set()
if (dest / '.git').exists():
tracked = set(subprocess.check_output(['git', '-C', str(dest), 'ls-files'], text=True).splitlines())
else:
tracked = {e['path'] for e in json.loads((dest / '.iomatex-source.json').read_text()).get('files', [])}
for p in dest.rglob('*'):
relative = p.relative_to(dest).as_posix()
if '.git' in p.relative_to(dest).parts or relative in tracked or relative == '.iomatex-source.json':
continue
if p.is_file() and not p.is_symlink() and not (staged / relative).exists():
(staged / relative).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(p, staged / relative)
dest.rename(previous)
try:
staged.rename(dest)
write_json(AUTH, auth, 0o600)
# Execute the NEW activator from the downloaded commit, not an old bootstrap copy.
subprocess.run([sys.executable, str(dest / 'offline/git_delivery.py'), 'activate', str(dest)], check=True)
except BaseException:
if dest.exists(): shutil.rmtree(dest)
if previous.exists(): previous.rename(dest)
raise
print('Lightweight installer ready:', commit, str(dest), flush=True)
def manifest(path):
result = {}
for line in path.read_text().splitlines():
digest, name = line.split(' ', 1)
name = safe_path(name)
if not re.fullmatch('[a-f0-9]{64}', digest) or name in result:
raise ValueError('Invalid checksum manifest')
result[name] = digest
return result
def catalog(root):
root = Path(root)
sums = manifest(root / DEBIAN / 'SHA256SUMS')
runtime = manifest(root / 'third_party/SHA256SUMS')
for name, digest in sums.items():
if not name.endswith('.deb') and hashlib.sha256((root / DEBIAN / name).read_bytes()).hexdigest() != digest:
raise ValueError('Metadata checksum mismatch: ' + name)
if (root / DEBIAN / 'platform').read_text().splitlines() != ['bullseye', 'arm64']:
raise ValueError('Unsupported package catalog')
objects = {}
stanzas = []
for text, prefix, base, hashes in [
((root / DEBIAN / 'repo/Packages').read_text(), 'debian', DEBIAN + '/repo', {k.removeprefix('repo/'):v for k,v in sums.items() if k.endswith('.deb')}),
((root / 'third_party/node/Packages').read_text(), 'node', 'third_party/node', {k.removeprefix('node/'):v for k,v in runtime.items() if k.startswith('node/')}),
]:
for stanza in text.strip().split('\n\n'):
fields = dict(line.split(': ', 1) for line in stanza.splitlines() if ': ' in line and not line.startswith(' '))
name = safe_path(fields['Filename'].removeprefix('./'))
digest = fields['SHA256']
if hashes.get(name) != digest:
raise ValueError('Package index not covered by SHA256SUMS: ' + name)
logical = prefix + '/' + name
objects[logical] = {'path': base + '/' + name, 'sha256': digest, 'size': int(fields['Size'])}
stanzas.append(re.sub(r'^Filename: .*$', 'Filename: ' + logical, stanza, flags=re.M))
for name, digest in runtime.items():
objects['third_party/' + name] = {'path': 'third_party/' + name, 'sha256': digest}
digest = manifest(root / 'stage_itscreen/itscreen.sha256')['itscreen']
objects['stage_itscreen/itscreen'] = {'path': 'stage_itscreen/itscreen', 'sha256': digest}
return '\n\n'.join(stanzas) + '\n\n', objects
def activate(root):
platform_check()
root = Path(root).resolve()
source = json.loads((root / '.iomatex-source.json').read_text())
repo_name('https://' + HOST + '/' + source['repo'])
raw_endpoint('probe', source['commit'])
auth_from_env() # fail before modifying APT if reboot credentials are missing
text, objects = catalog(root)
STATE.mkdir(parents=True, exist_ok=True)
(STATE / 'Packages').write_text(text)
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
write_json(STATE / 'source.json', {'repo':source['repo'], 'commit':source['commit'], 'objects':objects})
owner = Path('/usr/local/lib/iomatex')
owner.mkdir(parents=True, exist_ok=True)
shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py')
method = Path('/usr/lib/apt/methods/iomatex')
method.write_text('#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/iomatex/git_delivery.py apt-method\n')
method.chmod(0o755)
CACHE.mkdir(parents=True, exist_ok=True)
(CACHE / 'partial').mkdir(exist_ok=True)
apt = Path('/etc/apt')
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.it-screen.com/ ./\n')
(apt / 'apt.conf.d/99iomatex-offline').write_text(
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
'Dir::Etc::sourceparts "-";\n'
'Dir::Cache::archives "/userdata/iomatex-apt-cache/";\n'
'APT::Install-Recommends "false";\nAPT::Install-Suggests "false";\nAcquire::Languages "none";\n'
'APT::Keep-Downloaded-Packages "false";\nBinary::apt-get::APT::Keep-Downloaded-Packages "false";\n'
'DPkg::Post-Invoke { "rm -f /userdata/iomatex-apt-cache/*.deb /userdata/iomatex-apt-cache/partial/*.deb"; };\n')
cleanup()
print('Git-only APT ready; payloads downloaded on demand:', source['commit'], flush=True)
def cleanup():
CACHE.mkdir(parents=True, exist_ok=True)
with (CACHE / 'lock').open('a') as lock:
try: fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError: return
for folder in [CACHE, CACHE / 'partial']:
if folder.exists():
for p in folder.iterdir():
if p.is_file() and p.name != 'lock': p.unlink()
def download_object(config, key, dest, auth):
entry = config['objects'].get(key)
if entry is None:
raise FileNotFoundError('Object absent from the pinned Git catalog')
path = Path(dest)
digest = hashlib.sha256()
size = 0
try:
with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), auth) as response, path.open('wb') as output:
while True:
chunk = response.read(1024 * 1024)
if not chunk: break
output.write(chunk)
digest.update(chunk)
size += len(chunk)
if digest.hexdigest() != entry['sha256'] or ('size' in entry and size != entry['size']):
raise ValueError('Git payload checksum or size mismatch')
except BaseException:
path.unlink(missing_ok=True)
raise
return digest.hexdigest(), size
def message(code, fields):
print(code)
for k, v in fields.items():
print(k + ': ' + str(v).replace('\n', ' ').replace('\r', ' '))
print('', flush=True)
def apt_key(uri, objects):
u = urllib.parse.urlparse(uri)
if u.scheme != 'iomatex' or u.netloc != HOST or u.query or u.fragment:
raise ValueError('Unsupported APT source')
# APT's method protocol may already decode the URI displayed by apt-get.
# Preserve literal %3a in Git filenames; never decode it twice into an epoch colon.
for path in (u.path, urllib.parse.unquote(u.path)):
key = safe_path(path.lstrip('/'))
if key in ('Packages', 'Packages.gz') or key in objects:
return key
raise FileNotFoundError('File absent from the pinned Git catalog')
def apt_method():
def stopped(signum, frame):
raise SystemExit(0)
signal.signal(signal.SIGINT, stopped)
signal.signal(signal.SIGTERM, stopped)
config = json.loads((STATE / 'source.json').read_text())
auth = auth_from_env()
# APT launches this helper as root; read private credentials before dropping privileges.
if os.geteuid() == 0:
user = pwd.getpwnam('_apt')
os.setgroups([])
os.setgid(user.pw_gid)
os.setuid(user.pw_uid)
message('100 Capabilities', {'Version':'1.0', 'Single-Instance':'true', 'Pipeline':'false', 'Send-Config':'false'})
while True:
first = sys.stdin.readline()
if not first: return
if not first.strip(): continue
fields = {}
while True:
line = sys.stdin.readline().rstrip('\n')
if not line: break
k, _, value = line.partition(': ')
fields[k] = value
if not first.startswith('600 '): continue
uri, filename = fields.get('URI', ''), fields.get('Filename', '')
try:
key = apt_key(uri, config['objects'])
message('200 URI Start', {'URI':uri})
if key in ('Packages', 'Packages.gz'):
data = (STATE / key).read_bytes()
Path(filename).write_bytes(data)
digest, size = hashlib.sha256(data).hexdigest(), len(data)
else:
digest, size = download_object(config, key, filename, auth)
message('201 URI Done', {'URI':uri, 'Filename':filename, 'Size':size, 'SHA256-Hash':digest})
except Exception as e:
# Never print authenticated URLs, response bodies, or credentials.
message('400 URI Failure', {'URI':uri, 'Message':type(e).__name__ + ': Git download failed or object absent'})
def main():
cmd = sys.argv[1]
if cmd == 'bootstrap': bootstrap(*sys.argv[2:])
elif cmd == 'activate': activate(sys.argv[2])
elif cmd == 'cleanup': cleanup()
elif cmd == 'fetch':
download_object(json.loads((STATE / 'source.json').read_text()), sys.argv[2], sys.argv[3], auth_from_env())
elif cmd == 'apt-method': apt_method()
else: raise ValueError('Unknown command')
if __name__ == '__main__':
try: main()
except Exception as error:
print('Iomatex Git delivery failed: ' + type(error).__name__ + ': ' + str(error), file=sys.stderr)
sys.exit(1)