Begin archipelagod with read-only bus service and durable admission foundation

This commit is contained in:
Pavel Isaev 2026-11-07 16:43:05 +03:00
parent 2848c1fdc9
commit 34961d260c
16 changed files with 2339 additions and 10 deletions

1519
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -7,3 +7,8 @@ publish = false
[dependencies]
serde_json = "1.0"
serde = { version = "1", features = ["derive"] }
archipelago-contracts = { path = "../contracts" }
zbus = { version = "=5.12.0", default-features = false, features = ["async-io", "blocking-api"] }
# Macro releases use private zbus dispatch APIs; pin the matching family too.
zbus_macros = "=5.12.0"

View file

@ -1,5 +1,15 @@
# Archipelago system
## Системная служба (D-092/D-093)
Начат read-only срез `archipelagod`, общий wire-контракт, авторизация и durable
journal foundation. Текущая граница реализации/проверки описана в
[`SERVICE.md`](SERVICE.md); mutation engine и клиенты ещё не мигрированы.
Актуальные компиляции/VM выполняются на yabloko; terra публикует артефакты.
Матрица новых проверок включается в штатный release pipeline.
## Исторический onboarding-прототип
Экспериментальная чистая модель первого запуска по D-036/D-064.
Дизайн: `../installer/CONTROL-LAYER.md`.

78
SERVICE.md Normal file
View file

@ -0,0 +1,78 @@
# archipelagod implementation checkpoint
2026-11-07. D-092/D-093 are accepted; the full service migration is in progress.
## Implemented source slice
- Thin `cli/src/bin/archipelagod.rs` entrypoint uses the existing system crate.
- System-bus Manager, Properties, Introspectable and ObjectManager. Only
GetCapabilities/GetStatus are advertised. Other Manager calls explicitly return
`org.archipelago.System1.Error.Unsupported`, without spawning a CLI or admitting
work. Extension/overlay/broker features are absent.
- Local OSTree observation on a worker outside the D-Bus executor. It takes the
existing `/run/archipelago-compose.lock` nonblocking, reads with a 10-second
command deadline, retains cached state with `reconciling=true` on failure and
emits StatusRevision after durable publication. Deployment IDs include serial;
unknown base/Purpose/snapshot/support fields are omitted. No mirror request.
- Private `/var/lib/archipelago/service/observation.json` contains versioned local
observations, not update intent or a second operation authority. Revisions
survive restart; unsupported schema stops startup without resetting it.
- Admission journal foundation: private bounded records, lifetime ownership lock,
UID/method/request-ID/canonical-input binding, reconnect deduplication, explicit
transitions, file+directory fsync, immutable terminal records and fail-closed
unknown schemas/durability errors. Surviving active work blocks new admission
until engine reconciliation. No auto-replay, guessed success or automatic GC.
- Async Polkit helper derives UID/unique sender from the bus, requires both
interactive flags and uses a service-selected action. PackageKit's current
owner is rejected from direct authorization: broker verification is still needed.
Cancellation-own checks compare authenticated UID to the retained initiator in
the service, not a caller option or an undocumented Polkit subject field.
- Unit, activation, bus policy, separate Polkit actions/rules are provided under
`integrations/dbus/`. They are **not installed by the image builder yet**.
- `updates::prepare` returns its result instead of formatting it internally;
current CLI wrappers preserve output. Exact-target callers cannot silently
follow a moved track. This legacy engine adapter is not yet admitted by D-Bus.
- Explicit development CLI: `archipelago service capabilities|status`. Ordinary
installed-host commands retain their existing path until coordinated migration.
## Dependency and compilation
Use pure-Rust zbus **5.12.0**, async-io executor and blocking client wrapper; no
new libdbus/GIO link dependency in the core Rust binary. Existing engine work is
blocking and stays outside the bus executor. Pin `zbus_macros=5.12.0` as well:
the initial resolver selected macros 5.19 against zbus 5.12, producing a private
DispatchResult2 API mismatch. Matching versions compile on the existing Rust 1.90
tools image. CLI/system lockfiles retain exact checksums for transitive crates.
Build preparation uses yabloko `/opt/archipelago/dbus-next/`, separate from frozen
release sources and the regular target directory. Rust release compilation and
compilation of the contract/system test executables have been checked there.
Tests are wired into the regular release-cycle compile stage; no separate VM or
standalone test run has been executed for this slice. Native proxy compilation,
activation, real bus calls and Polkit session behavior still need pipeline evidence.
## Next integration boundary
Do not install this read-only slice as a completed installed-host replacement.
Still required: typed execution/progress/results; one migrated legacy plan/operation
authority; durable terminal results and recovery against OSTree/boot state; bounded
worker admission and cache; fast refresh; exact plan Download/Stage; safe Cancel;
owned workers; full CLI routing and native GUI migration; measured limits; real
Host Extension/overlay/broker implementation and acceptance. Local-package trust
and future host method schemas remain governed by their RFC contracts.
The service observer's output does not claim that a legacy update job is a durable
service transaction. The new journal is not connected to the mutation engine yet
and must not be used as an independent second writer. Keep old records/inputs for
migration. Feature policy and package plans must derive their required actions on
the service side; an eventual Stage handler must never select `stage-update` solely
because of its method name. Read-only compilation is not rollout or VM acceptance.
Future packaging destinations: binary `/usr/bin/archipelagod`, unit
`/usr/lib/systemd/system/archipelagod.service`, bus activation
`/usr/share/dbus-1/system-services/`, bus policy `/usr/share/dbus-1/system.d/`,
Polkit action XML `/usr/share/polkit-1/actions/`, rules
`/usr/share/polkit-1/rules.d/`. Keep `KillMode=control-group`; sandbox changes require
real compose/mount acceptance. No service enablement or timer change is needed for
bus activation. Both native clients must transition together before old helpers
and their broad action are removed.

