Quote the release code name and ship the Cockpit update page

This commit is contained in:
Archipelago 2026-11-16 21:43:51 +03:00
parent d1c924d653
commit 4100d76100
3 changed files with 342 additions and 2 deletions

View file

@ -25,3 +25,226 @@ Container Runner defaults
- qemu-user-static binfmt registrations are enabled for foreign-architecture images.
- Container data is workload state in /var; OS updates and rollback do not remove it.
EOF
# Cockpit update page (D-100). It is a D-Bus client of archipelagod: no
# PackageKit, no pacman, no shell command and no second deployment writer.
updates="$pkg/runtime/usr/share/cockpit/archipelago-updates"
mkdir -p "$updates"
cat > "$updates/manifest.json" <<'EOF'
{
"version": 0,
"tools": {
"archipelago-updates": {
"label": "Обновления ОС",
"path": "index.html"
}
}
}
EOF
cat > "$updates/index.html" <<'EOF'
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Archipelago · Обновления ОС</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Archipelago · Обновления ОС</h1>
<p id="daemon" class="muted">Проверка службы…</p>
</header>
<section id="state" class="card">
<dl>
<dt>Загруженная система</dt><dd id="booted">—</dd>
<dt>Следующая загрузка</dt><dd id="pending">—</dd>
<dt>Обновление</dt><dd id="update">—</dd>
</dl>
</section>
<section class="card">
<div class="actions">
<button id="refresh">Проверить обновления</button>
<button id="prepare" disabled>Подготовить план</button>
<button id="download" disabled>Загрузить</button>
<button id="stage" disabled>Применить</button>
</div>
<p id="progress" class="muted" aria-live="polite"></p>
<p id="error" class="error" hidden></p>
<p id="result" hidden></p>
</section>
<section class="card">
<h2>Изменения</h2>
<pre id="details" class="muted">Проверьте обновления, чтобы увидеть состав.</pre>
</section>
<script src="updates.js"></script>
</body>
</html>
EOF
cat > "$updates/style.css" <<'EOF'
:root { color-scheme: light dark; }
body { font-family: system-ui, sans-serif; margin: 0 auto; max-width: 56rem; padding: 1.5rem; }
h1 { font-size: 1.35rem; margin: 0 0 .35rem; }
h2 { font-size: 1rem; margin: 0 0 .5rem; }
.card { border: 1px solid color-mix(in srgb, currentColor 20%, transparent); border-radius: .6rem; padding: 1rem; margin: 1rem 0; }
dl { display: grid; grid-template-columns: max-content 1fr; gap: .25rem 1rem; margin: 0; }
dt { font-weight: 600; }
.muted { opacity: .75; }
.error { color: #c0392b; white-space: pre-wrap; }
.actions { display: flex; flex-wrap: wrap; gap: .5rem; }
button { padding: .45rem .9rem; border-radius: .45rem; cursor: pointer; }
button:disabled { cursor: not-allowed; opacity: .5; }
pre { white-space: pre-wrap; max-height: 22rem; overflow: auto; margin: 0; }
EOF
cat > "$updates/updates.js" <<'EOF'
"use strict";
// The page is a typed D-Bus client only. It never shells out and never claims an
// update is installed before the daemon reports a staged deployment.
const MANAGER = "/org/archipelago/System1";
const MANAGER_IFACE = "org.archipelago.System1.Manager";
const TRANSACTION_IFACE = "org.archipelago.System1.Transaction";
const bus = cockpit.dbus("org.archipelago.System1", { bus: "system", superuser: "try" });
const $ = id => document.getElementById(id);
let busy = false;
let planId = null;
let target = null;
function uuid() {
if (window.crypto && crypto.randomUUID) { return crypto.randomUUID(); }
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
return hex.slice(0, 8) + "-" + hex.slice(8, 12) + "-" + hex.slice(12, 16) + "-" +
hex.slice(16, 20) + "-" + hex.slice(20);
}
function options(extra) {
return Object.assign({ interactive: true, request_id: uuid() }, extra || {});
}
async function call(method, args) {
const reply = await bus.call(MANAGER, MANAGER_IFACE, method, args || []);
return reply[0];
}
function showError(text) {
$("error").hidden = !text;
$("error").textContent = text || "";
}
function setBusy(value) {
busy = value;
for (const id of ["refresh", "prepare", "download", "stage"]) {
$(id).disabled = value || ($(id).dataset.ready !== "yes");
}
}
function label(state) {
return ({ current: "Система актуальна", available: "Доступно обновление",
downloaded: "Файлы загружены", staged: "Готово к перезагрузке",
"no-change": "Изменений нет", reconciled: "Проверка результата" })[state] || state || "—";
}
async function refreshStatus() {
try {
const status = await call("GetStatus");
$("daemon").textContent = "Служба archipelagod доступна (D-Bus, system bus)";
$("booted").textContent = (status.booted && status.booted.deployment_id) || "—";
$("pending").textContent = (status.pending && status.pending.deployment_id) || "нет";
$("update").textContent = label(status.update && status.update.state);
} catch (error) {
$("daemon").textContent = "Служба archipelagod недоступна; состояние системы неизвестно";
showError("D-Bus: " + error);
}
}
async function waitTransaction(path, caption) {
for (;;) {
const [snapshot] = await bus.call(path, TRANSACTION_IFACE, "GetSnapshot", []);
const progress = snapshot.Progress || {};
const percent = typeof progress.percent === "number" ? progress.percent + "% · " : "";
$("progress").textContent = caption + ": " + percent + (progress.message || snapshot.Phase || "");
const state = snapshot.State;
if (state === "succeeded") { $("progress").textContent = caption + ": готово"; return snapshot.Result || {}; }
if (state === "failed" || state === "cancelled" || state === "interrupted") {
const description = snapshot.Error && (snapshot.Error.message || snapshot.Error.code);
throw new Error(caption + ": " + (description || state));
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
async function run(method, args, caption) {
const path = await call(method, args);
return waitTransaction(path, caption);
}
async function check() {
showError("");
setBusy(true);
$("result").hidden = true;
try {
const refreshed = await run("Refresh", [options({ force: true })], "Проверка обновлений");
target = refreshed.target || null;
$("update").textContent = label(refreshed.state);
planId = null;
$("prepare").dataset.ready = target && refreshed.state !== "current" ? "yes" : "no";
$("download").dataset.ready = "no";
$("stage").dataset.ready = "no";
if (target && refreshed.state !== "current") {
const details = await call("GetUpdateDetails", [target, options()]);
$("details").textContent = JSON.stringify(details.plan || details, null, 2);
} else {
$("details").textContent = "Система актуальна: новых образов нет.";
}
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
async function prepare() {
showError("");
setBusy(true);
try {
const plan = await run("PrepareUpdate", [target, options()], "Подготовка плана");
planId = plan.plan_id || null;
$("details").textContent = JSON.stringify(plan.plan || plan, null, 2);
$("download").dataset.ready = planId ? "yes" : "no";
$("stage").dataset.ready = planId ? "yes" : "no";
$("prepare").dataset.ready = "no";
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
async function download() {
showError("");
setBusy(true);
try {
await run("Download", [planId, options()], "Загрузка");
$("download").dataset.ready = "no";
$("stage").dataset.ready = "yes";
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
async function stage() {
showError("");
setBusy(true);
try {
const staged = await run("Stage", [planId, options()], "Применение");
$("result").hidden = false;
$("result").textContent = staged.outcome === "no-change"
? "Изменений нет."
: "Изменения подготовлены. Они вступят в силу после перезагрузки; перезагрузка выполняется вручную.";
$("stage").dataset.ready = "no";
await refreshStatus();
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
$("refresh").dataset.ready = "yes";
$("refresh").addEventListener("click", check);
$("prepare").addEventListener("click", prepare);
$("download").addEventListener("click", download);
$("stage").addEventListener("click", stage);
setBusy(false);
refreshStatus();
EOF
cat > "$pkg/runtime/usr/share/archipelago/container-runner/cockpit-updates" <<'EOF'
The Cockpit page /usr/share/cockpit/archipelago-updates is a typed client of
org.archipelago.System1 on the system bus (GetStatus, Refresh, GetUpdateDetails,
PrepareUpdate, Download, Stage, Transaction.GetSnapshot). It never uses
PackageKit, pacman, shell commands or a second deployment writer. Stage only
prepares the next boot; the operator reboots explicitly.
EOF

View file

@ -75,9 +75,14 @@ ID=archipelago
ID_LIKE=arch
PRETTY_NAME="Archipelago Core Tesseract"
VERSION="Tesseract"
VERSION_ID=Tesseract
VERSION_CODENAME=tesseract
VERSION_ID="Tesseract"
VERSION_CODENAME="tesseract"
EOF
# Release assets must keep the code name quoted everywhere; an unquoted value is
# accepted by systemd but breaks consumers that compare the raw field text.
grep -qx 'VERSION="Tesseract"' "$pkg/runtime/usr/lib/archipelago/defaults/os-release"
grep -qx 'VERSION_ID="Tesseract"' "$pkg/runtime/usr/lib/archipelago/defaults/os-release"
grep -qx 'VERSION_CODENAME="tesseract"' "$pkg/runtime/usr/lib/archipelago/defaults/os-release"
printf 'LANG=C.UTF-8\n' > "$pkg/runtime/usr/lib/archipelago/defaults/locale.conf"
printf 'KEYMAP=us\nFONT=ter-v24b\n' > "$pkg/runtime/usr/lib/archipelago/defaults/vconsole.conf"
cat > "$pkg/runtime/usr/lib/archipelago/defaults/kmscon.conf" <<'EOF'
@ -219,10 +224,34 @@ When = PreTransaction
Exec = /usr/bin/test ! -e /run/ostree-booted
AbortOnFail
EOF
cat > "$pkg/runtime/usr/lib/systemd/system/archipelago-ostree-gc.service" <<'EOF'
[Unit]
Description=Collect unreachable OSTree objects
ConditionPathExists=/run/ostree-booted
ConditionPathExists=!/run/archipelago-live
After=ostree-finalize-staged.service local-fs.target
[Service]
Type=oneshot
ExecStart=/usr/bin/archipelago cleanup apply
Nice=10
IOSchedulingClass=idle
EOF
cat > "$pkg/runtime/usr/lib/systemd/system/archipelago-ostree-gc.timer" <<'EOF'
[Unit]
Description=Periodic OSTree object collection
[Timer]
OnBootSec=30min
OnCalendar=weekly
RandomizedDelaySec=20min
Persistent=true
[Install]
WantedBy=timers.target
EOF
cat > "$pkg/runtime/usr/lib/systemd/system-preset/20-archipelago.preset" <<'EOF'
enable archipelago-firstboot@tty1.service
enable archipelago-keyring.service
enable archipelago-ssh-keys.service
enable archipelago-ostree-gc.timer
enable ostree-remount.service
enable systemd-networkd.service
enable systemd-resolved.service

88
tests/cockpit_updater.py Normal file
View file

@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Contract checks for the Container Runner Cockpit update page.
The page is packaged as plain files inside the Purpose layer, so its only
executable contract is the typed D-Bus surface it uses. This test reads the
adapter that writes those files and rejects a page that would bypass the daemon.
"""
import json
import re
import subprocess
import unittest
from pathlib import Path
ADAPTER = Path(__file__).parents[1] / 'adapters/container-runner-package.sh'
PREFIX = 'usr/share/cockpit/archipelago-updates/'
REQUIRED = ['GetStatus', 'Refresh', 'GetUpdateDetails', 'PrepareUpdate', 'Download',
'Stage', 'GetSnapshot', 'org.archipelago.System1']
FORBIDDEN = ['packagekit', 'PackageKit', 'pacman', 'systemctl', 'cockpit.spawn', 'cockpit.job',
'pkcon', 'rpm-ostree']
def heredocs(text):
files = {}
current = None
body = []
for line in text.splitlines():
if current is None:
match = re.match(r"cat > \"\$pkg/runtime/(\S+)\" <<'EOF'$", line)
if match:
current = match.group(1)
body = []
continue
if line == 'EOF':
files[current] = '\n'.join(body) + '\n'
current = None
continue
body.append(line)
return files
class CockpitUpdater(unittest.TestCase):
def setUp(self):
# The adapter writes the page through a $updates shorthand; expand it so the
# packaged paths can be asserted exactly.
self.text = ADAPTER.read_text().replace(
'"$updates/', '"$pkg/runtime/usr/share/cockpit/archipelago-updates/')
self.files = heredocs(self.text)
self.updates = {name[len(PREFIX):]: body for name, body in self.files.items()
if name.startswith(PREFIX)}
def test_page_is_packaged_with_a_valid_manifest(self):
self.assertEqual(sorted(self.updates), ['index.html', 'manifest.json', 'style.css', 'updates.js'])
manifest = json.loads(self.updates['manifest.json'])
self.assertEqual(manifest['version'], 0)
tools = manifest['tools']
self.assertEqual(len(tools), 1)
entry = next(iter(tools.values()))
self.assertEqual(entry['path'], 'index.html')
self.assertIn('style.css', self.updates['index.html'])
for control in ('refresh', 'prepare', 'download', 'stage'):
self.assertIn(f'id="{control}"', self.updates['index.html'], control)
self.assertIn('updates.js', self.updates['index.html'])
def test_page_is_a_typed_dbus_client(self):
script = self.updates['updates.js']
for name in REQUIRED:
self.assertIn(name, script, name)
self.assertIn('superuser', script)
self.assertIn('request_id', script)
self.assertIn('interactive', script)
# The staged result is reported as pending, never as installed.
self.assertIn('после перезагрузки', script)
self.assertNotIn('location.reload', script)
for token in FORBIDDEN:
self.assertNotIn(token, script.lower() if token.islower() else script, token)
def test_page_does_not_shell_out_and_adapter_stays_valid(self):
for name, body in self.updates.items():
for token in FORBIDDEN:
self.assertNotIn(token, body, f'{name}: {token}')
result = subprocess.run(['bash', '-n', str(ADAPTER)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
# The page is written only by the Container Runner Purpose adapter.
self.assertEqual(self.text.count(PREFIX), len(self.updates))
if __name__ == '__main__':
unittest.main()