151 lines
7.5 KiB
Python
151 lines
7.5 KiB
Python
"""Versioned runtime/UI update over an exact qualified Node package.
|
|
|
|
Preserves every OS integration, dependency and preparation payload from the
|
|
predecessor. Only the executable, version and provenance can change.
|
|
"""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from node_package_delta import parts
|
|
|
|
REPO = Path(__file__).resolve().parents[3]
|
|
sys.path.insert(0, str(REPO / "scripts/packaging"))
|
|
from debian import package # noqa: E402
|
|
from qualified_payloads import QualifiedPayloads # noqa: E402
|
|
|
|
|
|
def verify_embedded_ui(executable):
|
|
built = REPO / "apps/node-agent/ui/dist"
|
|
embedded = REPO / "apps/node-agent/web/dist"
|
|
|
|
def files(root):
|
|
return {str(p.relative_to(root)): p for p in root.rglob("*") if p.is_file()}
|
|
expected, actual = files(built), files(embedded)
|
|
if not expected or expected.keys() != actual.keys():
|
|
raise ValueError("Built and embedded Node UI inventories differ; sync UI before compiling")
|
|
for name, source in expected.items():
|
|
if (hashlib.sha256(source.read_bytes()).digest()
|
|
!= hashlib.sha256(actual[name].read_bytes()).digest()):
|
|
raise ValueError("Built and embedded Node UI differ: " + name)
|
|
# Go embed stores these bytes verbatim. Detect a binary compiled before the
|
|
# UI was copied, even when both source directories have since been synced.
|
|
index = expected["index.html"].read_bytes()
|
|
entries = re.findall(rb'<script[^>]+src="([^"]+\.js)"', index)
|
|
if not entries or index not in executable:
|
|
raise ValueError("Executable does not embed the built Node UI index")
|
|
for entry in entries:
|
|
path = entry.decode().removeprefix("/").removeprefix("./")
|
|
if path not in expected or expected[path].read_bytes() not in executable:
|
|
raise ValueError("Executable does not embed the built Node UI entry")
|
|
|
|
|
|
def build(base, base_sha, binary, version, output, uplink=False, vesc_evidence=False):
|
|
if output.exists():
|
|
raise FileExistsError("Published releases are immutable")
|
|
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*", version):
|
|
raise ValueError("Invalid version")
|
|
with QualifiedPayloads(base.parent, REPO / 'apps/node-agent/build', REPO).locked() as store:
|
|
raw = store.read(base.name)
|
|
if hashlib.sha256(raw).hexdigest() != base_sha:
|
|
raise ValueError("Qualified predecessor changed")
|
|
archives = parts(raw)
|
|
executable = binary.read_bytes()
|
|
if executable[:6] != b"\x7fELF\x02\x01" or executable[18:20] != b"\x3e\x00":
|
|
raise ValueError("Expected Linux amd64 executable")
|
|
verify_embedded_ui(executable)
|
|
provenance_path = "usr/share/doc/mission-core-node/provenance.json"
|
|
previous = dict((n, d) for n, d, _ in archives["data.tar.gz"])
|
|
sources = {}
|
|
for folder in (
|
|
"apps/node-agent/internal", "apps/node-agent/ui/src", "apps/node-agent/web/dist",
|
|
"packages/router-ui/src", "packages/sensor-ui/src",
|
|
):
|
|
for path in sorted((REPO / folder).rglob("*")):
|
|
if path.is_file():
|
|
sources[str(path.relative_to(REPO))] = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
provenance = dict(schema="missioncore.node.runtime-revision/v1", version=version,
|
|
predecessor_sha256=base_sha,
|
|
predecessor=json.loads(previous[provenance_path]),
|
|
binary_sha256=hashlib.sha256(executable).hexdigest(), sources=sources)
|
|
changes = {"usr/lib/mission-core-node/node-agent": executable,
|
|
provenance_path: (json.dumps(provenance, indent=2) + "\n").encode()}
|
|
if vesc_evidence:
|
|
# A diagnostic-only revision must prove that executable statements outside
|
|
# this one trace call are identical to the qualified motor controller.
|
|
import ast
|
|
|
|
target = "usr/lib/mission-core-vesc/runtime/remote_control.py"
|
|
source = REPO / "plugins/vesc/runtime/remote_control.py"
|
|
desired = source.read_bytes()
|
|
|
|
class WithoutLeaseTrace(ast.NodeTransformer):
|
|
def visit_Expr(self, node):
|
|
call = node.value
|
|
if (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
|
and ast.unparse(call.func) == "self.trace.add" and call.args
|
|
and isinstance(call.args[0], ast.Constant)
|
|
and call.args[0].value == "lease_expired"):
|
|
return ast.Pass()
|
|
return self.generic_visit(node)
|
|
|
|
def authority(raw):
|
|
return ast.dump(WithoutLeaseTrace().visit(ast.parse(raw)), include_attributes=False)
|
|
|
|
if authority(previous[target]) != authority(desired):
|
|
raise ValueError("VESC change exceeds diagnostic trace fields")
|
|
changes[target] = desired
|
|
sources[str(source.relative_to(REPO))] = hashlib.sha256(desired).hexdigest()
|
|
provenance["vesc_evidence_only"] = True
|
|
changes[provenance_path] = (json.dumps(provenance, indent=2) + "\n").encode()
|
|
if uplink:
|
|
packaging = REPO / 'apps/node-agent/packaging'
|
|
for path in [packaging / 'uplink_helper.py', packaging / 'qualify_uplink_namespace.py',
|
|
*sorted((packaging / 'uplink').glob('*.py'))]:
|
|
name = 'usr/lib/mission-core-node/' + str(path.relative_to(packaging))
|
|
changes[name] = path.read_bytes()
|
|
sources[str(path.relative_to(REPO))] = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
provenance['scope'] = ('Runtime and reversible NetBird uplink routing; '
|
|
'qualified predecessor retained')
|
|
changes[provenance_path] = (json.dumps(provenance, indent=2) + '\n').encode()
|
|
controls = []
|
|
changed_controls = ['control']
|
|
for name, data, mode in archives["control.tar.gz"]:
|
|
if name == "control":
|
|
data, count = re.subn(rb"(?m)^Version: [^\n]+$", b"Version: " + version.encode(), data)
|
|
assert count == 1
|
|
if uplink and name == 'prerm':
|
|
replacement = (REPO / 'apps/node-agent/packaging/prerm').read_bytes()
|
|
if replacement != data:
|
|
changed_controls.append(name)
|
|
data = replacement
|
|
controls.append((name, data, mode))
|
|
payload = [(n, changes.get(n, d), m) for n, d, m in archives["data.tar.gz"]]
|
|
payload += [(n, d, 0o644) for n, d in changes.items() if n not in previous]
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
with output.open("xb") as stream:
|
|
stream.write(package(controls, payload))
|
|
report = dict(version=version, base_sha256=base_sha, bytes=output.stat().st_size,
|
|
sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
|
|
changed_controls=changed_controls, changed_payloads=list(changes))
|
|
output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n")
|
|
return report
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--base", type=Path, required=True)
|
|
parser.add_argument("--base-sha256", required=True)
|
|
parser.add_argument("--binary", type=Path, required=True)
|
|
parser.add_argument("--version", required=True)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
parser.add_argument('--uplink', action='store_true')
|
|
parser.add_argument('--vesc-evidence', action='store_true')
|
|
args = parser.parse_args()
|
|
print(json.dumps(build(args.base, args.base_sha256, args.binary, args.version, args.output,
|
|
uplink=args.uplink, vesc_evidence=args.vesc_evidence)))
|