View file

@ -0,0 +1,12 @@
polkit.addRule(function(action, subject) {
var actions = ["refresh", "download", "stage-update", "cancel", "read-logs",
"extension-enable", "extension-change", "extension-local", "extension-override",
"extension-restore", "overlay-change"];
var prefix = "org.archipelago.system.";
if (action.id.indexOf(prefix) !== 0 || actions.indexOf(action.id.slice(prefix.length)) < 0) return;
if (subject.user === "root") return polkit.Result.YES;
if (!subject.local || !subject.active) return;
if ((action.id === prefix + "stage-update" || action.id === prefix + "read-logs") && subject.isInGroup("wheel")) return polkit.Result.YES;
if (action.id === prefix + "cancel" && action.lookup("cancel_own") === "true") return polkit.Result.YES;
// Host Extension / overlay actions retain admin authentication, including wheel.
});

View file

@ -0,0 +1,23 @@
[Unit]
Description=Archipelago installed-system service
Documentation=https://mirror.nw-sys.ru/archipelago/docs/#RFC-0012
After=dbus.service
ConditionPathExists=/run/ostree-booted
[Service]
Type=dbus
BusName=org.archipelago.System1
ExecStart=/usr/bin/archipelagod
User=root
Group=root
StateDirectory=archipelago
UMask=0077
KillMode=control-group
TimeoutStopSec=30s
Restart=on-failure
RestartSec=5s
# Do not impose filesystem/mount restrictions until the staging worker is integrated.
# No idle exit while work is accepted. No per-operation timeout on the bus unit.
[Install]
Alias=archipelago-daemon.service

View file

@ -0,0 +1,9 @@
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="root"><allow own="org.archipelago.System1"/></policy>
<policy context="default">
<allow send_destination="org.archipelago.System1"/>
<!-- Mutations require per-method daemon authorization, not bus policy. -->
</policy>
</busconfig>

View file

@ -0,0 +1,5 @@
[D-BUS Service]
Name=org.archipelago.System1
Exec=/usr/bin/archipelagod
User=root
SystemdService=archipelagod.service

View file

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN" "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
<vendor>Archipelago</vendor>
<vendor_url>https://mirror.nw-sys.ru/archipelago/</vendor_url>
<action id="org.archipelago.system.refresh">
<description>Refresh Archipelago metadata</description><message>Authorization is required to refresh system metadata</message>
<defaults><allow_any>no</allow_any><allow_inactive>no</allow_inactive><allow_active>yes</allow_active></defaults>
</action>
<action id="org.archipelago.system.download">
<description>Download a verified Archipelago update</description><message>Authorization is required to download system inputs</message>
<defaults><allow_any>no</allow_any><allow_inactive>no</allow_inactive><allow_active>yes</allow_active></defaults>
</action>
<action id="org.archipelago.system.stage-update">
<description>Stage a trusted current-track OS update</description><message>Authorization is required to stage the OS update</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.cancel">
<description>Cancel an Archipelago operation</description><message>Authorization is required to cancel this operation</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.read-logs">
<description>Read protected Archipelago operation logs</description><message>Authorization is required to read operation logs</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.extension-enable">
<description>Configure Host Extensions</description><message>Authorization is required to enable or disable Host Extensions</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.extension-change">
<description>Change repository Host Extensions</description><message>Authorization is required to change native package requests</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.extension-local">
<description>Import or apply local package inputs</description><message>Authorization is required to use local package inputs</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.extension-override">
<description>Replace managed packages</description><message>Authorization is required to change package overrides</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.extension-restore">
<description>Restore a Host Extension generation</description><message>Authorization is required to restore package requests</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.overlay-change">
<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>
</policyconfig>

View file

@ -1,6 +1,8 @@
# Included inside the matching, checksum-pinned Discover source tree.
kcoreaddons_add_plugin(archipelago-backend SOURCES ArchipelagoBackend.cpp INSTALL_NAMESPACE "discover")
target_link_libraries(archipelago-backend Qt::Core KF6::CoreAddons Discover::Common)
find_package(Qt6 REQUIRED COMPONENTS DBus)
qt_add_dbus_interfaces(archipelago_bus_sources org.archipelago.System1.xml)
kcoreaddons_add_plugin(archipelago-backend SOURCES ArchipelagoBackend.cpp ${archipelago_bus_sources} INSTALL_NAMESPACE "discover")
target_link_libraries(archipelago-backend Qt::Core Qt::DBus KF6::CoreAddons Discover::Common)
set_target_properties(archipelago-backend PROPERTIES
INSTALL_RPATH "/usr/lib/plasma-discover"
BUILD_WITH_INSTALL_RPATH TRUE)

View file

@ -1,4 +1,4 @@
//! Installed-host lifecycle prototypes. No host mutations are implemented yet.
//! Installed-host lifecycle engine and service integration.
pub mod onboarding;
pub mod extensions;
pub mod desktop;
@ -6,6 +6,7 @@ pub mod updates;
pub mod package_diff;
pub mod software;
mod progress;
pub mod service;
pub const HOST: &str = include_str!("../adapters/host.sh");
pub const FIRSTBOOT: &str = include_str!("../adapters/firstboot.sh");

View file

