Add staged kernel arguments and explicit CLI output contracts

This commit is contained in:
Pavel Isaev 2026-11-09 16:55:42 +03:00
parent 3c630f5705
commit 382e670547
13 changed files with 579 additions and 30 deletions

View file

@ -0,0 +1,116 @@
"""Private read/transform adapter using libostree; never edits boot entries.
The Rust service owns authorization, locking, durable intent and staged deployment.
"""
import ctypes as C
import json
import sys
ostree = C.CDLL('libostree-1.so.1')
glib = C.CDLL('libglib-2.0.so.0')
gobject = C.CDLL('libgobject-2.0.so.0')
P = C.c_void_p
S = C.c_char_p
def bind(lib, name, result, *args):
f = getattr(lib, name)
f.restype, f.argtypes = result, list(args)
return f
class Error(C.Structure):
_fields_ = [('domain', C.c_uint), ('code', C.c_int), ('message', S)]
class Array(C.Structure):
_fields_ = [('pdata', C.POINTER(P)), ('len', C.c_uint)]
def checked(f, *args):
error = C.POINTER(Error)()
if not f(*args, C.byref(error)):
message = error.contents.message.decode() if error else 'libostree operation failed'
if error:
bind(glib, 'g_error_free', None, P)(error)
raise ValueError(message)
def arguments(options, changes):
kargs = bind(ostree, 'ostree_kernel_args_from_string', P, S)(options)
try:
for change in changes:
op, arg = change['op'], change['argument']
if not arg or len(arg) > 4096 or any(c in arg for c in '\x00\r\n') or arg.split('=', 1)[0] == 'ostree':
raise ValueError('Invalid kernel argument or protected ostree selector')
# Native operations split their input again. Validate the complete
# token, not only its first key, before passing it to libostree.
if arg.count('"') % 2 or arguments(arg.encode(), []) != [arg]:
raise ValueError('Expected exactly one kernel argument with balanced quotes')
if op in ('append', 'append-if-missing'):
name = 'ostree_kernel_args_' + op.replace('-', '_')
bind(ostree, name, None, P, S)(kargs, arg.encode())
elif op in ('delete', 'delete-if-present', 'replace'):
name = 'ostree_kernel_args_' + ('new_replace' if op == 'replace' else op.replace('-', '_'))
checked(bind(ostree, name, C.c_int, P, S, C.POINTER(C.POINTER(Error))), kargs, arg.encode())
else:
raise ValueError('Unknown kernel argument operation')
vector = bind(ostree, 'ostree_kernel_args_to_strv', C.POINTER(S), P)(kargs)
try:
result, i = [], 0
while vector[i] is not None:
token = vector[i].decode()
if token.split('=', 1)[0] != 'ostree':
result.append(token)
i += 1
return result
finally:
bind(glib, 'g_strfreev', None, C.POINTER(S))(vector)
finally:
bind(ostree, 'ostree_kernel_args_free', None, P)(kargs)
def snapshot(changes):
root = bind(ostree, 'ostree_sysroot_new_default', P)()
try:
checked(bind(ostree, 'ostree_sysroot_load', C.c_int, P, P, C.POINTER(C.POINTER(Error))), root, None)
booted = bind(ostree, 'ostree_sysroot_get_booted_deployment', P, P)(root)
deployments = bind(ostree, 'ostree_sysroot_get_deployments', C.POINTER(Array), P)(root)
try:
result = []
options_by_id = {}
for index in range(deployments.contents.len):
d = deployments.contents.pdata[index]
osname = bind(ostree, 'ostree_deployment_get_osname', S, P)(d).decode()
if osname != 'archipelago':
continue
checksum = bind(ostree, 'ostree_deployment_get_csum', S, P)(d).decode()
serial = bind(ostree, 'ostree_deployment_get_deployserial', C.c_int, P)(d)
config = bind(ostree, 'ostree_deployment_get_bootconfig', P, P)(d)
if not config:
raise ValueError('Deployment boot configuration unavailable')
options = bind(ostree, 'ostree_bootconfig_parser_get', S, P, S)(config, b'options')
if options is None:
raise ValueError('Deployment kernel arguments unavailable')
result.append(dict(deployment_id=f'{osname}/{checksum}.{serial}', checksum=checksum,
booted=d == booted, staged=bool(bind(ostree, 'ostree_deployment_is_staged', C.c_int, P)(d)),
arguments=arguments(options, [])))
options_by_id[result[-1]['deployment_id']] = options
if changes is not None:
selected = next((d for d in result if d['staged']), None) or next((d for d in result if d['booted']), None)
if selected is None:
raise ValueError('No booted deployment')
selected['edited'] = arguments(options_by_id[selected['deployment_id']], changes)
return result
finally:
bind(glib, 'g_ptr_array_unref', None, C.POINTER(Array))(deployments)
finally:
bind(gobject, 'g_object_unref', None, P)(root)
if __name__ == '__main__':
try:
print(json.dumps(snapshot(json.loads(sys.argv[1]) if len(sys.argv) > 1 else None)))
except Exception as error:
print(str(error), file=sys.stderr)
sys.exit(1)

View file

@ -47,4 +47,8 @@
<description>Change Managed Overlays</description><message>Authorization is required to change the ordered overlay selection</message>
<defaults><allow_any>auth_admin</allow_any><allow_inactive>auth_admin</allow_inactive><allow_active>auth_admin_keep</allow_active></defaults>
</action>
<action id="org.archipelago.system.kernel-arguments">
<description>Change kernel arguments</description><message>Authorization is required to prepare kernel arguments for the next boot</message>
<defaults><allow_any>auth_admin</allow_any><allow_inactive>auth_admin</allow_inactive><allow_active>auth_admin_keep</allow_active></defaults>
</action>
</policyconfig>

