journal-query CLI, machined, polkit con grants reales, GNOME boot test

- ente-journalctl: bin nuevo en ente-journald-compat. Lee
  ~/.local/share/ente/journal/index.log, parse timestamp:source:unit:sha,
  filtra --unit/--source/--since/--grep/--tail, restituye blobs desde CAS
  y formatea (pretty | --json). Default extrae MESSAGE de journald native.
- compat-machined: org.freedesktop.machine1.Manager con
  ListMachines/GetMachine/Register/Terminate. Lista vacía + NotFound —
  apps que llaman al boot ya no quedan en timeout.
- compat-polkit: query_policy() consulta el bus interno por el cap
  POLKIT_DECISION_IFACE con blob (pid_be|uid_be|action_id_utf8). Si hay
  proveedor su byte de respuesta gobierna; si no, default-allow.
  Anuncia POLKIT_SERVICE_IFACE (separado para evitar recursión).
- docs/gnome-boot-test.md: procedimiento end-to-end para arrancar GNOME
  con ente-zero como PID 1 en QEMU. scripts/build-rootfs.sh overlaya
  binarios + symlink /init. scripts/run-vm.sh boot QEMU con KVM y GTK.
  docs/seed-gnome-test.k Card Semilla con genesis para 8 shims +
  dbus-daemon + NetworkManager + gdm.

