Skip to content

Commit 15e46a9

Browse files
committed
Add portal backend impl
1 parent c2229f0 commit 15e46a9

File tree

6 files changed

+268
-0
lines changed

6 files changed

+268
-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: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
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::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+
impl From<oo7::Error> for Error {
49+
fn from(err: oo7::Error) -> Self {
50+
Error::new(&err.to_string())
51+
}
52+
}
53+
54+
struct Secret;
55+
56+
#[dbus_interface(name = "org.freedesktop.impl.portal.Secret")]
57+
impl Secret {
58+
#[dbus_interface(property, name = "version")]
59+
fn version(&self) -> u32 {
60+
PORTAL_VERSION
61+
}
62+
63+
#[dbus_interface(out_args("response", "results"))]
64+
async fn retrieve_secret(
65+
&self,
66+
#[zbus(object_server)] object_server: &zbus::ObjectServer,
67+
handle: OwnedObjectPath,
68+
app_id: &str,
69+
fd: zvariant::Fd,
70+
_options: HashMap<&str, zvariant::Value<'_>>,
71+
) -> Result<(ResponseType, HashMap<&str, zvariant::OwnedValue>), Error> {
72+
tracing::debug!("Got request from {app_id} with options: {_options:?}");
73+
74+
let (sender, receiver) = futures_channel::oneshot::channel();
75+
76+
if let Err(err) = Request::serve(object_server, handle.clone(), sender).await {
77+
tracing::error!("Could not register object {handle}: {err}");
78+
}
79+
80+
let fut_1 = async move {
81+
let res = match retrieve_secret_inner(app_id, fd).await {
82+
Ok(res) => Ok((ResponseType::Success, res)),
83+
Err(err) => {
84+
tracing::error!("could not retrieve secret: {err}");
85+
Ok((ResponseType::Other, HashMap::new()))
86+
}
87+
};
88+
89+
// We do not accept Close request anymore here.
90+
tracing::debug!("Object {handle} handled");
91+
object_server
92+
.remove::<Request, &zvariant::OwnedObjectPath>(&handle)
93+
.await
94+
.unwrap();
95+
96+
res
97+
};
98+
99+
let fut_2 = async move {
100+
receiver.await.unwrap();
101+
Ok((ResponseType::Cancelled, HashMap::new()))
102+
};
103+
104+
let t1 = fut_1.fuse();
105+
let t2 = fut_2.fuse();
106+
107+
futures_util::pin_mut!(t1, t2);
108+
109+
futures_util::select! {
110+
fut_1_res = t1 => fut_1_res,
111+
fut_2_res = t2 => fut_2_res,
112+
}
113+
}
114+
}
115+
116+
fn generate_secret() -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
117+
let mut secret = [0; PORTAL_SECRET_SIZE];
118+
let rand = ring::rand::SystemRandom::new();
119+
rand.fill(&mut secret)
120+
.map_err(|e| Error::new(&e.to_string()))?;
121+
Ok(zeroize::Zeroizing::new(secret.to_vec()))
122+
}
123+
124+
async fn retrieve_secret_inner(
125+
app_id: &str,
126+
fd: zvariant::Fd,
127+
) -> Result<HashMap<&'static str, zvariant::OwnedValue>, Error> {
128+
let collection = collection().await?;
129+
let attributes = HashMap::from([("app_id", app_id)]);
130+
131+
let secret = if let Some(item) = collection.search_items(attributes.clone()).await?.first() {
132+
item.secret().await?
133+
} else {
134+
tracing::debug!("Could not find secret for {app_id}, creating one");
135+
let secret = generate_secret()?;
136+
collection
137+
.create_item(
138+
&format!("Secret Portal token for {app_id}"),
139+
attributes,
140+
&secret,
141+
true,
142+
// TODO Find a better one.
143+
"text/plain",
144+
)
145+
.await?;
146+
147+
secret
148+
};
149+
150+
// Write the secret to the FD.
151+
let raw_fd = fd.as_raw_fd();
152+
let std_stream = unsafe { std::os::unix::net::UnixStream::from_raw_fd(raw_fd) };
153+
let mut stream =
154+
tokio::net::UnixStream::from_std(std_stream).map_err(|e| Error::new(&e.to_string()))?;
155+
stream
156+
.write(&secret)
157+
.await
158+
.map_err(|e| Error::new(&e.to_string()))?;
159+
160+
Ok(HashMap::new())
161+
}
162+
163+
#[tokio::main]
164+
async fn main() -> Result<(), zbus::Error> {
165+
tracing_subscriber::fmt::init();
166+
167+
let backend = Secret;
168+
let cnx = zbus::ConnectionBuilder::session()?
169+
.serve_at(PORTAL_PATH, backend)?
170+
.build()
171+
.await?;
172+
// NOTE For debugging.
173+
let flags = zbus::fdo::RequestNameFlags::ReplaceExisting
174+
| zbus::fdo::RequestNameFlags::AllowReplacement;
175+
cnx.request_name_with_flags(PORTAL_NAME, flags).await?;
176+
177+
loop {
178+
pending::<()>().await;
179+
}
180+
}
181+
182+
struct Request {
183+
handle_path: zvariant::OwnedObjectPath,
184+
sender: Arc<Mutex<Option<futures_channel::oneshot::Sender<()>>>>,
185+
}
186+
187+
#[dbus_interface(name = "org.freedesktop.impl.portal.Request")]
188+
impl Request {
189+
async fn close(
190+
&self,
191+
#[zbus(object_server)] server: &zbus::ObjectServer,
192+
) -> zbus::fdo::Result<()> {
193+
tracing::debug!("Object {} closed", self.handle_path);
194+
server
195+
.remove::<Self, &zvariant::OwnedObjectPath>(&self.handle_path)
196+
.await?;
197+
198+
if let Ok(mut guard) = self.sender.lock() {
199+
if let Some(sender) = (*guard).take() {
200+
// This will Err out if the receiver has been dropped.
201+
let _ = sender.send(());
202+
}
203+
}
204+
205+
Ok(())
206+
}
207+
}
208+
209+
impl Request {
210+
async fn serve(
211+
object_server: &zbus::ObjectServer,
212+
handle_path: OwnedObjectPath,
213+
sender: futures_channel::oneshot::Sender<()>,
214+
) -> zbus::fdo::Result<()> {
215+
tracing::debug!("Handling object {:?}", handle_path.as_str());
216+
217+
let iface = Request {
218+
handle_path: handle_path.clone(),
219+
sender: Arc::new(Mutex::new(Some(sender))),
220+
};
221+
222+
object_server.at(handle_path, iface).await?;
223+
224+
Ok(())
225+
}
226+
}
227+
228+
async fn collection<'a>() -> Result<oo7::dbus::Collection<'a>, oo7::Error> {
229+
// TODO Store in a OnceCell.
230+
let service = Service::new().await?;
231+
let collection = match service.default_collection().await {
232+
Ok(c) => Ok(c),
233+
Err(oo7::dbus::Error::NotFound(_)) => {
234+
service
235+
.create_collection("Login", Some(oo7::dbus::DEFAULT_COLLECTION))
236+
.await
237+
}
238+
Err(e) => Err(e),
239+
}?;
240+
241+
Ok(collection)
242+
}

0 commit comments

Comments
 (0)