⎇ d88a9c57914ac7870b43a7a4f616510161278237
crates/ente-polkit-compat/src/main.rs
Historia
Quién tocó qué
crudo
Persistencia setters, compat-resolved, journald→CAS, compat-polkit
1//! ente-polkit-compat: shim de `org.freedesktop.PolicyKit1.Authority`.
2//!
3//! Polkit autoriza llamadas privilegiadas (e.g. SetHostname, PowerOff).
4//! En el fractal no usamos polkit como gatekeeper — la auth se hace en
5//! el bus interno via SO_PEERCRED y capability grants. Pero apps que
6//! usan polkit (gnome-control-center, etc) bloquean en `CheckAuthorization`
7//! si no responde nadie.
8//!
9//! Este shim responde "is_authorized=true" siempre — el fractal queda
10//! como sistema confiado. El logging deja audit trail de qué acciones se
11//! han pedido para futuro análisis.
12//!
13//! Producción real: integrar con el grant system del bus interno —
14//! CheckAuthorization solicita un token al graph y devuelve true/false
15//! según el resultado.
16
17use ente_bus::{BusClient, BusRequest, BusResponse};
18use ente_card::Capability;
19use std::collections::HashMap;
20use tokio::signal::unix::{signal, SignalKind};
21use tracing::{info, warn};
22use tracing_subscriber::EnvFilter;
23use zbus::{fdo, interface, zvariant::OwnedValue};
24
25const BUS_NAME: &str = "org.freedesktop.PolicyKit1";
26const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/Authority";
27
28#[tokio::main(flavor = "current_thread")]
29async fn main() -> anyhow::Result<()> {
30 init_tracing();
31 info!("ente-polkit-compat: arrancando");
32 announce_to_fractal().await;
33
34 let manager = PolkitAuthority;
35 let conn_result = zbus::connection::Builder::system()
36 .and_then(|b| b.name(BUS_NAME))
37 .and_then(|b| b.serve_at(OBJ_PATH, manager));
38 match conn_result {
39 Ok(builder) => match builder.build().await {
40 Ok(_conn) => {
41 info!(name = BUS_NAME, "name acquired, sirviendo");
42 wait_for_term().await
43 }
44 Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
45 },
46 Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
47 }
48}
49
50struct PolkitAuthority;
51
52/// Wire format de Polkit: `Subject = (s, a{sv})` — kind ("unix-session",
53/// "unix-process", "system-bus-name") + detalles. El detail típico:
54/// {"pid": u32, "start-time": u64, "uid": u32}
55type Subject = (String, HashMap<String, OwnedValue>);
56
57/// Resultado de `CheckAuthorization`: `(b, b, a{ss})` —
58/// is_authorized, is_challenge, details.
59type AuthResult = (bool, bool, HashMap<String, String>);
60
61#[interface(name = "org.freedesktop.PolicyKit1.Authority")]
62impl PolkitAuthority {
63 async fn check_authorization(
64 &self,
65 subject: Subject,
66 action_id: String,
67 _details: HashMap<String, String>,
68 _flags: u32,
69 _cancellation_id: String,
70 ) -> fdo::Result<AuthResult> {
71 let (subj_kind, subj_details) = subject;
72 let pid = subj_details.get("pid")
73 .and_then(|v| u32::try_from(v).ok());
74 let uid = subj_details.get("uid")
75 .and_then(|v| u32::try_from(v).ok());
76 info!(%action_id, %subj_kind, ?pid, ?uid, "CheckAuthorization → ALLOW");
77 // Always-yes: fractal confía en todos sus Entes (auth real está en el bus).
78 Ok((true, false, HashMap::new()))
79 }
80
81 async fn check_authorization_by_async(
82 &self,
83 subject: Subject,
84 action_id: String,
85 details: HashMap<String, String>,
86 flags: u32,
87 cancellation_id: String,
88 ) -> fdo::Result<AuthResult> {
89 // Mismo comportamiento; algunos clientes llaman la versión async.
90 self.check_authorization(subject, action_id, details, flags, cancellation_id).await
91 }
92
93 async fn cancel_check_authorization(&self, _cancellation_id: String) -> fdo::Result<()> {
94 Ok(())
95 }
96
97 async fn enumerate_actions(&self, _locale: String) -> fdo::Result<Vec<EnumeratedAction>> {
98 // Devolvemos lista vacía — no enumeramos acciones registradas.
99 // El llamador (típicamente gnome-control-center settings panel)
100 // debería degradar grácilmente.
101 Ok(vec![])
102 }
103
104 async fn register_authentication_agent(
105 &self,
106 _subject: Subject,
107 _locale: String,
108 _object_path: String,
109 ) -> fdo::Result<()> {
110 info!("RegisterAuthenticationAgent (no-op)");
111 Ok(())
112 }
113
114 async fn register_authentication_agent_with_options(
115 &self,
116 _subject: Subject,
117 _locale: String,
118 _object_path: String,
119 _options: HashMap<String, OwnedValue>,
120 ) -> fdo::Result<()> {
121 Ok(())
122 }
123
124 async fn unregister_authentication_agent(
125 &self,
126 _subject: Subject,
127 _object_path: String,
128 ) -> fdo::Result<()> {
129 Ok(())
130 }
131
132 async fn authentication_agent_response(
133 &self,
134 _cookie: String,
135 _identity: (String, HashMap<String, OwnedValue>),
136 ) -> fdo::Result<()> {
137 Ok(())
138 }
139
140 async fn enumerate_temporary_authorizations(
141 &self,
142 _subject: Subject,
143 ) -> fdo::Result<Vec<TemporaryAuth>> {
144 Ok(vec![])
145 }
146
147 async fn revoke_temporary_authorizations(&self, _subject: Subject) -> fdo::Result<()> {
148 Ok(())
149 }
150
151 async fn revoke_temporary_authorization_by_id(&self, _id: String) -> fdo::Result<()> {
152 Ok(())
153 }
154
155 #[zbus(property)]
156 async fn backend_name(&self) -> String { "ente-polkit-compat".into() }
157
158 #[zbus(property)]
159 async fn backend_version(&self) -> String { env!("CARGO_PKG_VERSION").into() }
160
161 #[zbus(property)]
162 async fn backend_features(&self) -> u32 { 0 }
163}
164
165/// Wire signature de EnumerateActions item:
166/// `(ssssssuusa{ss})` — action_id, descripción, message, vendor, vendor_url,
167/// icon_name, implicit_any, implicit_inactive, implicit_active, annotations.
168type EnumeratedAction = (
169 String, String, String, String, String, String,
170 u32, u32, String, HashMap<String, String>,
171);
172
173/// Wire signature de TemporaryAuthorization:
174/// `(sssss)` — id, action_id, subject_kind, subject_detail, time_obtained, time_expires.
175/// Aquí `(string)` * 5 + 2 timestamps. Simplificamos al subset relevante.
176type TemporaryAuth = (String, String, (String, HashMap<String, OwnedValue>), u64, u64);
177
178async fn announce_to_fractal() {
179 if let Ok(mut client) = BusClient::from_env().await {
180 let req = BusRequest::Announce {
181 capabilities: vec![Capability::Endpoint {
182 interface: ente_card::InterfaceId([0xa4; 16]),
183 version: 1,
184 }],
185 };
186 match client.call(req).await {
187 Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
188 Ok(other) => warn!(?other, "Announce respuesta inesperada"),
189 Err(e) => warn!(?e, "Announce falló"),
190 }
191 }
192}
193
194async fn wait_for_term() -> anyhow::Result<()> {
195 let mut term = signal(SignalKind::terminate())?;
196 let mut int_ = signal(SignalKind::interrupt())?;
197 tokio::select! {
198 _ = term.recv() => info!("SIGTERM"),
199 _ = int_.recv() => info!("SIGINT"),
200 }
201 Ok(())
202}
203
204fn init_tracing() {
205 let filter = EnvFilter::try_from_default_env()
206 .unwrap_or_else(|_| EnvFilter::new("ente_polkit_compat=info"));
207 tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
208}