View file

@ -9,7 +9,7 @@ use zbus::{Connection, message::{Header, Flags}};
#[serde(rename_all = "kebab-case")]
pub enum Action {
Refresh, Download, StageUpdate, Cancel, ReadLogs, ExtensionEnable,
ExtensionChange, ExtensionLocal, ExtensionOverride, ExtensionRestore, OverlayChange,
ExtensionChange, ExtensionLocal, ExtensionOverride, ExtensionRestore, OverlayChange, KernelArguments,
}
impl Action {
pub(crate) fn id(self) -> &'static str {
@ -25,6 +25,7 @@ impl Action {
Self::ExtensionOverride => "org.archipelago.system.extension-override",
Self::ExtensionRestore => "org.archipelago.system.extension-restore",
Self::OverlayChange => "org.archipelago.system.overlay-change",
Self::KernelArguments => "org.archipelago.system.kernel-arguments",
}
}
}

View file

@ -2,7 +2,7 @@
use super::{Dictionary, text};
use archipelago_contracts::system_bus::{BUS_NAME, MANAGER_PATH, MANAGER_INTERFACE};
use serde_json::{json, Value};
use std::{fs, time::{Duration, Instant}};
use std::{cell::RefCell, fs, io::IsTerminal, time::{Duration, Instant}};
use zbus::{blocking::{Connection, Proxy}, proxy::MethodFlags, zvariant::{OwnedObjectPath, Value as Variant}};
fn error(e: impl std::fmt::Display) -> String { e.to_string() }
@ -30,7 +30,7 @@ fn map(fields: Dictionary) -> Result<Value,String> {
.collect::<Result<serde_json::Map<_,_>,_>>().map(Value::Object)
}
struct Client { connection: Connection, interactive: bool, offline: bool, request_id: String }
struct Client { connection: Connection, interactive: bool, offline: bool, request_id: String, output: RefCell<super::client_output::Output> }
impl Client {
fn proxy(&self, packages: bool) -> Result<Proxy<'_>,String> {
Proxy::new(&self.connection,BUS_NAME,if packages {"/org/archipelago/System1/HostExtensions"} else {MANAGER_PATH},
@ -51,13 +51,13 @@ impl Client {
let flags = if self.interactive { MethodFlags::AllowInteractiveAuth.into() } else { Default::default() };
let path: OwnedObjectPath = proxy.call_with_flags(method,flags,body).map_err(error)?.ok_or("Missing operation reply")?;
let id = path.as_str().rsplit('/').next().and_then(|p| p.strip_prefix("op_")).ok_or("Invalid operation object path")?;
eprintln!("Operation: {id}; retry token: {}", self.request_id);
self.output.borrow_mut().record("operation", &json!({"operation_id":id,"request_id":self.request_id,"method":method}));
self.wait(id)
}
fn wait(&self, id: &str) -> Result<Value,String> {
if !archipelago_contracts::system_bus::operation_id(id) { return Err("Invalid operation identity".into()); }
let deadline = Instant::now() + Duration::from_secs(4*3600);
let mut previous = String::new();
let mut revision = None;
let mut failures = 0;
loop {
let observed = (|| {
@ -75,16 +75,37 @@ impl Client {
}
};
let phase = snapshot["Phase"].as_str().unwrap_or("unknown");
if phase != previous { eprintln!("{phase}: {}",snapshot["Progress"]["message"].as_str().unwrap_or("")); previous = phase.into(); }
if revision != snapshot["Revision"].as_u64() {
self.output.borrow_mut().record("snapshot", &snapshot);
revision = snapshot["Revision"].as_u64();
}
self.output.borrow_mut().progress(phase);
if matches!(snapshot["State"].as_str(), Some("succeeded" | "failed" | "cancelled" | "interrupted")) && self.output.borrow().debug {
match self.logs(id) {
Ok(logs) => self.output.borrow_mut().record("service-log", &logs),
Err(e) => self.output.borrow_mut().record("service-log-unavailable", &json!({"message":e})),
}
}
match snapshot["State"].as_str() {
Some("succeeded") => return Ok(snapshot["Result"].clone()),
Some("failed" | "cancelled" | "interrupted") => return Err(format!("Operation {id}: {}",snapshot["Error"])),
Some("failed" | "cancelled" | "interrupted") => return Err(snapshot["Error"].to_string()),
_ => (),
}
if Instant::now() >= deadline { return Err(format!("Stopped waiting; operation {id} continues. Use archipelago transaction wait {id}")); }
std::thread::sleep(Duration::from_millis(500));
}
}
fn logs(&self, id: &str) -> Result<Value, String> {
let mut cursor = String::new();
let mut lines = Vec::new();
loop {
let page = self.dispatch(&["transaction", "log", id, &cursor])?;
lines.extend(page["lines"].as_array().ok_or("Invalid log page")?.iter().cloned());
cursor = page["next_cursor"].as_str().unwrap_or("").into();
if cursor.is_empty() || lines.len() >= 256 { break; }
}
Ok(json!({"operation_id":id,"lines":lines}))
}
fn query(&self, packages: bool, method: &str) -> Result<Value,String> {
map(self.proxy(packages)?.call(method,&()).map_err(error)?)
}
@ -94,11 +115,18 @@ impl Client {
}
fn stage(&self, plan: Value) -> Result<Value,String> {
let id = plan["plan_id"].as_str().ok_or("Missing prepared plan identity")?;
eprintln!("Checked plan {id}: {}",plan["plan"]);
self.output.borrow_mut().record("plan", &plan);
self.operation(false,"Stage",&(id,self.options()))
}
fn dispatch(&self, args: &[&str]) -> Result<Value,String> {
match args {
["kargs"] => self.query(false, "GetKernelArguments"),
["kargs", edits @ ..] => {
let changes = karg_edits(edits)?;
let state = self.query(false, "GetKernelArguments")?;
let context = state["context_id"].as_str().ok_or("Missing kernel arguments context")?;
self.operation(false, "ChangeKernelArguments", &(changes, context, self.options()))
}
["overlay", "status"] => {
let proxy = self.overlay_proxy()?;
self.operation_on(&proxy, "RefreshCatalog", &(self.options(),))?;
@ -279,7 +307,10 @@ mod overlay_tests {
}
pub fn dispatch(args: &[String]) -> Result<(),String> {
let mut interactive = false;
let json = args.iter().any(|a| a == "--json");
let debug = args.iter().any(|a| a == "--debug");
let output = RefCell::new(super::client_output::Output::new(json, debug)?);
let mut interactive = std::io::stdin().is_terminal() && !json;
let mut offline = false;
let mut request = fs::read_to_string("/proc/sys/kernel/random/uuid").map_err(error)?.trim().to_owned();
let mut positional = Vec::new();
@ -288,14 +319,71 @@ pub fn dispatch(args: &[String]) -> Result<(),String> {
match arg.as_str() {
"--interactive" => interactive = true,
"--offline" => offline = true,
"--json" => (),
"--json" | "--debug" => (),
"--non-interactive" => interactive = false,
"--request-id" => request = iter.next().ok_or("Missing request ID")?.clone(),
_ => positional.push(arg.as_str()),
}
}
if !archipelago_contracts::system_bus::request_id(&request) { return Err("Expected a UUID retry token".into()); }
let client = Client { connection:Connection::system().map_err(error)?,interactive,offline,request_id:request };
let result = client.dispatch(&positional)?;
println!("{}",serde_json::to_string_pretty(&result).map_err(error)?);
let client = Client { connection:Connection::system().map_err(error)?,interactive,offline,request_id:request,output };
client.output.borrow_mut().record("command", &json!({"arguments":args,"request_id":client.request_id}));
let result = match client.dispatch(&positional) {
Ok(result) => result,
Err(message) => {
let mut detail: Value = serde_json::from_str(&message).unwrap_or_else(|_| json!({"message":message}));
detail["log"] = json!(client.output.borrow().path);
client.output.borrow_mut().record("error", &detail);
return Err(detail.to_string());
}
};
client.output.borrow_mut().finish(&positional, &result);
Ok(())
}
pub fn command(args: &[String]) -> Option<&str> {
let mut iter = args.iter();
while let Some(arg) = iter.next() {
match arg.as_str() {
"--json" | "--debug" | "--interactive" | "--non-interactive" | "--offline" => (),
"--request-id" => { iter.next(); },
_ => return Some(arg),
}
}
None
}
pub fn report_error(args: &[String], message: &str) {
let detail: Value = serde_json::from_str(message).unwrap_or_else(|_| json!({"message":message}));
if args.iter().any(|a| a == "--json") { println!("{}", json!({"error":detail})); }
else if args.iter().any(|a| a == "--debug") { eprintln!("{}", json!({"error":detail})); }
else {
let ru = super::client_output::russian();
eprintln!("✗ {}", super::client_output::failure(detail["message"].as_str().unwrap_or(message), ru));
if let Some(path) = detail["log"].as_str() { eprintln!("{}: {path}", if ru {"Подробности"} else {"Details"}); }
}
}
pub fn error_exit_code(message: &str) -> u8 {
serde_json::from_str::<Value>(message).ok().and_then(|value|
serde_json::from_value::<archipelago_contracts::system_bus::ErrorCode>(value["code"].clone()).ok())
.map(|code| code.exit_code()).unwrap_or(1)
}
fn karg_edits(args: &[&str]) -> Result<Vec<Dictionary>, String> {
let mut result = Vec::new();
let mut iter = args.iter();
while let Some(arg) = iter.next() {
let (op, value) = match arg.split_once('=') {
Some((op, value)) => (op, value),
None => (*arg, *iter.next().ok_or("Missing kernel argument value")?),
};
let op = op.strip_prefix("--").ok_or("Expected --append, --append-if-missing, --delete, --delete-if-present or --replace")?;
if !["append", "append-if-missing", "delete", "delete-if-present", "replace"].contains(&op) {
return Err(format!("Unknown kargs option: {op}"));
}
result.push(Dictionary::from([("op".into(), text(op)), ("argument".into(), text(value))]));
}
if result.is_empty() { return Err("No kernel argument edits".into()); }
Ok(result)
}

View file

@ -0,0 +1,170 @@
//! Human CLI presentation and private diagnostic log; JSON stdout is one document.
use serde_json::{json, Value};
use std::{fs::{self, File}, io::{IsTerminal, Write}, os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, path::PathBuf, time::{Instant, SystemTime, UNIX_EPOCH}};
pub struct Output {
pub json: bool,
pub debug: bool,
ru: bool,
tty: bool,
phase: String,
start: Instant,
log: File,
pub path: PathBuf,
}
pub fn russian() -> bool {
["LC_ALL", "LC_MESSAGES", "LANG"].iter().filter_map(|key| std::env::var(key).ok())
.find(|value| !value.is_empty()).is_some_and(|value| value.starts_with("ru"))
}
impl Output {
pub fn new(json: bool, debug: bool) -> Result<Self, String> {
let directory = if let Some(path) = std::env::var_os("ARCHIPELAGO_LOG_DIR") { PathBuf::from(path) }
else if fs::metadata("/proc/self").is_ok_and(|m| m.uid() == 0) { PathBuf::from("/var/log/archipelago") }
else { std::env::var_os("XDG_STATE_HOME").map(PathBuf::from).or_else(||
std::env::var_os("HOME").map(|p| PathBuf::from(p).join(".local/state")))
.ok_or("No diagnostic log directory available")?.join("archipelago/logs") };
if !directory.is_absolute() { return Err("Diagnostic log directory must be absolute".into()); }
fs::DirBuilder::new().recursive(true).mode(0o700).create(&directory).map_err(|e| e.to_string())?;
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos();
let path = directory.join(format!("{stamp}-{}.log", std::process::id()));
let log = File::options().create_new(true).write(true).mode(0o600).open(&path).map_err(|e| e.to_string())?;
Ok(Self { json, debug, ru:russian(), tty:std::io::stderr().is_terminal() && !json && !debug,
phase:String::new(), start:Instant::now(), log, path })
}
pub fn record(&mut self, event: &str, data: &Value) {
let line = json!({"elapsed_ms":self.start.elapsed().as_millis(),"event":event,"data":data});
if let Err(error) = writeln!(self.log, "{line}") { eprintln!("Cannot write diagnostic log: {error}"); }
if self.debug { eprintln!("{line}"); }
}
pub fn progress(&mut self, phase: &str) {
if self.json || self.debug || matches!(phase, "admission" | "finished" | "unknown") { return; }
let message = phase_label(phase, self.ru);
if self.tty {
eprint!("\r\x1b[2K … {message} · {}s", self.start.elapsed().as_secs());
let _ = std::io::stderr().flush();
} else if self.phase != message { eprintln!(" • {message}"); }
self.phase = message;
}
pub fn clear(&self) { if self.tty && !self.phase.is_empty() { eprint!("\r\x1b[2K"); } }
pub fn finish(&mut self, args: &[&str], result: &Value) {
self.clear();
self.phase.clear();
self.record("result", result);
if self.json || self.debug { println!("{}", serde_json::to_string_pretty(result).expect("JSON result")); }
else { println!("{}", human(args, result, self.ru)); }
}
}
impl Drop for Output { fn drop(&mut self) { self.clear(); let _ = self.log.sync_all(); } }
fn phase_label(phase: &str, ru: bool) -> String {
let pair = match phase {
"metadata" => ("Проверка доступных пакетов и обновлений", "Checking available packages and updates"),
"details" => ("Подготовка списка изменений", "Reading changes"),
"planning" => ("Проверка запрошенных изменений", "Checking requested changes"),
"downloading" => ("Загрузка и проверка файлов", "Downloading and verifying files"),
"composing" => ("Подготовка системы", "Preparing system"),
"validating" => ("Проверка пакетов и совместимости", "Validating packages and compatibility"),
"finalizing" => ("Сохранение изменений", "Saving changes"),
"staging" => ("Подготовка следующей загрузки", "Preparing next boot"),
"reconciling" => ("Проверка результата операции", "Reconciling operation result"),
_ => ("Выполнение операции", "Working"),
};
if ru { pair.0.into() } else { pair.1.into() }
}
pub fn human(args: &[&str], result: &Value, ru: bool) -> String {
let t = |a: &str, b: &str| if ru { a.to_string() } else { b.to_string() };
if args.first() == Some(&"kargs") && result.get("selected").is_some() {
return result["selected"]["arguments"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" ")).unwrap_or_default();
}
if args == ["status"] {
return format!("{}: {}\n{}: {}\n{}: {}", t("Загруженная система", "Booted deployment"),
result["booted"]["deployment_id"].as_str().unwrap_or("—"), t("Следующая загрузка", "Pending deployment"),
result["pending"]["deployment_id"].as_str().unwrap_or("—"), t("Обновления", "Updates"),
match result["update"]["state"].as_str() { Some("current") => t("Система актуальна", "Up to date"),
Some("available") => t("Доступно обновление", "Update available"), _ => t("Не проверены", "Not checked") });
}
if let Some(lines) = result["lines"].as_array() { return lines.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("\n"); }
if args == ["extension", "status"] {
let names = |state: &Value| state["requested"].as_array().map(|rows|
rows.iter().filter_map(|r| r["name"].as_str()).collect::<Vec<_>>().join(", ")).filter(|s| !s.is_empty()).unwrap_or_else(|| "—".into());
return format!("Host Extensions: {}\n{}: {}\n{}: {}", if result["enabled"] == true { t("включены", "enabled") } else { t("выключены", "disabled") },
t("В загруженной системе", "Booted requests"), names(&result["booted"]),
t("Запрошено для следующей загрузки", "Desired requests"), names(&result["desired"]));
}
if let Some(rows) = result["transactions"].as_array() {
return rows.iter().map(|r| format!("{} {} {}", r["Id"].as_str().unwrap_or(""), r["Kind"].as_str().unwrap_or(""), r["State"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("\n");
}
if let Some(outcome) = result["outcome"].as_str() {
return match outcome {
"staged" => t("✓ Изменения подготовлены. Они вступят в силу после перезагрузки.", "✓ Changes prepared. Reboot when ready to activate them."),
"no-change" => t("✓ Запрошенные изменения уже применены.", "✓ No changes needed."),
"current" => t("✓ Система актуальна.", "✓ System is up to date."),
"available" => t("Доступно обновление системы.", "A system update is available."),
"configured" => if result["effects"]["extensions_enabled"] == true {
t("✓ Host Extensions включены.", "✓ Host Extensions enabled.")
} else { t("✓ Настройки сохранены.", "✓ Settings saved.") },
"downloaded" => t("✓ Файлы загружены и проверены.", "✓ Files downloaded and verified."),
"planned" => format!("{}: {}", t("План изменений", "Change plan"), result["plan_id"].as_str().unwrap_or("")),
"imported" => format!("{}: {}", t("Пакет импортирован", "Package imported"), result["input_id"].as_str().unwrap_or("")),
_ => describe(result, 0, ru),
};
}
describe(result, 0, ru)
}
// Queries retain all fields, but format them as readable lists rather than JSON.
fn describe(value: &Value, depth: usize, ru: bool) -> String {
let pad = " ".repeat(depth);
match value {
Value::Object(map) => map.iter().filter(|(k,_)| !matches!(k.as_str(), "context_id" | "revision" | "intent_generation"))
.map(|(k,v)| { let label = field_label(k, ru);
if v.is_object() || v.is_array() { format!("{pad}{label}:\n{}", describe(v, depth+1, ru)) }
else { format!("{pad}{label}: {}", describe(v, 0, ru)) } }).collect::<Vec<_>>().join("\n"),
Value::Array(a) => a.iter().map(|v| format!("{pad}• {}", describe(v, depth, ru))).collect::<Vec<_>>().join("\n"),
Value::Bool(b) => if *b { if ru { "да" } else { "yes" } } else if ru { "нет" } else { "no" }.into(),
Value::String(s) => s.clone(), Value::Null => "—".into(), _ => value.to_string(),
}
}
fn field_label(key: &str, ru: bool) -> String {
let pair = match key {
"booted" => ("Загруженная система", "Booted system"), "pending" => ("Следующая загрузка", "Pending system"),
"desired" => ("Запрошенное состояние", "Desired state"), "requested" => ("Запрошенные пакеты", "Requested packages"),
"name" => ("Название", "Name"), "version" => ("Версия", "Version"), "source" => ("Источник", "Source"),
"package_changes" => ("Изменения пакетов", "Package changes"), "added" => ("Добавлено", "Added"),
"removed" => ("Удалено", "Removed"), "changed" => ("Изменено", "Changed"), "before" => ("До", "Before"), "after" => ("После", "After"),
"overlays" => ("Доступные оверлеи", "Available overlays"), "selection" => ("Выбранные оверлеи", "Selected overlays"),
"generations" => ("История расширений", "Extension history"), "reboot_required" => ("Нужна перезагрузка", "Reboot required"),
"warnings" => ("Предупреждения", "Warnings"), "message" => ("Сообщение", "Message"),
_ => return key.replace('_', " "),
};
if ru { pair.0.into() } else { pair.1.into() }
}
pub fn failure(message: &str, ru: bool) -> String {
if message.contains("Explicitly enable Host Extensions") {
return if ru { "Сначала включите Host Extensions: archipelago extension enable" } else { "Enable Host Extensions first: archipelago extension enable" }.into();
}
if message.contains("Administrator authorization required") {
return if ru { "Нужно подтверждение администратора. Повторите с --interactive в сеансе с агентом авторизации или через sudo." }
else { "Administrator authorization is required. Retry with --interactive in a session with an authorization agent, or use sudo." }.into();
}
message.into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn human_success_does_not_leak_transaction_plumbing() {
let value = json!({"outcome":"staged","operation_id":"secret-id","request_id":"retry-token","effects":{}});
let text = human(&["extension","add","nano"], &value, true);
assert!(text.contains("перезагрузки"));
assert!(!text.contains("secret-id") && !text.contains("retry-token") && !text.contains('{'));
assert!(failure("Explicitly enable Host Extensions before changing requests", true).contains("archipelago extension enable"));
}
}

109
src/service/kargs.rs Normal file
View file

@ -0,0 +1,109 @@
//! Kernel arguments use native libostree parsing and new staged deployments.
use super::{storage, worker::{Failure, Result, Worker}};
use archipelago_contracts::system_bus::{ErrorCode, Phase};
use serde_json::{json, Value};
use std::{process::{Command, Stdio}, time::Duration};
const ADAPTER: &str = include_str!("../../adapters/kernel-arguments.py");
fn fail(message: &str) -> Failure { Failure::new(ErrorCode::InvalidArgument, message) }
pub fn validate(changes: &Value) -> Result<()> {
let rows = changes.as_array().ok_or_else(|| fail("Expected kernel argument edits"))?;
if rows.is_empty() || rows.len() > 256 || changes.to_string().len() > 65536 { return Err(fail("Invalid kernel argument edit count/size")); }
for row in rows {
let op = row["op"].as_str().unwrap_or("");
let arg = row["argument"].as_str().unwrap_or("");
let key = arg.split('=').next().unwrap_or("");
if row.as_object().is_none_or(|o| o.len() != 2) || !["append", "append-if-missing", "delete", "delete-if-present", "replace"].contains(&op)
|| arg.is_empty() || arg.len() > 4096 || arg.contains(['\0', '\r', '\n']) || key == "ostree"
|| key.is_empty() || !key.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) {
return Err(fail("Invalid kernel argument edit; ostree selector is managed automatically"));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edits_are_bounded_and_cannot_replace_ostree_selector() {
for arg in ["ostree=/bad", "ostree", "", "x\ny", " ostree=/bad", "\"ostree\"=/bad"] {
assert!(validate(&json!([{"op":"append","argument":arg}])).is_err());
}
assert!(validate(&json!([{"op":"append","argument":"rd.driver.blacklist=nouveau"}])).is_ok());
assert!(validate(&json!([{"op":"execute","argument":"quiet"}])).is_err());
}
}
pub fn inspect() -> Result<Value> {
let output = Command::new("/usr/bin/timeout").args(["--kill-after=2", "15", "/usr/bin/python3", "-c", ADAPTER])
.stdin(Stdio::null()).output().map_err(storage::io_error)?;
if !output.status.success() || output.stdout.len() > 1024*1024 {
return Err(Failure::new(ErrorCode::Unavailable, "Cannot read deployment kernel arguments"));
}
let deployments: Value = serde_json::from_slice(&output.stdout).map_err(|_| fail("Invalid kernel arguments observation"))?;
let context = storage::hash(&serde_json::to_vec(&deployments).map_err(|_| fail("Invalid kargs context"))?);
let selected = selected(&deployments)?.clone();
Ok(json!({"context_id":context,"selected":selected,"deployments":deployments}))
}
fn selected(rows: &Value) -> Result<&Value> {
let rows = rows.as_array().ok_or_else(|| fail("Missing kernel arguments"))?;
rows.iter().find(|d| d["staged"] == true).or_else(|| rows.iter().find(|d| d["booted"] == true))
.ok_or_else(|| fail("No booted Archipelago deployment"))
}
/// All installed mutations inherit the effective pending/booted arguments. The
/// image's initial defaults must not overwrite explicit user edits on each update.
pub fn deployment_args(target: &str) -> Result<(Vec<String>, Value)> {
let state = inspect()?;
let arguments = state["selected"]["arguments"].clone();
Ok((deploy_args(target, &arguments)?, arguments))
}
fn deploy_args(target: &str, arguments: &Value) -> Result<Vec<String>> {
if !archipelago_contracts::system_bus::checksum(target) { return Err(fail("Invalid deployment checksum")); }
let mut args: Vec<String> = ["admin", "deploy", "--stage", "--retain", "--os=archipelago", "--karg-none"].iter().map(|s| (*s).into()).collect();
for arg in arguments.as_array().ok_or_else(|| fail("Missing argument vector"))? {
let arg = arg.as_str().ok_or_else(|| fail("Invalid argument vector"))?;
args.push(format!("--karg-append={arg}"));
}
args.push(target.into());
Ok(args)
}
pub fn execute(worker: &Worker, changes: &Value, context: &str) -> Result<Value> {
validate(changes)?;
let _lock = crate::updates::lock().map_err(|_| Failure::new(ErrorCode::Busy, "Host is busy or provisioning is incomplete"))?;
let initial = crate::updates::managed::status(worker)?;
crate::updates::managed::ensure_pending_owned(worker, &initial)?;
let before = inspect()?;
if before["context_id"] != context { return Err(Failure::new(ErrorCode::PlanStale, "Kernel arguments changed; read the current deployment and retry")); }
worker.events.checkpoint(Phase::Planning, true, "Preparing kernel arguments")?;
let output = worker.command("/usr/bin/python3", &["-c", ADAPTER, &changes.to_string()], Duration::from_secs(15), true)?;
let rows: Value = serde_json::from_str(&output).map_err(|_| fail("Invalid edited kernel arguments"))?;
let source = selected(&rows)?;
let after = &source["edited"];
if after == &before["selected"]["arguments"] { return Ok(json!({"outcome":"no-change","changed":false,"arguments":after})); }
if crate::updates::managed::status(worker)? != initial || inspect()? != before {
return Err(Failure::new(ErrorCode::PlanStale, "Deployment changed before kernel argument staging"));
}
let target = source["checksum"].as_str().ok_or_else(|| fail("Missing selected deployment"))?;
worker.events.checkpoint(Phase::Staging, false, "Preparing deployment with updated kernel arguments")?;
worker.events.effect("stage_intent", json!({"checksum":target,"initial":initial,"kernel_arguments":after}))?;
let args = deploy_args(target, after)?;
worker.command("/usr/bin/ostree", &args.iter().map(String::as_str).collect::<Vec<_>>(), Duration::from_secs(300), false)?;
let deployment = crate::updates::managed::staged(&crate::updates::managed::status(worker)?, target)?;
verify(&deployment, after)?;
worker.events.effect("deployment", deployment.clone())?;
Ok(json!({"outcome":"staged","changed":true,"deployment":deployment,"arguments":after,"reboot_required":true}))
}
pub fn verify(deployment: &Value, expected: &Value) -> Result<()> {
let state = inspect()?;
if state["selected"]["deployment_id"] != deployment["deployment_id"] || state["selected"]["arguments"] != *expected {
return Err(Failure::new(ErrorCode::Interrupted, "Staged kernel arguments do not match the retained intent"));
}
Ok(())
}

View file

@ -3,6 +3,7 @@
pub mod journal;
pub mod authorization;
pub mod client;
mod client_output;
mod observation;
pub(crate) mod storage;
pub(crate) mod worker;
@ -17,6 +18,7 @@ pub(crate) mod packages;
pub(crate) mod overlays;
mod managed_overlays;
pub(crate) mod overlay_build;
pub(crate) mod kargs;
use archipelago_contracts::system_bus::{self as protocol, BUS_NAME, MANAGER_INTERFACE, MANAGER_PATH};
use std::{collections::HashMap, fs, os::unix::fs::MetadataExt,
@ -117,12 +119,13 @@ impl Manager {
fn get_capabilities(&self) -> Dictionary {
HashMap::from([
("api_major".into(), OwnedValue::from(1_u32)),
("api_minor".into(), OwnedValue::from(1_u32)),
("api_minor".into(), OwnedValue::from(2_u32)),
("operations".into(), strings([
"GetCapabilities", "GetStatus", "Refresh", "GetUpdateDetails", "PrepareUpdate",
"Download", "Stage", "GetTransaction", "ListTransactions", "ValidatePending",
"GetKernelArguments", "ChangeKernelArguments",
].iter().map(|name| (*name).into()).collect())),
("features".into(), strings(vec!["durable-transactions".into(), "host-extensions".into()])),
("features".into(), strings(vec!["durable-transactions".into(), "host-extensions".into(), "kernel-arguments".into()])),
("limits".into(), dictionary(HashMap::from([
("max_page_entries".into(), OwnedValue::from(protocol::MAX_PAGE_ENTRIES)),
("max_request_bytes".into(), OwnedValue::from(protocol::MAX_REQUEST_BYTES as u32)),
@ -130,6 +133,35 @@ impl Manager {
])
}
#[zbus(out_args("arguments"))]
fn get_kernel_arguments(&self) -> Result<Dictionary, BusError> {
wire::map(&kargs::inspect()?)
}
#[zbus(out_args("transaction"))]
async fn change_kernel_arguments(&self, changes: Vec<Dictionary>, context_id: &str, options: Dictionary,
#[zbus(connection)] connection: &zbus::Connection,
#[zbus(header)] header: zbus::message::Header<'_>) -> Result<OwnedObjectPath, BusError> {
if !protocol::checksum(context_id) || changes.len() > 256 { return Err(BusError::InvalidArgument("Invalid kernel arguments context or edit count".into())); }
let changes = changes.into_iter().map(|row| {
if row.len() != 2 { return Err(BusError::InvalidArgument("Expected op and argument".into())); }
let string = |key: &str| -> Result<String, BusError> {
row.get(key).and_then(|v| <&str>::try_from(v).ok()).map(str::to_owned)
.ok_or_else(|| BusError::InvalidArgument("Expected string kernel argument fields".into()))
};
Ok(serde_json::json!({"op":string("op")?,"argument":string("argument")?}))
}).collect::<Result<Vec<_>, BusError>>()?;
let changes = serde_json::json!(changes);
kargs::validate(&changes)?;
let method = protocol::Method::ChangeKernelArguments;
let options = wire::options(method, options)?;
let caller = authorization::authorize(connection, &header, &options, authorization::Action::KernelArguments, None).await?;
let context = context_id.to_owned();
self.runtime.submit(connection, caller, method, options,
serde_json::json!({"changes":changes,"context_id":context}), "",
move |worker| kargs::execute(worker, &changes, &context)).await
}
#[zbus(out_args("status"))]
fn get_status(&self) -> Result<Dictionary, BusError> {
let observed = self.status.read().map_err(|_| BusError::Unavailable("Status observer unavailable".into()))?.clone();

View file

@ -503,14 +503,11 @@ pub(crate) fn execute_locked(worker: &Worker, plan: &Plan, download_only: bool,
sandbox.release_checkout(worker)?;
if current(worker)?.1 != initial { return Err(Failure::new(ErrorCode::PlanStale,"Deployment changed before staging")); }
worker.events.checkpoint(Phase::Staging,false,"Staging the complete extension generation")?;
worker.events.effect("stage_intent",json!({"checksum":target,"initial":initial,"generation":id}))?;
let mut args = vec!["admin","deploy","--stage","--retain","--os=archipelago"];
if Path::new("/usr/lib/archipelago/desktop-boot").exists() {
args.extend(["--karg=quiet","--karg=splash","--karg=plymouth.ignore-serial-consoles"]);
}
args.push(&target);
worker.command("/usr/bin/ostree",&args,Duration::from_secs(300),false)?;
let (args, arguments) = super::kargs::deployment_args(&target)?;
worker.events.effect("stage_intent",json!({"checksum":target,"initial":initial,"generation":id,"kernel_arguments":arguments}))?;
worker.command("/usr/bin/ostree",&args.iter().map(String::as_str).collect::<Vec<_>>(),Duration::from_secs(300),false)?;
let deployment = crate::updates::managed::staged(&crate::updates::managed::status(worker)?,&target)?;
super::kargs::verify(&deployment, &arguments)?;
worker.events.effect("deployment",deployment.clone())?;
Ok(json!({"outcome":"staged","changed":true,"generation":id,"deployment":deployment,"effects":{"deployment_staged":true}}))
}

View file

@ -229,12 +229,17 @@ impl Runtime {
let deployment = crate::updates::managed::staged(&state, target)?;
// A matching deployment already present before the operation cannot be
// used as proof that the interrupted operation completed.
if crate::updates::managed::staged(&intent["initial"], target).is_ok() {
if crate::updates::managed::staged(&intent["initial"], target).is_ok_and(|old| old["deployment_id"] == deployment["deployment_id"]) {
return Err(Failure::new(ErrorCode::Interrupted, "Staging identity is ambiguous; inspect retained operation"));
}
if let Some(expected) = intent.get("kernel_arguments") { super::kargs::verify(&deployment, expected)?; }
journal.update(&record.id, |record| { record.effects["deployment"] = deployment.clone(); Ok(()) })
.map_err(|_| Failure::new(ErrorCode::Unavailable, "Cannot record observed stage result"))?;
let mut result = json!({"outcome":"staged","changed":true,"deployment":deployment,"effects":{"deployment_staged":true}});
if record.binding.method == Method::ChangeKernelArguments {
result["arguments"] = intent["kernel_arguments"].clone();
result["reboot_required"] = json!(true);
}
if let Some(generation) = intent.get("generation") { result["generation"] = generation.clone(); }
Ok(Ok(result))
}

View file

@ -51,7 +51,7 @@ fn variant(key: &str, value: &Value) -> Result<OwnedValue, BusError> {
// before/after are overlay ordering strings OR package-diff records.
// Preserve the historical empty-array type, but encode populated package
// lists as aa{sv}, including when replaying durable transactions.
Value::Array(items) if matches!(key, "warnings" | "required_actions" | "requires" | "conflicts" | "core" | "purpose" | "inputs" | "outputs")
Value::Array(items) if matches!(key, "warnings" | "required_actions" | "requires" | "conflicts" | "core" | "purpose" | "inputs" | "outputs" | "arguments")
|| (matches!(key, "before" | "after") && items.is_empty()) || items.iter().any(Value::is_string) => {
let values = items.iter().map(|v| v.as_str().map(str::to_string)
.ok_or_else(|| BusError::ExecutionFailed("Invalid string array".into()))).collect::<Result<Vec<_>, _>>()?;

View file

@ -1,4 +1,5 @@
//! Privileged, short-lived desktop software bridge to the shared update engine.
//! Historical pre-D-Bus desktop bridge, not exposed by the current CLI or units.
//! Native store plugins use service transactions; this legacy cache is not their API.
use serde_json::{json, Value};
use std::{fs, path::Path, process::Command};

View file

@ -337,13 +337,12 @@ pub(crate) fn execute(worker: &Worker, plan: &Plan, download_only: bool, offline
cmd(worker, &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), &plan.target], false, true)?;
if status(worker)? != initial { return Err(Failure::new(ErrorCode::PlanStale, "Deployment changed before staging")); }
worker.events.checkpoint(Phase::Staging, false, "Staging deployment for the next boot")?;
worker.events.effect("stage_intent", json!({"checksum":plan.target,"initial":initial}))?;
let mut args = vec!["admin", "deploy", "--stage", "--retain", "--os=archipelago"];
if candidate != "core" { args.extend(["--karg=quiet", "--karg=splash", "--karg=plymouth.ignore-serial-consoles"]); }
args.push(&plan.target);
worker.command("/usr/bin/ostree", &args, Duration::from_secs(300), false)?;
let (args, arguments) = crate::service::kargs::deployment_args(&plan.target)?;
worker.events.effect("stage_intent", json!({"checksum":plan.target,"initial":initial,"kernel_arguments":arguments}))?;
worker.command("/usr/bin/ostree", &args.iter().map(String::as_str).collect::<Vec<_>>(), Duration::from_secs(300), false)?;
let observed = status(worker)?;
let deployment = staged(&observed, &plan.target)?;
crate::service::kargs::verify(&deployment, &arguments)?;
worker.events.effect("deployment", deployment.clone())?;
Ok(json!({"outcome":"staged","changed":true,"deployment":deployment,"effects":{"deployment_staged":true}}))
}

27
tests/kernel_arguments.py Normal file
View file

@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Native libostree argument semantics, run in the normal build-tools stage."""
from pathlib import Path
import runpy
arguments = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'adapters/kernel-arguments.py'))['arguments']
base = b'root=UUID=fixture rw quiet console=tty0 console=ttyS0 ostree=/managed'
assert arguments(base, []) == ['root=UUID=fixture', 'rw', 'quiet', 'console=tty0', 'console=ttyS0']
edits = [{'op':'append-if-missing','argument':'quiet'},
{'op':'delete','argument':'quiet'},
{'op':'replace','argument':'console=ttyS0=ttyS1'},
{'op':'append','argument':'archipelago.test=yes'}]
result = arguments(base, edits)
assert 'quiet' not in result and 'console=ttyS0' not in result
assert 'console=tty0' in result and 'console=ttyS1' in result and 'archipelago.test=yes' in result
assert arguments(base, [{'op':'delete-if-present','argument':'absent'}]) == arguments(base, [])
for change in [{'op':'delete','argument':'absent'}, {'op':'append','argument':'ostree=/bad'},
{'op':'append','argument':'test=yes ostree=/bad'},
{'op':'append','argument':'test="unterminated'},
{'op':'replace','argument':'absent=new'}]:
try:
arguments(base, [change])
except ValueError:
pass
else:
raise AssertionError(change)
print('Native kernel argument edit/duplicate/protected-selector checks passed')