@ -0,0 +1,62 @@
//! Polkit boundary for future admitted operations. No client selects action IDs.
//! The original sender comes from the authenticated message header, never a map.
use super::{BusError, text};
use archipelago_contracts::system_bus::{Caller, Options};
use std::collections::HashMap;
use zbus::{Connection, message::{Header, Flags}};
#[derive(Clone, Copy, Debug)]
pub enum Action {
Refresh, Download, StageUpdate, Cancel, ReadLogs, ExtensionEnable,
ExtensionChange, ExtensionLocal, ExtensionOverride, ExtensionRestore, OverlayChange,
}
impl Action {
fn id(self) -> &'static str {
match self {
Self::Refresh => "org.archipelago.system.refresh",
Self::Download => "org.archipelago.system.download",
Self::StageUpdate => "org.archipelago.system.stage-update",
Self::Cancel => "org.archipelago.system.cancel",
Self::ReadLogs => "org.archipelago.system.read-logs",
Self::ExtensionEnable => "org.archipelago.system.extension-enable",
Self::ExtensionChange => "org.archipelago.system.extension-change",
Self::ExtensionLocal => "org.archipelago.system.extension-local",
Self::ExtensionOverride => "org.archipelago.system.extension-override",
Self::ExtensionRestore => "org.archipelago.system.extension-restore",
Self::OverlayChange => "org.archipelago.system.overlay-change",
}
}
}
/// `initiator_uid` is from the retained operation, only for Cancel. All other
/// details are service-controlled. Broker delegation needs its separate verifier;
/// this direct-client helper must not be used to authorize PackageKit as root.
pub async fn authorize(connection: &Connection, header: &Header<'_>, options: &Options,
action: Action, initiator_uid: Option<u32>) -> Result<Caller, BusError> {
let sender = header.sender().ok_or_else(|| BusError::NotAuthorized("Authenticated sender required".into()))?;
let bus = zbus::fdo::DBusProxy::new(connection).await
.map_err(|_| BusError::Unavailable("Cannot contact system bus authority".into()))?;
let uid = bus.get_connection_unix_user(sender.clone().into()).await
.map_err(|_| BusError::NotAuthorized("Sender is no longer connected".into()))?;
if let Ok(owner) = bus.get_name_owner(zbus::names::BusName::try_from("org.freedesktop.PackageKit").expect("constant bus name")).await {
if owner.as_str() == sender.as_str() {
return Err(BusError::NotAuthorized("PackageKit must use the verified original-caller broker".into()));
}
}
let subject = ("system-bus-name", HashMap::from([("name", text(sender.as_str()))]));
let mut details: HashMap<&str, String> = HashMap::new();
if let Action::Cancel = action {
let initiator = initiator_uid.ok_or_else(|| BusError::InvalidArgument("Cancellation requires retained initiator".into()))?;
details.insert("cancel_own", (uid == initiator).to_string());
} else if initiator_uid.is_some() { return Err(BusError::InvalidArgument("Unexpected initiator detail".into())); }
let flags = if options.may_prompt(header.primary().flags().contains(Flags::AllowInteractiveAuth)) { 1_u32 } else { 0 };
let proxy = zbus::Proxy::new(connection, "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority",
"org.freedesktop.PolicyKit1.Authority").await
.map_err(|_| BusError::Unavailable("Authorization service unavailable".into()))?;
let (authorized, challenge, _details): (bool, bool, HashMap<String, String>) = proxy
.call("CheckAuthorization", &(subject, action.id(), details, flags, "")).await
.map_err(|_| BusError::Unavailable("Authorization check failed".into()))?;
if authorized { Ok(Caller { uid, unique_sender: sender.to_string() }) }
else if challenge { Err(BusError::AuthenticationRequired("Administrator authorization required; use an explicit interactive request and an authorization agent".into())) }
else { Err(BusError::NotAuthorized("Operation is not authorized for this session".into())) }
}

238
src/service/journal.rs Normal file
View file

