Skip to content

Commit b528765

Browse files
committed
Add portal backend impl
1 parent c2229f0 commit b528765

File tree

6 files changed

+254
-0
lines changed

6 files changed

+254
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
/target
2+
/portal/target
23
Cargo.lock
34
cli/target

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ resolver = "2"
44
members = [
55
"client",
66
"cli",
7+
"portal-impl",
78
]

portal-impl/Cargo.toml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
[package]
2+
name = "oo7-portal-impl"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
tokio = { version = "1.17", features = [ "macros", "io-util", "rt-multi-thread" ] }
8+
futures-util = "0.3"
9+
futures-channel = "0.3"
10+
oo7 = { path = "../client", default-features = false, features = ["tokio", "native_crypto"] }
11+
ring = "0.17.5"
12+
secrecy = { version = "0.8", features = [ "alloc" ] }
13+
serde = { version = "1.0", features = ["derive"] }
14+
tracing = "0.1"
15+
tracing-subscriber = "0.3"
16+
zbus = "3.5.0"
17+
zeroize = { version = "1", features = ["zeroize_derive"] }

portal-impl/data/oo7-portal.portal

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[portal]
2+
DBusName=org.freedesktop.impl.portal.desktop.oo7
3+
Interfaces=org.freedesktop.impl.portal.Secret
4+
UseIn=gnome

portal-impl/data/oo7-portal.service

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[D-BUS Service]
2+
Name=org.freedesktop.impl.portal.Secret
3+
Exec=@bindir@/oo7-portal