8 compat-shims operativos en paralelo cubriendo: logind, hostnamed,
timedated, localed, journald, resolved, polkit, machined.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sergio
2026-05-04 10:13:00 +00:00
parent d88a9c5791
commit 48e41331a1
13 changed files with 959 additions and 6 deletions
+14
View File
@@ -18,6 +18,20 @@ pub const ENV_BUS_SOCK: &str = "ENTE_BUS_SOCK";
pub const ENV_ENTE_ID: &str = "ENTE_ID";
pub const MAX_FRAME: usize = 1 << 20; // 1 MiB — protección contra OOM
/// Interface UUID para decisiones de policy. Un Ente independiente
/// (separado de polkit-compat) se anuncia como proveedor de
/// `Capability::Endpoint { interface: POLKIT_DECISION_IFACE, version: 1 }`
/// para arbitrar autorizaciones. Recibe blob:
/// `pid_be | uid_be | action_id_utf8` → responde 1 byte: 1=allow, 0=deny.
pub const POLKIT_DECISION_IFACE: ente_card::InterfaceId =
ente_card::InterfaceId([0xb0; 16]);
/// Interface UUID auto-anunciado por compat-polkit. Diferente al de
/// decisión para evitar recursión (polkit-compat invoca DECISION pero
/// no es proveedor de DECISION; se anuncia como SERVICE).
pub const POLKIT_SERVICE_IFACE: ente_card::InterfaceId =
ente_card::InterfaceId([0xa4; 16]);
/// Credenciales del peer extraídas vía SO_PEERCRED al accept del bus.
/// Imposibles de falsear desde el cliente — el kernel las inyecta.
/// Definidas aquí (no en ente-zero) porque conceptualmente son atributo
+4
View File
@@ -9,6 +9,10 @@ publish.workspace = true
name = "ente-journald-compat"
path = "src/main.rs"
[[bin]]
name = "ente-journalctl"
path = "src/journalctl.rs"
[dependencies]
ente-card = { path = "../ente-card" }
ente-bus = { path = "../ente-bus" }
@@ -0,0 +1,197 @@
//! ente-journalctl: query CLI sobre el journal persistido en CAS.
//!
//! Lee el index `~/.local/share/ente/journal/index.log` (líneas
//! `timestamp_ms:source:unit:sha_hex`), filtra, y para cada match
//! restituye el blob desde CAS y lo imprime.
//!
//! Uso:
//! ente-journalctl # todo el journal
//! ente-journalctl --unit foo.service # filtra por unit
//! ente-journalctl --since 60 # últimos 60 segundos
//! ente-journalctl --grep "panic" # contiene "panic"
//! ente-journalctl --tail 20 # últimas 20 entries
//! ente-journalctl --json # output JSON-lines
use std::path::PathBuf;
struct Args {
unit: Option<String>,
since_secs: Option<u64>,
grep: Option<String>,
tail: Option<usize>,
source: Option<String>,
json: bool,
}
fn parse_args() -> Args {
let mut args = std::env::args().skip(1);
let mut a = Args {
unit: None, since_secs: None, grep: None, tail: None, source: None, json: false,
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--unit" | "-u" => a.unit = args.next(),
"--since" | "-S" => a.since_secs = args.next().and_then(|s| s.parse().ok()),
"--grep" | "-g" => a.grep = args.next(),
"--tail" | "-n" => a.tail = args.next().and_then(|s| s.parse().ok()),
"--source" => a.source = args.next(),
"--json" => a.json = true,
"-h" | "--help" => { print_help(); std::process::exit(0); }
other => {
eprintln!("argumento desconocido: {other}");
print_help();
std::process::exit(2);
}
}
}
a
}
fn print_help() {
eprintln!("ente-journalctl — query CLI del journal persistido en CAS");
eprintln!();
eprintln!("Filtros:");
eprintln!(" --unit, -u <name> Filtra por unidad (e.g. foo.service)");
eprintln!(" --source <s> journal | syslog");
eprintln!(" --since, -S <secs> Sólo últimos N segundos");
eprintln!(" --grep, -g <text> Contiene <text> en el body decoded");
eprintln!(" --tail, -n <N> Últimas N entries");
eprintln!("Output:");
eprintln!(" --json JSON-lines en lugar de pretty");
}
fn index_path() -> PathBuf {
let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") { d }
else if let Ok(h) = std::env::var("HOME") { format!("{h}/.local/share") }
else { "/var/lib".into() };
PathBuf::from(base).join("ente").join("journal").join("index.log")
}
fn now_ms() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
}
#[derive(Debug)]
struct IndexEntry {
timestamp_ms: u128,
source: String,
unit: String,
sha_hex: String,
}
fn parse_line(line: &str) -> Option<IndexEntry> {
let mut parts = line.splitn(4, ':');
let ts: u128 = parts.next()?.parse().ok()?;
let source = parts.next()?.to_string();
let unit = parts.next()?.to_string();
let sha = parts.next()?.to_string();
if sha.len() != 64 { return None; }
Some(IndexEntry { timestamp_ms: ts, source, unit, sha_hex: sha })
}
fn parse_sha(hex: &str) -> Option<[u8; 32]> {
if hex.len() != 64 { return None; }
let mut sha = [0u8; 32];
for i in 0..32 {
sha[i] = u8::from_str_radix(&hex[i*2..i*2+2], 16).ok()?;
}
Some(sha)
}
fn main() -> anyhow::Result<()> {
let args = parse_args();
let path = index_path();
if !path.exists() {
eprintln!("index no existe: {} — ¿journald-compat ha corrido?", path.display());
std::process::exit(1);
}
let raw = std::fs::read_to_string(&path)?;
let mut entries: Vec<IndexEntry> = raw.lines()
.filter_map(parse_line)
.collect();
// Filtros
let now = now_ms();
if let Some(secs) = args.since_secs {
let cutoff = now.saturating_sub(secs as u128 * 1000);
entries.retain(|e| e.timestamp_ms >= cutoff);
}
if let Some(unit) = &args.unit {
entries.retain(|e| &e.unit == unit);
}
if let Some(src) = &args.source {
entries.retain(|e| &e.source == src);
}
// tail después de filtros temporales/identidad pero antes de grep —
// grep es post porque requiere cargar bytes del CAS.
let mut out: Vec<(IndexEntry, String)> = entries.into_iter()
.filter_map(|e| {
let sha = parse_sha(&e.sha_hex)?;
let bytes = ente_cas::resolve(&sha).ok()?;
let body = String::from_utf8_lossy(&bytes).into_owned();
Some((e, body))
})
.collect();
if let Some(g) = &args.grep {
out.retain(|(_, body)| body.contains(g.as_str()));
}
if let Some(n) = args.tail {
let len = out.len();
if len > n { out.drain(..len - n); }
}
for (e, body) in out {
if args.json {
print_json(&e, &body);
} else {
print_pretty(&e, &body);
}
}
Ok(())
}
fn print_pretty(e: &IndexEntry, body: &str) {
let secs = e.timestamp_ms / 1000;
let ms = e.timestamp_ms % 1000;
let header = if e.unit == "-" {
format!("{}.{:03} [{}]", secs, ms, e.source)
} else {
format!("{}.{:03} [{}] {{{}}}", secs, ms, e.source, e.unit)
};
println!("{header}");
// Si es journald native (KEY=value lines), extraer MESSAGE.
if body.contains('=') && body.lines().any(|l| l.contains('=')) {
for line in body.lines() {
if let Some((k, v)) = line.split_once('=') {
if k.trim() == "MESSAGE" {
println!(" {v}");
return;
}
}
}
}
for line in body.trim_end().lines() {
println!(" {line}");
}
}
fn print_json(e: &IndexEntry, body: &str) {
// JSON-lines básico, sin dependencia de serde — formato simple y estable.
let escaped_body = body
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t");
let unit_field = if e.unit == "-" { "null".to_string() }
else { format!("\"{}\"", e.unit) };
println!(
r#"{{"timestamp_ms":{},"source":"{}","unit":{},"sha":"{}","body":"{}"}}"#,
e.timestamp_ms, e.source, unit_field, e.sha_hex, escaped_body
);
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "ente-machined-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-machined-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../ente-card" }
ente-bus = { path = "../ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
+186
View File
@@ -0,0 +1,186 @@
//! ente-machined-compat: shim de `org.freedesktop.machine1`.
//!
//! systemd-machined trackea VMs y containers (typically managed por systemd-nspawn).
//! En el fractal cada Ente con namespaces es candidato a "machine", pero la
//! correspondencia no es 1:1 — un Ente puede tener menos aislamiento que una
//! container completa.
//!
//! Este shim devuelve listas vacías para no romper clientes (gnome-boxes,
//! virt-manager, etc) que llaman a `ListMachines` durante boot. Métodos de
//! mutación (RegisterMachine, KillMachine) se aceptan como no-op con audit
//! log via tracing.
//!
//! Producción real: integrar con el graph del fractal — ListMachines query
//! BusRequest::ListEntes filtrado por `card.soma.namespaces.pid`.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::collections::HashMap;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface, zvariant::OwnedValue};
const BUS_NAME: &str = "org.freedesktop.machine1";
const OBJ_PATH: &str = "/org/freedesktop/machine1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-machined-compat: arrancando");
announce_to_fractal().await;
let manager = MachineManager;
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
},
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
}
}
struct MachineManager;
/// Tipo del wire format de ListMachines: `(s, s, s, u, ay, ay, t, ay)` —
/// name, class, service, leader_pid, root_directory_path, id_unix, time_obtained,
/// machine_id_bytes. systemd usa este struct simplificado.
type Machine = (String, String, String, u32, String);
#[interface(name = "org.freedesktop.machine1.Manager")]
impl MachineManager {
/// Lista vacía — no trackeamos containers todavía.
async fn list_machines(&self) -> fdo::Result<Vec<Machine>> {
Ok(vec![])
}
/// Devuelve siempre NotFound — sin machines registradas.
async fn get_machine(&self, name: String) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
Err(fdo::Error::Failed(format!("machine '{name}' no encontrada")))
}
async fn get_machine_by_pid(&self, pid: u32) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
Err(fdo::Error::Failed(format!("PID {pid} no asociado a ninguna machine")))
}
async fn register_machine(
&self,
name: String,
_id: Vec<u8>,
_service: String,
class: String,
_leader_pid: u32,
_root_directory: String,
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
info!(%name, %class, "RegisterMachine (no-op)");
Err(fdo::Error::NotSupported(
"RegisterMachine no implementado — usar Cards del fractal".into()
))
}
async fn register_machine_with_network(
&self,
name: String,
id: Vec<u8>,
service: String,
class: String,
leader_pid: u32,
root_directory: String,
_network_interfaces: Vec<i32>,
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
self.register_machine(name, id, service, class, leader_pid, root_directory).await
}
async fn create_machine(
&self,
name: String,
_id: Vec<u8>,
_service: String,
class: String,
_leader_pid: u32,
_root_directory: String,
_scope_properties: Vec<(String, OwnedValue)>,
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
info!(%name, %class, "CreateMachine (no-op)");
Err(fdo::Error::NotSupported(
"CreateMachine no implementado".into()
))
}
async fn terminate_machine(&self, name: String) -> fdo::Result<()> {
info!(%name, "TerminateMachine (no-op)");
Ok(())
}
async fn kill_machine(&self, name: String, _who: String, _signal: i32) -> fdo::Result<()> {
info!(%name, "KillMachine (no-op)");
Ok(())
}
async fn get_machine_address(&self, name: String) -> fdo::Result<Vec<(i32, Vec<u8>)>> {
warn!(%name, "GetMachineAddress (sin tracking, devuelvo vacío)");
Ok(vec![])
}
async fn get_machine_osrelease(&self, name: String) -> fdo::Result<HashMap<String, String>> {
warn!(%name, "GetMachineOSRelease (sin tracking)");
Ok(HashMap::new())
}
/// Operaciones sobre la "host machine" (PID 1 namespace) — siempre
/// disponibles. Usamos el path canónico `/org/freedesktop/machine1/machine/_host`.
async fn open_machine_login(&self, _name: String) -> fdo::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedFd)> {
Err(fdo::Error::NotSupported(
"OpenMachineLogin no implementado".into()
))
}
async fn open_machine_shell(
&self,
_name: String,
_user: String,
_path: String,
_args: Vec<String>,
_environment: Vec<String>,
) -> fdo::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedFd)> {
Err(fdo::Error::NotSupported("OpenMachineShell no implementado".into()))
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa5; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_machined_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
+60 -6
View File
@@ -14,11 +14,11 @@
//! CheckAuthorization solicita un token al graph y devuelve true/false
//! según el resultado.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_bus::{BusClient, BusRequest, BusResponse, POLKIT_DECISION_IFACE, POLKIT_SERVICE_IFACE};
use ente_card::Capability;
use std::collections::HashMap;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface, zvariant::OwnedValue};
@@ -73,9 +73,12 @@ impl PolkitAuthority {
.and_then(|v| u32::try_from(v).ok());
let uid = subj_details.get("uid")
.and_then(|v| u32::try_from(v).ok());
info!(%action_id, %subj_kind, ?pid, ?uid, "CheckAuthorization → ALLOW");
// Always-yes: fractal confía en todos sus Entes (auth real está en el bus).
Ok((true, false, HashMap::new()))
// Pregunta al bus interno del fractal si hay un policy provider.
// Si lo hay, su decisión gobierna. Si no (NoProvider), default = allow.
let decision = query_policy(&action_id, pid, uid).await;
info!(%action_id, %subj_kind, ?pid, ?uid, ?decision, "CheckAuthorization");
Ok((decision.allow, false, HashMap::new()))
}
async fn check_authorization_by_async(
@@ -175,11 +178,62 @@ type EnumeratedAction = (
/// Aquí `(string)` * 5 + 2 timestamps. Simplificamos al subset relevante.
type TemporaryAuth = (String, String, (String, HashMap<String, OwnedValue>), u64, u64);
/// Resultado de una consulta de policy al fractal.
#[derive(Debug)]
struct PolicyDecision {
allow: bool,
/// Origen: "fractal" si vino del bus, "default-allow" si no había proveedor.
source: &'static str,
}
/// Pregunta al bus interno: ¿hay alguien que decida sobre `action_id`?
/// Wire format del blob: `pid_u32_be | uid_u32_be | action_id_utf8`.
/// El proveedor responde con `Invoked { result: [0|1] }` — 1 = allow.
async fn query_policy(action_id: &str, pid: Option<u32>, uid: Option<u32>) -> PolicyDecision {
let mut blob = Vec::with_capacity(8 + action_id.len());
blob.extend_from_slice(&pid.unwrap_or(0).to_be_bytes());
blob.extend_from_slice(&uid.unwrap_or(0).to_be_bytes());
blob.extend_from_slice(action_id.as_bytes());
let mut client = match BusClient::from_env().await {
Ok(c) => c,
Err(e) => {
debug!(?e, "no bus client — default allow");
return PolicyDecision { allow: true, source: "no-bus" };
}
};
let req = BusRequest::Invoke {
cap: Capability::Endpoint {
interface: POLKIT_DECISION_IFACE,
version: 1,
},
blob,
};
match client.call(req).await {
Ok(BusResponse::Invoked { result }) => {
let allow = result.first().copied().unwrap_or(1) != 0;
PolicyDecision { allow, source: "fractal" }
}
Ok(BusResponse::Error(msg)) if msg.contains("sin proveedor") => {
// No hay policy provider — default allow.
PolicyDecision { allow: true, source: "default-allow" }
}
Ok(other) => {
warn!(?other, "policy: respuesta inesperada — default allow");
PolicyDecision { allow: true, source: "default-allow" }
}
Err(e) => {
warn!(?e, "policy: bus call falló — default allow");
PolicyDecision { allow: true, source: "default-allow" }
}
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa4; 16]),
interface: POLKIT_SERVICE_IFACE,
version: 1,
}],
};
+1
View File
@@ -155,6 +155,7 @@ fn synthesize_dev_seed() -> EntityCard {
("compat-journald", "target/debug/ente-journald-compat"),
("compat-resolved", "target/debug/ente-resolved-compat"),
("compat-polkit", "target/debug/ente-polkit-compat"),
("compat-machined", "target/debug/ente-machined-compat"),
] {
if let Some(card) = optional_native_card(
label, bin,