@ -0,0 +1,238 @@
//! Private durable admission journal. One owner, fsynced records, no replay of work.
//! This is not an OSTree authority: critical effects require engine reconciliation.
use archipelago_contracts::system_bus::{self as protocol, Caller, Method, Options, Phase, State};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::BTreeMap, fs::{self, File, OpenOptions}, io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH}};
const MAX_RECORD_BYTES: u64 = 256 * 1024;
const MAX_RECORDS: usize = 4096;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub uid: u32,
pub method: Method,
pub request_id: Option<String>,
pub inputs: Value,
pub offline: bool,
pub force: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Record {
pub version: u32,
pub id: String,
pub binding: Binding,
pub original_sender: String,
pub state: State,
pub phase: Phase,
pub revision: u64,
pub created_at_usec: u64,
pub updated_at_usec: u64,
pub retained_until_usec: u64,
pub effects: Value,
}
pub struct Journal {
directory: PathBuf,
_owner: File,
records: BTreeMap<String, Record>,
poisoned: bool,
}
#[derive(Debug)]
pub enum Admission { Accepted(Record), Existing(Record) }
fn now() -> Result<u64, String> {
SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?
.as_micros().try_into().map_err(|_| "timestamp overflow".into())
}
fn random_id() -> Result<String, String> {
let mut bytes = [0_u8; 16];
File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut bytes)).map_err(|e| e.to_string())?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
fn private(path: &Path, directory: bool) -> Result<(), String> {
let m = fs::symlink_metadata(path).map_err(|e| e.to_string())?;
if m.file_type().is_symlink() || m.is_dir() != directory || (!directory && !m.is_file()) || m.mode() & 0o077 != 0 {
return Err("journal entry must be a private regular file/directory".into());
}
// Same owner as the service process; production entrypoint requires root.
let uid = fs::metadata("/proc/self").map_err(|e| e.to_string())?.uid();
if m.uid() != uid { return Err("journal ownership mismatch".into()); }
Ok(())
}
impl Journal {
/// Parent must be a service-owned directory. No client selects this path.
/// Unknown versions/corruption stop admission; never reset or remove history.
pub fn open(directory: &Path) -> Result<Self, String> {
if !directory.exists() {
fs::DirBuilder::new().mode(0o700).create(directory).map_err(|e| e.to_string())?;
File::open(directory.parent().ok_or("journal parent missing")?).and_then(|f| f.sync_all()).map_err(|e| e.to_string())?;
}
private(directory, true)?;
let lock_path = directory.join("owner.lock");
if lock_path.exists() { private(&lock_path, false)?; }
let owner = OpenOptions::new().write(true).create(true).truncate(false).mode(0o600)
.open(&lock_path).map_err(|e| e.to_string())?;
owner.try_lock().map_err(|_| "journal already owned")?;
let mut records = BTreeMap::new();
for entry in fs::read_dir(directory).map_err(|e| e.to_string())? {
let path = entry.map_err(|e| e.to_string())?.path();
let name = path.file_name().and_then(|n| n.to_str()).ok_or("invalid journal filename")?;
if name == "owner.lock" || (name.starts_with("partial-") && protocol::operation_id(&name[8..])) { continue; }
let id = name.strip_suffix(".json").filter(|s| protocol::operation_id(s)).ok_or("unrecognized journal entry; retained")?;
if records.len() >= MAX_RECORDS { return Err("journal capacity exceeded; explicit maintenance required".into()); }
private(&path, false)?;
let mut file = File::open(&path).map_err(|e| e.to_string())?;
if file.metadata().map_err(|e| e.to_string())?.len() > MAX_RECORD_BYTES { return Err("journal record too large".into()); }
let mut bytes = Vec::new();
Read::by_ref(&mut file).take(MAX_RECORD_BYTES + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_RECORD_BYTES { return Err("journal record too large".into()); }
let value: Value = serde_json::from_slice(&bytes).map_err(|e| format!("invalid journal JSON: {e}"))?;
if value["version"].as_u64() != Some(protocol::JOURNAL_VERSION.into()) {
return Err("unsupported journal version; retained without modification".into());
}
let record: Record = serde_json::from_value(value).map_err(|e| e.to_string())?;
if record.id != id || record.revision == 0 || !record.effects.is_object() ||
record.binding.request_id.as_deref().is_some_and(|s| !protocol::request_id(s)) ||
(record.binding.method.requires_request_id() && record.binding.request_id.is_none()) {
return Err("invalid journal identity/state".into());
}
if records.values().any(|r: &Record| record.binding.request_id.is_some() &&
r.binding.uid == record.binding.uid && r.binding.method == record.binding.method &&
r.binding.request_id == record.binding.request_id) {
return Err("duplicate durable request binding; reconciliation required".into());
}
records.insert(id.to_owned(), record);
}
Ok(Self { directory: directory.into(), _owner: owner, records, poisoned: false })
}
pub fn records(&self) -> impl Iterator<Item = &Record> { self.records.values() }
/// Call only after authorization and validation. Persist before RPC replies.
/// Any surviving active record blocks fresh work until explicit reconciliation.
pub fn admit(&mut self, caller: &Caller, method: Method, options: &Options, inputs: Value) -> Result<Admission, String> {
if self.poisoned { return Err("journal durability uncertain; restart and reconcile".into()); }
if matches!(method, Method::Cancel | Method::GetLog) ||
(options.force && !matches!(method, Method::Refresh | Method::RefreshCatalog)) ||
options.request_id.as_deref().is_some_and(|id| !protocol::request_id(id)) ||
(method.requires_request_id() && options.request_id.is_none()) ||
!inputs.is_object() || serde_json::to_vec(&inputs).map_err(|e| e.to_string())?.len() > protocol::MAX_REQUEST_BYTES {
return Err("invalid admission inputs".into());
}
let binding = Binding { uid: caller.uid, method, request_id: options.request_id.clone(), inputs,
offline: options.offline, force: options.force };
if binding.request_id.is_some() {
if let Some(prior) = self.records.values().find(|r| r.binding.uid == binding.uid &&
r.binding.method == method && r.binding.request_id == binding.request_id) {
return if prior.binding == binding { Ok(Admission::Existing(prior.clone())) }
else { Err("request ID reused with different canonical inputs".into()) };
}
}
if self.records.values().any(|r| !r.state.terminal()) { return Err("active or unreconciled operation; admission blocked".into()); }
if self.records.len() >= MAX_RECORDS { return Err("journal capacity reached; protected records retained".into()); }
let timestamp = now()?;
let id = random_id()?;
if self.records.contains_key(&id) { return Err("operation identity collision".into()); }
let record = Record { version: protocol::JOURNAL_VERSION, id: id.clone(), binding,
original_sender: caller.unique_sender.clone(), state: State::Queued, phase: Phase::Admission,
revision: 1, created_at_usec: timestamp, updated_at_usec: timestamp,
retained_until_usec: 0, effects: serde_json::json!({}) };
self.persist(&record)?;
self.records.insert(id, record.clone());
Ok(Admission::Accepted(record))
}
/// Before critical effects, persist the new phase. Terminal records are immutable.
/// `effects` comes from engine observation, never from the transport caller.
pub fn transition(&mut self, id: &str, state: State, phase: Phase, effects: Value) -> Result<Record, String> {
if self.poisoned { return Err("journal durability uncertain; restart and reconcile".into()); }
if !protocol::operation_id(id) || !effects.is_object() { return Err("invalid transition".into()); }
let mut record = self.records.get(id).ok_or("unknown operation")?.clone();
if record.state.terminal() { return Err("terminal record is immutable".into()); }
let allowed = match record.state {
State::Queued => matches!(state, State::Running | State::Cancelled | State::Reconciling | State::Interrupted | State::Failed),
State::Running => !matches!(state, State::Queued),
State::Cancelling => matches!(state, State::Cancelling | State::Cancelled | State::Failed | State::Reconciling | State::Interrupted),
State::Reconciling => matches!(state, State::Succeeded | State::Failed | State::Interrupted | State::Reconciling),
_ => false,
};
if !allowed { return Err("invalid state transition".into()); }
record.state = state;
record.phase = phase;
record.effects = effects;
record.revision = record.revision.checked_add(1).ok_or("revision overflow")?;
record.updated_at_usec = now()?.max(record.updated_at_usec);
// No automatic GC until deployment/plan protection is wired into the engine.
self.persist(&record)?;
self.records.insert(id.into(), record.clone());
Ok(record)
}
fn persist(&mut self, record: &Record) -> Result<(), String> {
let bytes = serde_json::to_vec(record).map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_RECORD_BYTES { return Err("record too large".into()); }
let temp = self.directory.join(format!("partial-{}", random_id()?));
let result = (|| -> std::io::Result<()> {
let mut file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&temp)?;
file.write_all(&bytes)?;
file.sync_all()?;
fs::rename(&temp, self.directory.join(format!("{}.json", record.id)))?;
File::open(&self.directory)?.sync_all()
})();
if let Err(error) = result {
self.poisoned = true;
return Err(format!("journal write failed; admission stopped: {error}"));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn fixture() -> PathBuf { std::env::temp_dir().join(format!("archipelago-journal-{}", random_id().unwrap())) }
#[test]
fn restart_reattaches_same_request_and_blocks_ambiguous_new_work() {
let path = fixture();
let caller = Caller { uid: 1000, unique_sender: ":1.20".into() };
let options = Options { request_id: Some("12345678-1234-1234-1234-123456789abc".into()), ..Default::default() };
let mut j = Journal::open(&path).unwrap();
let Admission::Accepted(first) = j.admit(&caller, Method::Stage, &options, json!({"plan_id":"a".repeat(64)})).unwrap() else { panic!() };
assert!(Journal::open(&path).is_err());
j.transition(&first.id, State::Running, Phase::Staging, json!({})).unwrap();
drop(j);
let mut j = Journal::open(&path).unwrap();
let reconnected = Caller { unique_sender: ":1.42".into(), ..caller };
assert!(matches!(j.admit(&reconnected, Method::Stage, &options, json!({"plan_id":"a".repeat(64)})), Ok(Admission::Existing(r)) if r.id == first.id));
assert!(j.admit(&reconnected, Method::Stage, &options, json!({"plan_id":"b".repeat(64)})).is_err());
assert!(j.admit(&reconnected, Method::Refresh, &Options::default(), json!({})).is_err());
j.transition(&first.id, State::Reconciling, Phase::Reconciling, json!({"deployment_seen":true})).unwrap();
j.transition(&first.id, State::Interrupted, Phase::Reconciling, json!({"deployment_seen":true})).unwrap();
assert!(j.transition(&first.id, State::Succeeded, Phase::Finished, json!({})).is_err());
drop(j);
fs::remove_dir_all(path).unwrap();
}
#[test]
fn newer_schema_is_retained_byte_for_byte() {
let path = fixture();
drop(Journal::open(&path).unwrap());
let record = path.join(format!("{}.json", "a".repeat(32)));
let bytes = b"{\"version\":999,\"future\":true}";
let mut f = OpenOptions::new().create_new(true).write(true).mode(0o600).open(&record).unwrap();
f.write_all(bytes).unwrap();
assert!(Journal::open(&path).is_err());
assert_eq!(fs::read(&record).unwrap(), bytes);
fs::remove_dir_all(path).unwrap();
}
}

149
src/service/mod.rs Normal file
View file

@ -0,0 +1,149 @@
//! Incremental service frontend. Only local observation is enabled in this slice.
//! Mutation capabilities stay absent until engine/journal/policy integration passes.
pub mod journal;
pub mod authorization;
mod observation;
use archipelago_contracts::system_bus::{self as protocol, BUS_NAME, MANAGER_INTERFACE, MANAGER_PATH};
use std::{collections::HashMap, fs, os::unix::fs::MetadataExt,
path::Path, sync::{Arc, RwLock}, time::Duration};
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Str, Value};
pub type Dictionary = HashMap<String, OwnedValue>;
fn text(s: impl Into<String>) -> OwnedValue { OwnedValue::from(Str::from(s.into())) }
fn strings(values: Vec<String>) -> OwnedValue {
OwnedValue::try_from(Value::from(values)).expect("string arrays contain no file descriptors")
}
fn dictionary(value: Dictionary) -> OwnedValue { OwnedValue::from(value) }
#[derive(Debug, zbus::DBusError)]
#[zbus(prefix = "org.archipelago.System1.Error")]
pub enum BusError {
Unsupported(String),
Unavailable(String),
InvalidArgument(String),
PlanStale(String),
NotAuthorized(String),
AuthenticationRequired(String),
}
struct Manager {
status: Arc<RwLock<observation::Snapshot>>,
}
#[zbus::interface(name = "org.archipelago.System1.Manager")]
#[allow(unused_variables)]
impl Manager {
#[zbus(out_args("capabilities"))]
fn get_capabilities(&self) -> Dictionary {
HashMap::from([
("api_major".into(), OwnedValue::from(1_u32)),
("api_minor".into(), OwnedValue::from(1_u32)),
("operations".into(), strings(vec!["GetCapabilities".into(), "GetStatus".into()])),
("features".into(), strings(vec![])),
("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)),
]))),
])
}
#[zbus(out_args("status"))]
fn get_status(&self) -> Result<Dictionary, BusError> {
self.status.read().map_err(|_| BusError::Unavailable("Status observer unavailable".into())).map(|s| s.wire())
}
#[zbus(property)]
fn status_revision(&self) -> zbus::fdo::Result<u64> {
self.status.read().map(|s| s.revision).map_err(|_| zbus::fdo::Error::Failed("Status observer unavailable".into()))
}
// No admission, journal write or implicit privileged CLI fallback on these paths.
#[zbus(out_args("transaction"))]
fn refresh(&self, options: Dictionary) -> Result<OwnedObjectPath, BusError> { unsupported() }
#[zbus(out_args("transaction"))]
fn get_update_details(&self, target: &str, options: Dictionary) -> Result<OwnedObjectPath, BusError> { unsupported() }
#[zbus(out_args("transaction"))]
fn prepare_update(&self, target: &str, options: Dictionary) -> Result<OwnedObjectPath, BusError> { unsupported() }
#[zbus(out_args("transaction"))]
fn download(&self, plan_id: &str, options: Dictionary) -> Result<OwnedObjectPath, BusError> { unsupported() }
#[zbus(out_args("transaction"))]
fn stage(&self, plan_id: &str, options: Dictionary) -> Result<OwnedObjectPath, BusError> { unsupported() }
#[zbus(out_args("transaction"))]
fn get_transaction(&self, operation_id: &str) -> Result<OwnedObjectPath, BusError> { unsupported() }
#[zbus(out_args("records", "next_cursor"))]
fn list_transactions(&self, cursor: &str, limit: u32) -> Result<(Vec<Dictionary>, String), BusError> { unsupported() }
#[zbus(out_args("result"))]
fn validate_pending(&self, deployment_id: &str) -> Result<Dictionary, BusError> { unsupported() }
}
struct ObjectRegistry { status: Arc<RwLock<observation::Snapshot>> }
// RFC-0012 additionally includes the manager itself in its root snapshot.
#[zbus::interface(name = "org.freedesktop.DBus.ObjectManager")]
impl ObjectRegistry {
fn get_managed_objects(&self) -> Result<HashMap<OwnedObjectPath, HashMap<String, Dictionary>>, BusError> {
let revision = self.status.read().map_err(|_| BusError::Unavailable("Status observer unavailable".into()))?.revision;
Ok(HashMap::from([(OwnedObjectPath::try_from(MANAGER_PATH).expect("constant object path"),
HashMap::from([(MANAGER_INTERFACE.into(), HashMap::from([("StatusRevision".into(), OwnedValue::from(revision))]))]))]))
}
#[zbus(signal)]
async fn interfaces_added(emitter: &zbus::object_server::SignalEmitter<'_>,
object_path: OwnedObjectPath, interfaces_and_properties: HashMap<String, Dictionary>) -> zbus::Result<()>;
#[zbus(signal)]
async fn interfaces_removed(emitter: &zbus::object_server::SignalEmitter<'_>,
object_path: OwnedObjectPath, interfaces: Vec<String>) -> zbus::Result<()>;
}
fn unsupported<T>() -> Result<T, BusError> {
Err(BusError::Unsupported("Operation is not enabled in this service build; inspect GetCapabilities".into()))
}
pub fn run() -> Result<(), String> {
if fs::metadata("/proc/self").map_err(|e| e.to_string())?.uid() != 0 {
return Err("archipelagod requires the system service identity".into());
}
if !Path::new("/run/ostree-booted").exists() {
return Err("archipelagod only supports installed OSTree systems".into());
}
let directory = Path::new("/var/lib/archipelago/service");
let observer = observation::Store::open(directory)?;
let status = Arc::new(RwLock::new(observer.initial()?));
let connection = zbus::blocking::connection::Builder::system().map_err(|e| e.to_string())?
.serve_at(MANAGER_PATH, Manager { status: status.clone() }).map_err(|e| e.to_string())?
.serve_at(MANAGER_PATH, ObjectRegistry { status: status.clone() }).map_err(|e| e.to_string())?
.name(BUS_NAME).map_err(|e| e.to_string())?.build().map_err(|e| e.to_string())?;
// Blocking local I/O is outside zbus' dispatch executor. No network here.
// Keep ownership even if a second manual service invocation is attempted.
loop {
let before = status.read().map_err(|_| "status observer poisoned")?.clone();
let next = match observation::observe() {
Ok(next) => next,
Err(error) => {
eprintln!("local deployment observation failed: {error}");
let mut next = before.clone();
next.reconciling = true;
next
}
};
if next.content_changed(&before) {
let next = observer.save(next, before.revision)?;
let revision = next.revision;
*status.write().map_err(|_| "status observer poisoned")? = next;
connection.emit_signal(None::<&str>, MANAGER_PATH, "org.freedesktop.DBus.Properties",
"PropertiesChanged", &(MANAGER_INTERFACE,
HashMap::from([("StatusRevision", OwnedValue::from(revision))]), Vec::<String>::new()))
.map_err(|e| e.to_string())?;
}
std::thread::sleep(Duration::from_secs(5));
}
}
/// Explicit development client, not an automatic fallback or installed CLI cutover.
pub fn inspect(capabilities: bool) -> Result<(), String> {
let bus = zbus::blocking::Connection::system().map_err(|e| e.to_string())?;
let proxy = zbus::blocking::Proxy::new(&bus, BUS_NAME, MANAGER_PATH, MANAGER_INTERFACE).map_err(|e| e.to_string())?;
let fields: Dictionary = proxy.call(if capabilities { "GetCapabilities" } else { "GetStatus" }, &()).map_err(|e| e.to_string())?;
println!("{}", serde_json::to_string_pretty(&fields).map_err(|e| e.to_string())?);
Ok(())
}