portal-impl/src/main.rs

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
use std::{
2+
collections::HashMap,
3+
future::pending,
4+
os::fd::{AsRawFd, FromRawFd},
5+
sync::{Arc, Mutex},
6+
};
7+
8+
use futures_util::FutureExt;
9+
use oo7::{
10+
dbus::{Algorithm, Service},
11+
zbus::{self, dbus_interface, zvariant, zvariant::Type},
12+
};
13+
use ring::rand::SecureRandom;
14+
use serde::Serialize;
15+
use tokio::io::AsyncWriteExt;
16+
use zvariant::OwnedObjectPath;
17+
18+
const PORTAL_VERSION: u32 = 1;
19+
const PORTAL_SECRET_SIZE: usize = 64;
20+
const PORTAL_NAME: &str = "org.freedesktop.impl.portal.desktop.oo7";
21+
const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop";
22+
23+
#[derive(Serialize, PartialEq, Eq, Debug, Type)]
24+
#[doc(hidden)]
25+
enum ResponseType {
26+
Success = 0,
27+
Cancelled = 1,
28+
Other = 2,
29+
}
30+
31+
#[derive(zbus::DBusError, Debug)]
32+
enum Error {
33+
Msg(String),
34+
}
35+
36+
impl Error {
37+
fn new(msg: &str) -> Error {
38+
Error::Msg(msg.to_string())
39+
}
40+
}
41+
42+
impl From<oo7::dbus::Error> for Error {
43+
fn from(err: oo7::dbus::Error) -> Self {
44+
Error::new(&err.to_string())
45+
}
46+
}
47+
48+
struct Secret;
49+
50+
#[dbus_interface(name = "org.freedesktop.impl.portal.Secret")]
51+
impl Secret {
52+
#[dbus_interface(property, name = "version")]
53+
fn version(&self) -> u32 {
54+
PORTAL_VERSION
55+
}
56+
57+
#[dbus_interface(out_args("response", "results"))]
58+
async fn retrieve_secret(
59+
&self,
60+
#[zbus(object_server)] object_server: &zbus::ObjectServer,
61+
handle: OwnedObjectPath,
62+
app_id: &str,
63+
fd: zvariant::Fd,
64+
_options: HashMap<&str, zvariant::Value<'_>>,
65+
) -> Result<(ResponseType, HashMap<&str, zvariant::OwnedValue>), Error> {
66+
tracing::debug!("Got request from {app_id} with options: {_options:?}");
67+
68+
let (sender, receiver) = futures_channel::oneshot::channel();
69+
70+
if let Err(err) = Request::serve(object_server, handle.clone(), sender).await {
71+
tracing::error!("Could not register object {handle}: {err}");
72+
}
73+
74+
let fut_1 = async move {
75+
let res = match retrieve_secret_inner(app_id, fd).await {
76+
Ok(res) => Ok((ResponseType::Success, res)),
77+
Err(err) => {
78+
tracing::error!("could not retrieve secret: {err}");
79+
Ok((ResponseType::Other, HashMap::new()))
80+
}
81+
};
82+
83+
// We do not accept Close request anymore here.
84+
tracing::debug!("Object {handle} handled");
85+
object_server
86+
.remove::<Request, &zvariant::OwnedObjectPath>(&handle)
87+
.await
88+
.unwrap();
89+
90+
res
91+
};
92+
93+
let fut_2 = async move {
94+
receiver.await.unwrap();
95+
Ok((ResponseType::Cancelled, HashMap::new()))
96+
};
97+
98+
let t1 = fut_1.fuse();
99+
let t2 = fut_2.fuse();
100+
101+
futures_util::pin_mut!(t1, t2);
102+
103+
futures_util::select! {
104+
fut_1_res = t1 => fut_1_res,
105+
fut_2_res = t2 => fut_2_res,
106+
}
107+
}
108+
}
109+
110+
fn generate_secret() -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
111+
let mut secret = [0; PORTAL_SECRET_SIZE];
112+
let rand = ring::rand::SystemRandom::new();
113+
rand.fill(&mut secret)
114+
.map_err(|err| Error::new(&err.to_string()))?;
115+
Ok(zeroize::Zeroizing::new(secret.to_vec()))
116+
}
117+
118+
async fn retrieve_secret_inner(
119+
app_id: &str,
120+
fd: zvariant::Fd,
121+
) -> Result<HashMap<&'static str, zvariant::OwnedValue>, Error> {
122+
let service = Service::new(Algorithm::Encrypted)
123+
.await
124+
.or(Service::new(Algorithm::Plain).await)?;
125+
let collection = service.default_collection().await?;
126+
let attributes = HashMap::from([("app_id", app_id)]);
127+
128+
let secret = if let Some(item) = collection
129+
.search_items(attributes.clone())
130+
.await
131+
.map_err(|err| Error::new(&err.to_string()))?
132+
.first()
133+
{
134+
item.secret().await?
135+
} else {
136+
tracing::debug!("Could not find secret for {app_id}, creating one");
137+
let secret = generate_secret()?;
138+
collection
139+
.create_item(
140+
&format!("Secret Portal token for {app_id}"),
141+
attributes,
142+
&secret,
143+
true,
144+
// TODO Find a better one.
145+
"text/plain",
146+
)
147+
.await?;
148+
149+
secret
150+
};
151+
152+
// Write the secret to the FD.
153+
let raw_fd = fd.as_raw_fd();
154+
let std_stream = unsafe { std::os::unix::net::UnixStream::from_raw_fd(raw_fd) };
155+
let mut stream =
156+
tokio::net::UnixStream::from_std(std_stream).map_err(|e| Error::new(&e.to_string()))?;
157+
stream
158+
.write(&secret)
159+
.await
160+
.map_err(|e| Error::new(&e.to_string()))?;
161+
162+
Ok(HashMap::new())
163+
}
164+
165+
#[tokio::main]
166+
async fn main() -> Result<(), zbus::Error> {
167+
tracing_subscriber::fmt::init();
168+
169+
let backend = Secret;
170+
let cnx = zbus::ConnectionBuilder::session()?
171+
.serve_at(PORTAL_PATH, backend)?
172+
.build()
173+
.await?;
174+
// NOTE For debugging.
175+
let flags = zbus::fdo::RequestNameFlags::ReplaceExisting
176+
| zbus::fdo::RequestNameFlags::AllowReplacement;
177+
cnx.request_name_with_flags(PORTAL_NAME, flags).await?;
178+
179+
loop {
180+
pending::<()>().await;
181+
}
182+
}
183+
184+
struct Request {
185+
handle_path: zvariant::OwnedObjectPath,
186+
sender: Arc<Mutex<Option<futures_channel::oneshot::Sender<()>>>>,
187+
}
188+
189+
#[dbus_interface(name = "org.freedesktop.impl.portal.Request")]
190+
impl Request {
191+
async fn close(
192+
&self,
193+
#[zbus(object_server)] server: &zbus::ObjectServer,
194+
) -> zbus::fdo::Result<()> {
195+
tracing::debug!("Object {} closed", self.handle_path);
196+
server
197+
.remove::<Self, &zvariant::OwnedObjectPath>(&self.handle_path)
198+
.await?;
199+
200+
if let Ok(mut guard) = self.sender.lock() {
201+
if let Some(sender) = (*guard).take() {
202+
// This will Err out if the receiver has been dropped.
203+
let _ = sender.send(());
204+
}
205+
}
206+
207+
Ok(())
208+
}
209+
}
210+
211+
impl Request {
212+
async fn serve(
213+
object_server: &zbus::ObjectServer,
214+
handle_path: OwnedObjectPath,
215+
sender: futures_channel::oneshot::Sender<()>,
216+
) -> zbus::fdo::Result<()> {
217+
tracing::debug!("Handling object {:?}", handle_path.as_str());
218+
219+
let iface = Request {
220+
handle_path: handle_path.clone(),
221+
sender: Arc::new(Mutex::new(Some(sender))),
222+
};
223+
224+
object_server.at(handle_path, iface).await?;
225+
226+
Ok(())
227+
}
228+
}

0 commit comments

Comments
 (0)