mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-17 09:55:03 +01:00
fix(core): save the session by replacing its keyring item (#78, B291)
Fedora 45 and 46 ship oo7-daemon 0.7.0~beta^1.e91b98a, which applies SetSecret only in memory (fixed upstream in 7fb11dd, after that snapshot). Every token rotation saved there was lost at the next reboot, and the next start found a spent refresh token. An existing entry is now written with CreateItem and replace, in the old item's collection with its label and attributes, which that build persists. A duplicate left behind is removed; the first save, a locked item, ambiguity or any failure fall back to SetSecret. No prompt is ever shown on this path. The daemon also logs a short fingerprint of the refresh token at each resume and each save, so a log across a reboot shows whether the keyring returned the last token saved.
This commit is contained in:
1 parent
ce3bfa217d
commit
64864562ef
9 files changed
+323
-8
No files matched your search
@@ -26,6 +26,7 @@ zip.workspace = true
|
||||
rusqlite.workspace = true
|
||||
keyring-core.workspace = true
|
||||
dbus-secret-service-keyring-store.workspace = true
|
||||
dbus-secret-service.workspace = true
|
||||
parking_lot.workspace = true
|
||||
async-trait.workspace = true
|
||||
libc.workspace = true
|
||||
|
||||
@@ -490,11 +490,48 @@ fn classify_verification_gate(e: ProtonError) -> Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Save `stored` to the keyring.
|
||||
///
|
||||
/// An existing entry is replaced by a new item rather than edited, because
|
||||
/// oo7 before 0.7.0 keeps an edit only in memory and a reboot brings the
|
||||
/// spent refresh token back (`docs/BUGS.md` B291). The usual write is the
|
||||
/// fallback: for the first save, and whenever replacing is not possible.
|
||||
fn write_stored(stored: &StoredSession) -> Result<()> {
|
||||
let json = Zeroizing::new(serde_json::to_string(stored)?);
|
||||
if replace_items() {
|
||||
match crate::secretservice::replace(KEYRING_SERVICE, KEYRING_USER, json.as_bytes()) {
|
||||
crate::secretservice::Replaced::Saved => return Ok(()),
|
||||
crate::secretservice::Replaced::Skipped(why) => {
|
||||
tracing::debug!(%why, "not replacing the keyring item; writing it in place");
|
||||
}
|
||||
}
|
||||
}
|
||||
with_keyring(|entry| entry.set_password(&json))
|
||||
}
|
||||
|
||||
/// Whether [`write_stored`] talks to the Secret Service directly: always,
|
||||
/// except in tests that use the in-memory store.
|
||||
#[cfg(not(test))]
|
||||
fn replace_items() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn replace_items() -> bool {
|
||||
tests::MOCK_STORE.lock().is_none()
|
||||
}
|
||||
|
||||
/// A short, one-way tag for a refresh token, for the log: enough to tell
|
||||
/// whether the token a start finds is the one the last save wrote, and
|
||||
/// nothing that helps anyone use it.
|
||||
fn fingerprint(token: &str) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
Sha256::digest(token.as_bytes())[..4]
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Load the persisted session blob, or `Error::NotLoggedIn` if absent.
|
||||
pub fn load() -> Result<StoredSession> {
|
||||
match with_keyring(|entry| entry.get_password()) {
|
||||
@@ -703,6 +740,10 @@ fn resume_stored(stored: &StoredSession) -> Result<ProtonApiSession> {
|
||||
resumed.access_token = tokens.access_token.clone();
|
||||
resumed.refresh_token = tokens.refresh_token.clone();
|
||||
}
|
||||
tracing::info!(
|
||||
refresh = %fingerprint(&resumed.refresh_token),
|
||||
"resuming the stored session"
|
||||
);
|
||||
let session = ProtonApiSession::resume(client_config(), resumed.to_params())?;
|
||||
let sink = register_refresh_handler(&session, stored.refresh_token.clone());
|
||||
if let Some(tokens) = unsaved {
|
||||
@@ -1082,8 +1123,11 @@ impl TokenSink {
|
||||
) {
|
||||
Rotation::Taken => {
|
||||
write_stored(&stored)?;
|
||||
tracing::info!(
|
||||
refresh = %fingerprint(&tokens.refresh_token),
|
||||
"successfully auto-persisted refreshed tokens in keyring"
|
||||
);
|
||||
state.stored_refresh = tokens.refresh_token;
|
||||
tracing::info!("successfully auto-persisted refreshed tokens in keyring");
|
||||
}
|
||||
Rotation::MovedOn => {
|
||||
tracing::info!(
|
||||
@@ -1408,6 +1452,48 @@ mod tests {
|
||||
keyring_core::unset_default_store();
|
||||
}
|
||||
|
||||
/// B291: every save after the first replaces the keyring item, so a
|
||||
/// provider that keeps an edited secret only in memory (oo7 before 0.7.0)
|
||||
/// still has the last one after a restart, and only one item is left.
|
||||
///
|
||||
/// Run like [`real_secret_service_survives_a_provider_restart`], in a
|
||||
/// throwaway session bus only.
|
||||
#[test]
|
||||
#[ignore = "needs a throwaway Secret Service; see real_secret_service_survives_a_provider_restart"]
|
||||
fn real_secret_service_keeps_the_last_save_across_a_provider_restart() {
|
||||
if std::env::var_os("PDFS_SECRET_SERVICE_RESTART_TEST").is_none() {
|
||||
return;
|
||||
}
|
||||
let restart = std::env::var("PDFS_RESTART_PROVIDER").expect("PDFS_RESTART_PROVIDER");
|
||||
let _turn = KEYRING.lock();
|
||||
*MOCK_STORE.lock() = None;
|
||||
keyring_core::unset_default_store();
|
||||
|
||||
for refresh in ["r1", "r2", "r3"] {
|
||||
write_stored(&stored_with(refresh)).unwrap();
|
||||
}
|
||||
let status = std::process::Command::new("sh")
|
||||
.args(["-c", &restart])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "restarting the provider failed");
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
|
||||
assert_eq!(load().unwrap().refresh_token, "r3");
|
||||
let ss =
|
||||
dbus_secret_service::SecretService::connect(dbus_secret_service::EncryptionType::Plain)
|
||||
.unwrap();
|
||||
let found = ss
|
||||
.search_items(std::collections::HashMap::from([
|
||||
("service", KEYRING_SERVICE),
|
||||
("username", KEYRING_USER),
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(found.unlocked.len() + found.locked.len(), 1);
|
||||
with_keyring(|e| e.delete_credential()).unwrap();
|
||||
keyring_core::unset_default_store();
|
||||
}
|
||||
|
||||
fn stored_with(refresh: &str) -> StoredSession {
|
||||
serde_json::from_str(&blob("").replace(r#""r""#, &format!("{refresh:?}"))).unwrap()
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod places;
|
||||
pub mod profile;
|
||||
pub mod sdkcache;
|
||||
pub mod search;
|
||||
mod secretservice;
|
||||
pub mod service;
|
||||
pub mod shell;
|
||||
pub mod similar;
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Saving a new secret into an existing Secret Service item by replacing the
|
||||
//! item, not by editing its secret (`docs/BUGS.md` B291).
|
||||
//!
|
||||
//! oo7-daemon before 0.7.0 applies `SetSecret` only in memory: the keyring
|
||||
//! file keeps the old secret, and it comes back once the daemon restarts.
|
||||
//! Fedora 45 ships such a build (`0.7.0~beta^1.e91b98a`). Every refreshed
|
||||
//! sign-in pdfs saved there was gone after a reboot, and the next start found
|
||||
//! a refresh token Proton had already spent.
|
||||
//!
|
||||
//! `CreateItem` with `replace` is written to the file there, and every
|
||||
//! provider implements it. So a secret that changes is written as a new item
|
||||
//! that replaces the old one: in the old one's collection, with its label and
|
||||
//! all of its attributes, so the provider recognises it as the same entry.
|
||||
|
||||
use dbus_secret_service::{Collection, EncryptionType, Path, SecretService};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The content type the keyring store writes its secrets with.
|
||||
const CONTENT_TYPE: &str = "application/octet-stream";
|
||||
|
||||
/// What [`replace`] did.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Replaced {
|
||||
/// The secret is saved.
|
||||
Saved,
|
||||
/// Nothing was changed; save it the usual way. Says why, for the log.
|
||||
Skipped(String),
|
||||
}
|
||||
|
||||
/// Save `secret` into the one item for `service`/`user` by replacing it.
|
||||
///
|
||||
/// Skips, changing nothing, when there is no such item yet (the store creates
|
||||
/// it), when there is more than one, when it is locked, or when the Secret
|
||||
/// Service fails before the new item exists. Never shows a prompt: one would
|
||||
/// block the caller, so it is dismissed and the write is skipped.
|
||||
pub(crate) fn replace(service: &str, user: &str, secret: &[u8]) -> Replaced {
|
||||
match try_replace(service, user, secret) {
|
||||
Ok(replaced) => replaced,
|
||||
Err(e) => Replaced::Skipped(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_replace(
|
||||
service: &str,
|
||||
user: &str,
|
||||
secret: &[u8],
|
||||
) -> Result<Replaced, dbus_secret_service::Error> {
|
||||
let ss = SecretService::connect_with_max_prompt_timeout(EncryptionType::Dh, 0)?;
|
||||
let lookup = HashMap::from([("service", service), ("username", user)]);
|
||||
let found = ss.search_items(lookup.clone())?;
|
||||
if !found.locked.is_empty() {
|
||||
return Ok(Replaced::Skipped("the item is locked".into()));
|
||||
}
|
||||
let [old] = found.unlocked.as_slice() else {
|
||||
return Ok(Replaced::Skipped(format!(
|
||||
"{} items match, not one",
|
||||
found.unlocked.len()
|
||||
)));
|
||||
};
|
||||
let Some(collection) = collection_of(&old.path) else {
|
||||
return Ok(Replaced::Skipped(format!(
|
||||
"no collection in the item path {}",
|
||||
old.path
|
||||
)));
|
||||
};
|
||||
let label = old.get_label()?;
|
||||
let attributes = old.get_attributes()?;
|
||||
let attributes: HashMap<&str, &str> = attributes
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str(), v.as_str()))
|
||||
.collect();
|
||||
let collection = Collection::new(&ss, collection);
|
||||
let new = collection.create_item(&label, attributes, secret, true, CONTENT_TYPE)?;
|
||||
|
||||
// A provider that did not match the old item leaves it next to the new
|
||||
// one, and two items make every read ambiguous.
|
||||
let after = ss.search_items(lookup)?;
|
||||
for item in after.unlocked.iter().chain(&after.locked) {
|
||||
if item.path == new.path {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = item.delete() {
|
||||
// The old item still holds the previous secret, so taking the new
|
||||
// one out leaves things as they were, for the usual write.
|
||||
if let Err(undo) = new.delete() {
|
||||
tracing::error!(
|
||||
error = %undo,
|
||||
"could not remove a duplicate keyring item; remove one of the two \
|
||||
`proton-drive-linux` entries in your keyring and sign in again"
|
||||
);
|
||||
}
|
||||
return Ok(Replaced::Skipped(format!(
|
||||
"could not remove the replaced item: {e}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(Replaced::Saved)
|
||||
}
|
||||
|
||||
/// The collection an item path belongs to: the path without its last part,
|
||||
/// as long as it is a Secret Service object path.
|
||||
fn collection_of(item: &Path<'_>) -> Option<Path<'static>> {
|
||||
let (collection, _) = item.rsplit_once('/')?;
|
||||
if !collection.starts_with("/org/freedesktop/secrets/") || collection.ends_with('/') {
|
||||
return None;
|
||||
}
|
||||
Path::new(collection.to_owned()).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn collection(item: &str) -> Option<String> {
|
||||
collection_of(&Path::new(item).unwrap()).map(|p| p.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_belongs_to_the_collection_its_path_names() {
|
||||
assert_eq!(
|
||||
collection("/org/freedesktop/secrets/collection/login/14").as_deref(),
|
||||
Some("/org/freedesktop/secrets/collection/login")
|
||||
);
|
||||
assert_eq!(
|
||||
collection("/org/freedesktop/secrets/aliases/default/3").as_deref(),
|
||||
Some("/org/freedesktop/secrets/aliases/default")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_outside_the_secret_service_names_no_collection() {
|
||||
assert_eq!(collection("/org/example/item/1"), None);
|
||||
assert_eq!(collection("/item"), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user