144
src/service/observation.rs Normal file
View file

@ -0,0 +1,144 @@
//! Durable revision for local OSTree observations; not the legacy software cache.
use super::{Dictionary, dictionary, text};
use archipelago_contracts::system_bus::checksum;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{fs::{self, File, OpenOptions}, io::Write,
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, path::{Path, PathBuf}, process::Command};
use zbus::zvariant::{OwnedObjectPath, OwnedValue};
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Deployment {
pub deployment_id: String,
pub checksum: String,
}
impl Deployment {
fn wire(&self, pending: bool) -> Dictionary {
let mut map = Dictionary::from([
("deployment_id".into(), text(&self.deployment_id)),
("checksum".into(), text(&self.checksum)),
]);
if pending { map.insert("reboot_required".into(), OwnedValue::from(true)); }
map
}
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
pub version: u32,
pub revision: u64,
pub booted: Option<Deployment>,
pub pending: Option<Deployment>,
pub reconciling: bool,
}
impl Snapshot {
pub fn wire(&self) -> Dictionary {
Dictionary::from([
("revision".into(), OwnedValue::from(self.revision)),
("booted".into(), dictionary(self.booted.as_ref().map(|d| d.wire(false)).unwrap_or_default())),
("pending".into(), dictionary(self.pending.as_ref().map(|d| d.wire(true)).unwrap_or_default())),
("desired".into(), dictionary(Dictionary::new())),
("reconciling".into(), OwnedValue::from(self.reconciling)),
("active_transactions".into(), OwnedValue::try_from(zbus::zvariant::Value::from(Vec::<OwnedObjectPath>::new())).expect("object paths contain no FDs")),
("update".into(), dictionary(Dictionary::from([
("state".into(), text("unknown")), ("target".into(), text("")),
("checked_at_usec".into(), OwnedValue::from(0_u64)),
("stale".into(), OwnedValue::from(true)),
("details_state".into(), text("unknown")),
("last_error".into(), dictionary(Dictionary::new())),
]))),
])
}
pub fn content_changed(&self, other: &Self) -> bool {
self.booted != other.booted || self.pending != other.pending || self.reconciling != other.reconciling
}
}
pub struct Store { directory: PathBuf, _owner: File }
impl Store {
pub fn open(directory: &Path) -> Result<Self, String> {
// systemd creates the parent StateDirectory before the service starts.
if !directory.exists() {
fs::DirBuilder::new().mode(0o700).create(directory).map_err(|e| e.to_string())?;
File::open(directory.parent().ok_or("missing state parent")?).and_then(|f| f.sync_all()).map_err(|e| e.to_string())?;
}
let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?;
if !metadata.is_dir() || metadata.uid() != 0 || metadata.mode() & 0o077 != 0 {
return Err("service state directory must be private and root-owned".into());
}
let lock = OpenOptions::new().create(true).truncate(false).write(true).mode(0o600)
.open(directory.join("owner.lock")).map_err(|e| e.to_string())?;
lock.try_lock().map_err(|_| "service observer already owned")?;
Ok(Self { directory: directory.into(), _owner: lock })
}
pub fn initial(&self) -> Result<Snapshot, String> {
let path = self.directory.join("observation.json");
let old = if path.exists() {
let meta = fs::symlink_metadata(&path).map_err(|e| e.to_string())?;
if !meta.is_file() || meta.len() > 65536 || meta.uid() != 0 || meta.mode() & 0o077 != 0 { return Err("invalid observation file".into()); }
let value: Value = serde_json::from_slice(&fs::read(path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
if value["version"] != 1 { return Err("unsupported observation version; retained".into()); }
serde_json::from_value::<Snapshot>(value).map_err(|e| e.to_string())?
} else { Snapshot { version: 1, revision: 0, booted: None, pending: None, reconciling: true } };
let mut next = old.clone();
next.reconciling = true;
self.save(next, old.revision)
}
pub fn save(&self, mut next: Snapshot, revision: u64) -> Result<Snapshot, String> {
next.revision = revision.checked_add(1).ok_or("status revision overflow")?;
let temp = self.directory.join("observation.tmp");
// The private directory and lifetime lock exclude competing writers.
let mut file = OpenOptions::new().write(true).create(true).truncate(true).mode(0o600)
.open(&temp).map_err(|e| e.to_string())?;
file.write_all(&serde_json::to_vec(&next).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
file.sync_all().map_err(|e| e.to_string())?;
fs::rename(temp, self.directory.join("observation.json")).map_err(|e| e.to_string())?;
File::open(&self.directory).and_then(|f| f.sync_all()).map_err(|e| e.to_string())?;
Ok(next)
}
}
pub fn observe() -> Result<Snapshot, String> {
let lock = OpenOptions::new().create(true).truncate(false).write(true).mode(0o600)
.open("/run/archipelago-compose.lock").map_err(|e| e.to_string())?;
lock.try_lock().map_err(|_| "host engine busy; cached observation remains reconciling")?;
let result = Command::new("timeout").args(["--kill-after=2", "10", "ostree", "admin", "status", "--json"])
.env("LC_ALL", "C").output().map_err(|e| e.to_string())?;
if !result.status.success() || result.stdout.len() > 1024 * 1024 { return Err("local OSTree status unavailable".into()); }
parse(&serde_json::from_slice(&result.stdout).map_err(|e| e.to_string())?)
}
fn parse(value: &Value) -> Result<Snapshot, String> {
let mut next = Snapshot { version: 1, revision: 0, booted: None, pending: None, reconciling: false };
for entry in value["deployments"].as_array().ok_or("missing deployments")? {
if entry["stateroot"] != "archipelago" { continue; }
let booted = entry["booted"] == true;
let pending = entry["pending"] == true || entry["staged"] == true;
if !booted && !pending { continue; }
let commit = entry["checksum"].as_str().filter(|s| checksum(s)).ok_or("invalid deployment checksum")?;
let serial = entry["serial"].as_u64().ok_or("missing deployment serial")?;
let deployment = Deployment { deployment_id: format!("archipelago/{commit}.{serial}"), checksum: commit.into() };
if booted && pending { return Err("ambiguous booted/pending role".into()); }
let slot = if booted { &mut next.booted } else { &mut next.pending };
if slot.replace(deployment).is_some() { return Err("ambiguous deployment identity".into()); }
}
if next.booted.is_none() { return Err("no booted Archipelago deployment".into()); }
Ok(next)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn same_commit_different_serials_remain_distinct() {
let hash = "a".repeat(64);
let s = parse(&json!({"deployments":[
{"stateroot":"archipelago","checksum":hash,"serial":0,"booted":true},
{"stateroot":"archipelago","checksum":hash,"serial":1,"staged":true}]})).unwrap();
assert_ne!(s.booted.unwrap().deployment_id, s.pending.unwrap().deployment_id);
assert!(parse(&json!({"deployments":[{"stateroot":"archipelago","checksum":hash,"booted":true}]})).is_err());
}
}

View file

@ -177,7 +177,16 @@ pub fn plan_json(save: bool) -> Result<(), String> {
plan_output(save, true, true)
}
pub fn diff() -> Result<(), String> { plan_output(false, false, true) }
fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(), String> {
/// Shared planning result. Formatting is a client concern; the future service
/// admission layer must bind this to its journal before advertising PrepareUpdate.
pub(crate) struct PreparedUpdate {
pub plan: Value,
pub plan_id: Option<String>,
}
pub(crate) fn prepare(save: bool, include_diff: bool, exact_target: Option<&str>) -> Result<PreparedUpdate, String> {
if exact_target.is_some_and(|s| !digest(s)) { return Err("invalid exact target checksum".into()); }
let _lock = lock()?;
reconcile_operations()?;
let binding = binding()?;
@ -191,6 +200,9 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(),
}
let reference = binding["reference"].as_str().ok_or("missing reference")?;
let target = summary_commit(&repo(&["remote", "summary", REMOTE])?, &reference)?;
if exact_target.is_some_and(|expected| expected != target) {
return Err("verified track target differs from the requested target; no implicit retarget".into());
}
require_newer(&base, &target)?;
let mut plan = json!({"version":3,"binding":binding,"variant":variant()?,"reference":reference,
"target":target,"base":base,"requested":requested,"initial":state});
@ -202,7 +214,22 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(),
plan["package_changes"] = json!(crate::package_diff::between(&before, &after)?);
plan["package_changes_scope"] = json!("managed-base");
}
if !save {
let plan_id = if save {
let temp = Path::new(STATE).join("plan.tmp");
write(&temp, &plan)?;
let hash = output("sha256sum", &[temp.to_str().unwrap()])?.split_whitespace().next().ok_or("missing digest")?.to_string();
fs::rename(&temp, plan_path(&hash)?).map_err(|e| e.to_string())?;
Some(hash)
} else { None };
Ok(PreparedUpdate { plan, plan_id })
}
fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(), String> {
let PreparedUpdate { plan, plan_id } = prepare(save, include_diff, None)?;
let reference = plan["reference"].as_str().ok_or("missing plan reference")?;
let base = plan["base"].as_str().ok_or("missing plan base")?;
let target = plan["target"].as_str().ok_or("missing plan target")?;
if plan_id.is_none() {
if json_output { println!("{}", serde_json::to_string_pretty(&plan).unwrap()); }
else {
println!("Track: {reference}\nCurrent: {base}\nTarget: {target}");
@ -217,10 +244,7 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(),
}
return Ok(());
}
let temp = Path::new(STATE).join("plan.tmp");
write(&temp, &plan)?;
let hash = output("sha256sum", &[temp.to_str().unwrap()])?.split_whitespace().next().ok_or("missing digest")?.to_string();
fs::rename(&temp, plan_path(&hash)?).map_err(|e| e.to_string())?;
let hash = plan_id.ok_or("missing saved plan identity")?;
if json_output {
println!("{}", serde_json::to_string_pretty(&json!({"plan_id":hash,"plan":plan})).unwrap());
} else {