Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Seal the session's cookies on disk with a key the keyring keeps
Yashwanth Kamireddi2f8c3f40bf60
diff --git a/Cargo.lock b/Cargo.lockindex bd928e4..1464930 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3997,6 +3997,7 @@ dependencies = [name = "quince-auth"version = "0.1.0"dependencies = [+ "aes-gcm","anyhow","base64 0.22.1","cookie_store 0.21.1",diff --git a/README.md b/README.mdindex ef11f7c..bb83c74 100644--- a/README.md+++ b/README.md@@ -183,7 +183,7 @@ On Linux, your desktop may ask you to unlock its keyring the first time. That's## Privacy- **Local-first.** Your library lives on your computer, so every app opens instantly, even offline.-- **Your sign-in stays in your system keyring:** Secret Service (GNOME Keyring or KWallet) on Linux, Credential Manager on Windows. Two-factor sign-in is Apple's own.+- **Your sign-in stays in your system keyring:** your password and session live in the Secret Service (GNOME Keyring or KWallet) on Linux and Credential Manager on Windows, so Skykeep can sign back in by itself. Session cookies are encrypted with a key kept there too. Any program running as you can read keyring entries; [SECURITY.md](SECURITY.md) has the details. Two-factor sign-in is Apple's own.- **Clear about what it connects to:** Apple for your iCloud, the calendars you subscribe to, and GitHub's release servers to check for new versions of Skykeep. Each has a connection of its own that can reach nothing else. No Skykeep account, no analytics.- **Independent.** Skykeep is an open-source project, not affiliated with or endorsed by Apple.diff --git a/SECURITY.md b/SECURITY.mdindex 12a72b6..57919c5 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -67,11 +67,23 @@ Everything is in your user's data folder: `~/.local/share/io.github.yashwanthkamon Linux, readable by you alone (mode 700), and `%APPDATA%\io.github.yashwanthkamireddi.Skykeep`on Windows.-- **Your password, Apple Account and session tokens:** in the system keyring (the Secret- Service, such as GNOME Keyring or KWallet, on Linux; Credential Manager on Windows), never- in a file. The password is kept so a session that lapses can sign itself back in without- asking; Apple asks for a code only when it stops trusting this computer.-- **Session cookies:** `cookies.json`, readable by you alone (mode 600).+- **Your password, Apple Account and session:** in the system keyring — the Secret Service+ (GNOME Keyring or KWallet) on Linux, Credential Manager on Windows — never in a file. The+ password is kept there so Skykeep can sign back in by itself when a session lapses, and you+ sign in once; Apple asks for a code only when it stops trusting this computer. Signing out+ erases it.+- **Session cookies:** `cookies.json`, encrypted (AES-256-GCM) with a random 256-bit key+ kept in the same keyring, one key per data folder, and readable by you alone (mode 600) as+ well. The file on its own opens nothing: copied into a backup or another folder, it is of no+ use without the keyring entry. With no keyring running, the cookies are kept in memory only+ and never written. If the key is gone (the keyring was reset), the file is deleted and+ Skykeep signs in afresh from what the keyring still holds, or asks you to.+- **What that protects, and what it does not.** The keyring is locked when you are logged out+ and encrypted on disk, but while you are logged in **any program running as you can read+ Skykeep's keyring entries**, the password included — the keyring does not tell one of your+ programs from another. A program that runs as you can already read your files too; the+ keyring is the system's own place for a secret like this, which is why it is kept there+ rather than in a file of Skykeep's own.- **Your library:** `library.db` (SQLite) — notes, reminders, events, contacts, the Driveand Photos listings — and caches of pictures and files you opened. These are not encryptedby Skykeep; use full-disk encryption, as you would for the same data on a Mac.diff --git a/crates/quince-auth/Cargo.toml b/crates/quince-auth/Cargo.tomlindex 35017a6..11fa0db 100644--- a/crates/quince-auth/Cargo.toml+++ b/crates/quince-auth/Cargo.toml@@ -17,6 +17,8 @@ sha2 = "0.10"pbkdf2 = { version = "0.12", default-features = false }hmac = "0.12"rand = "0.9"+# Sealing the cookie jar on disk (sealed.rs): the same AES-GCM locked notes already build.+aes-gcm = { version = "0.10", default-features = false, features = ["aes", "alloc"] }reqwest_cookie_store = "0.8"cookie_store = { version = "0.21", features = ["serde_json"] }thiserror = "2"diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex f392ad6..a96196e 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -22,6 +22,7 @@ macro_rules! quiet {}pub mod releases;+mod sealed;pub mod session;pub mod srp;@@ -265,6 +266,83 @@ pub struct Client {/// What was last written, as a hash of the session and one of the cookies: a heartbeat that/// changed neither writes neither (see [`Client::persist`]).persisted: std::sync::Mutex<Persisted>,+ /// The cookies on disk, as this start found them (see [`read_jar`]).+ cookies: Cookies,+}++/// What became of the cookies kept on disk when the client started.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Cookies {+ /// Read, or there were none.+ Read,+ /// Sealed, and the keyring would not answer for their key — locked, or not up yet. The file+ /// is left as it is and read again once the keyring answers.+ Unread,+ /// Sealed, and could not be opened: the keyring no longer holds their key (it was reset),+ /// or the file was changed. Set aside; the session carries on from its tokens.+ SetAside,+}++/// The cookie jar kept on disk, opened, and what became of the file.+///+/// A sealed file is opened with its key from the keyring. One that cannot be — no key, a key+/// that does not fit, a version this build does not know, a changed byte — is deleted, never+/// a reason to fail: the cookies only save a round trip, and the tokens the keyring holds open+/// a new set (see [`Client::resume`]).+///+/// A jar from before sealing (plain JSON) is read once and sealed in its place, or, with no+/// keyring to keep a key, deleted — its cookies held in memory for as long as Skykeep runs and+/// sealed by the first write a keyring takes. Either way no plaintext is left behind: the sealed+/// file is renamed over it, so the plain one is never there beside it.+fn read_jar(store: &Store) -> (cookie_store::CookieStore, Cookies) {+ let path = store.cookie_path();+ let parse = |json: &[u8]| cookie_store::serde::json::load(json).ok();+ let Ok(bytes) = std::fs::read(path) else {+ return (cookie_store::CookieStore::default(), Cookies::Read);+ };+ let set_aside = |why: &str| {+ quiet!("quince: the saved cookies were set aside: {why}");+ let _ = std::fs::remove_file(path);+ (cookie_store::CookieStore::default(), Cookies::SetAside)+ };+ if sealed::is_sealed(&bytes) {+ return match store.cookie_key() {+ Ok(Some(key)) => match sealed::open(&key, &bytes) {+ Ok(json) => match parse(&json) {+ Some(jar) => (jar, Cookies::Read),+ None => set_aside("they were not a cookie jar"),+ },+ Err(sealed::Unopened::Version(v)) => set_aside(&format!("unknown version {v}")),+ Err(sealed::Unopened::Damaged) => set_aside("they did not open with their key"),+ },+ Ok(None) => set_aside("the keyring no longer holds their key"),+ Err(e) => {+ quiet!("quince: the saved cookies wait for the keyring: {e}");+ (cookie_store::CookieStore::default(), Cookies::Unread)+ }+ };+ }+ // From before sealing: read once, then sealed in place or gone.+ let Some(jar) = parse(&bytes) else {+ let _ = std::fs::remove_file(path);+ return (cookie_store::CookieStore::default(), Cookies::Read);+ };+ let sealed_in_place = (|| -> Result<()> {+ let key = store.cookie_key_or_new()?;+ let mut json = Vec::new();+ cookie_store::serde::json::save(&jar, &mut json)+ .map_err(|e| Error::Protocol(format!("couldn't save cookies: {e}")))?;+ Ok(session::write_whole(+ path,+ &sealed::seal(&key, &json)?,+ true,+ )?)+ })();+ if let Err(e) = sealed_in_place {+ quiet!("quince: the cookies are kept in memory only: {e}");+ let _ = std::fs::remove_file(path);+ }+ (jar, Cookies::Read)}/// Hashes of the session and the cookie jar as last written; `None` for not written yet.@@ -294,17 +372,8 @@ impl Client {Err(e) => (session::Session::default(), Some(e.to_string())),};- let jar = {- let path = store.cookie_path();- let inner = if path.exists() {- let reader = std::io::BufReader::new(std::fs::File::open(path)?);- cookie_store::serde::json::load(reader)- .unwrap_or_else(|_| cookie_store::CookieStore::default())- } else {- cookie_store::CookieStore::default()- };- Arc::new(CookieStoreMutex::new(inner))- };+ let (jar, cookies) = read_jar(&store);+ let jar = Arc::new(CookieStoreMutex::new(jar));// Default origin is icloud.com — what setup.icloud.com and the service endpoints// expect. The idmsa SRP endpoints want their own origin and override it per request.@@ -347,9 +416,41 @@ impl Client {keyring_error,unsaved: None,persisted: std::sync::Mutex::new(Persisted::default()),+ cookies,})}+ /// Said when the cookies kept on disk could not be opened and were set aside — the keyring+ /// was reset, or the file changed. Nothing else is lost: Skykeep carries on from the+ /// session the keyring holds, and asks for a sign-in only if that is gone too.+ #[must_use]+ pub fn cookies_set_aside(&self) -> Option<&'static str> {+ (self.cookies == Cookies::SetAside).then_some(+ "Skykeep couldn't open its saved connection to iCloud, so it set it aside. \+ If you're asked to sign in again, that's all it takes — your library is untouched.",+ )+ }++ /// Cookies left unread at the start because the keyring would not answer, read now that it+ /// may — into a jar nothing has filled since, never over cookies newer than the file.+ fn read_cookies_again(&mut self) {+ if self.cookies != Cookies::Unread {+ return;+ }+ let (jar, cookies) = read_jar(&self.store);+ if cookies == Cookies::Unread {+ return;+ }+ self.cookies = cookies;+ let mut held = self+ .jar+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if held.iter_any().next().is_none() {+ *held = jar;+ }+ }+/// A lapsed session tried to sign itself back in, and Apple wants a code before it will/// trust this computer again. The code screen is the next thing to show.#[must_use]@@ -426,6 +527,8 @@ impl Client {/// would not answer at the start is not asked to replace it either.fn keep(&mut self) {self.keyring_error = None;+ // Never an empty jar written over cookies the keyring could not open at the start.+ self.read_cookies_again();match self.persist() {Ok(()) => self.unsaved = None,Err(e) => {@@ -442,13 +545,17 @@ impl Client {self.unsaved.as_deref()}- /// The cookie jar, as `cookie_store` wrote it, to its file.+ /// The cookie jar, as `cookie_store` wrote it, sealed to its file (see [`sealed`]).+ ///+ /// With no keyring to keep the key nothing is written: the cookies stay in memory, as the+ /// session does, and are sealed by the first write a keyring takes. Never in the clear.fn write_cookies(&self, cookies: &[u8]) -> Result<()> {- // The session's cookies are a credential: readable by this user alone, whatever folder- // they end up in (a backup, a copy), not only by the private data folder around them.+ let key = self.store.cookie_key_or_new()?;+ // The session's cookies are a credential: readable by this user alone as well, whatever+ // folder they end up in (a backup, a copy), not only by the private data folder.Ok(session::write_whole(self.store.cookie_path(),- cookies,+ &sealed::seal(&key, cookies)?,true,)?)}@@ -527,6 +634,7 @@ impl Client {Err(e) => return Err(e),}}+ self.read_cookies_again();if !self.session.is_resumable() {return Ok(false);}@@ -1590,3 +1698,228 @@ mod tests {}}}++/// The cookie jar on disk: sealed with a key the keyring keeps, and never in the clear.+#[cfg(test)]+mod sealed_jar_tests {+ use super::*;++ const VALUE: &str = "cookie-value-that-must-not-show";++ fn client(dir: &Path) -> Client {+ Client::with(dir, Endpoints::default(), Store::file(dir).unwrap()).unwrap()+ }++ fn holding_a_cookie(dir: &Path) -> Client {+ let c = client(dir);+ let url = reqwest::Url::parse("https://www.icloud.com/").unwrap();+ let cookie = cookie_store::RawCookie::parse(format!(+ "X-APPLE-WEBAUTH-USER={VALUE}; Domain=icloud.com; Path=/; Max-Age=3600; Secure"+ ))+ .unwrap();+ c.jar.lock().unwrap().insert_raw(&cookie, &url).unwrap();+ c+ }++ fn has_the_cookie(c: &Client) -> bool {+ c.jar.lock().unwrap().iter_any().any(|k| k.value() == VALUE)+ }++ fn cookies_file(dir: &Path) -> std::path::PathBuf {+ dir.join("cookies.json")+ }++ /// The jar as it was written before sealing: plain JSON.+ fn plain_jar(dir: &Path) -> Vec<u8> {+ let c = holding_a_cookie(dir);+ let mut json = Vec::new();+ cookie_store::serde::json::save(&c.jar.lock().unwrap(), &mut json).unwrap();+ assert!(String::from_utf8_lossy(&json).contains(VALUE));+ json+ }++ /// No keyring to keep a key: where the key would be is a folder, so nothing can be kept.+ fn no_keyring(dir: &Path) {+ std::fs::create_dir(dir.join("cookie-key")).unwrap();+ }++ fn nothing_but(dir: &Path, names: &[&str]) {+ let mut found: Vec<String> = std::fs::read_dir(dir)+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ found.sort();+ let mut want: Vec<String> = names.iter().map(|n| (*n).to_string()).collect();+ want.sort();+ assert_eq!(found, want);+ }++ #[test]+ fn cookies_are_sealed_on_disk_and_read_back_by_the_next_start() {+ let dir = tempfile::tempdir().unwrap();+ holding_a_cookie(dir.path()).persist().unwrap();++ let on_disk = std::fs::read(cookies_file(dir.path())).unwrap();+ assert!(+ on_disk.starts_with(sealed::MAGIC),+ "sealed, with its header"+ );+ assert!(+ !String::from_utf8_lossy(&on_disk).contains(VALUE),+ "the cookie is not in the file"+ );+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(cookies_file(dir.path()))+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o777, 0o600);+ }++ let next = client(dir.path());+ assert!(has_the_cookie(&next));+ assert!(next.cookies_set_aside().is_none());+ }++ /// A changed byte: set aside cleanly, the file gone, said calmly — never a crash.+ #[test]+ fn a_changed_file_is_set_aside() {+ let dir = tempfile::tempdir().unwrap();+ holding_a_cookie(dir.path()).persist().unwrap();+ let path = cookies_file(dir.path());+ let mut bytes = std::fs::read(&path).unwrap();+ let last = bytes.len() - 1;+ bytes[last] ^= 0x40;+ std::fs::write(&path, bytes).unwrap();++ let next = client(dir.path());+ assert!(!has_the_cookie(&next));+ assert!(!path.exists(), "nothing left that cannot be opened");+ assert!(next.cookies_set_aside().is_some(), "and it says so");+ // The next write seals afresh, and that opens.+ holding_a_cookie(dir.path()).persist().unwrap();+ assert!(has_the_cookie(&client(dir.path())));+ }++ #[test]+ fn a_version_this_build_does_not_know_is_set_aside() {+ let dir = tempfile::tempdir().unwrap();+ holding_a_cookie(dir.path()).persist().unwrap();+ let path = cookies_file(dir.path());+ let mut bytes = std::fs::read(&path).unwrap();+ bytes[sealed::MAGIC.len()] = sealed::VERSION + 1;+ std::fs::write(&path, bytes).unwrap();++ let next = client(dir.path());+ assert!(!has_the_cookie(&next));+ assert!(!path.exists());+ assert!(next.cookies_set_aside().is_some());+ }++ /// The keyring was reset: the file is there and its key is not.+ #[test]+ fn a_file_whose_key_is_gone_is_set_aside() {+ let dir = tempfile::tempdir().unwrap();+ holding_a_cookie(dir.path()).persist().unwrap();+ std::fs::remove_file(dir.path().join("cookie-key")).unwrap();++ let next = client(dir.path());+ assert!(!has_the_cookie(&next));+ assert!(!cookies_file(dir.path()).exists());+ assert!(next.cookies_set_aside().is_some());+ }++ /// A jar from before sealing is read once and sealed in its place; the plain one is gone,+ /// with nothing beside it.+ #[test]+ fn a_plain_jar_from_before_is_sealed_in_its_place() {+ let dir = tempfile::tempdir().unwrap();+ let json = plain_jar(dir.path());+ std::fs::write(cookies_file(dir.path()), &json).unwrap();++ let c = client(dir.path());+ assert!(has_the_cookie(&c), "nothing lost on the way");+ let on_disk = std::fs::read(cookies_file(dir.path())).unwrap();+ assert!(on_disk.starts_with(sealed::MAGIC));+ assert!(!String::from_utf8_lossy(&on_disk).contains(VALUE));+ nothing_but(dir.path(), &["cookies.json", "cookie-key"]);+ assert!(+ has_the_cookie(&client(dir.path())),+ "and it opens next time"+ );+ }++ /// No keyring, and a plain jar from before: read into memory, and the plain file deleted —+ /// it is not left there, and nothing is written in its place.+ #[test]+ fn a_plain_jar_with_no_keyring_is_kept_in_memory_and_deleted() {+ let dir = tempfile::tempdir().unwrap();+ let json = plain_jar(dir.path());+ no_keyring(dir.path());+ std::fs::write(cookies_file(dir.path()), &json).unwrap();++ let c = client(dir.path());+ assert!(has_the_cookie(&c), "held for as long as Skykeep runs");+ assert!(+ !cookies_file(dir.path()).exists(),+ "no plaintext left behind"+ );+ nothing_but(dir.path(), &["cookie-key"]);+ }++ /// No keyring: the cookies are not written at all — never in the clear — and saying so is+ /// what `keep` does with the error.+ #[test]+ fn with_no_keyring_nothing_is_written() {+ let dir = tempfile::tempdir().unwrap();+ no_keyring(dir.path());+ let mut c = holding_a_cookie(dir.path());+ assert!(matches!(c.persist(), Err(Error::Keyring(_))));+ assert!(!cookies_file(dir.path()).exists());+ nothing_but(dir.path(), &["cookie-key", "session.json"]);+ c.keep();+ assert!(c.unsaved().is_some(), "said: kept in memory only");+ assert!(has_the_cookie(&c));++ // A keyring comes up: the next write seals them.+ std::fs::remove_dir(dir.path().join("cookie-key")).unwrap();+ c.keep();+ assert!(c.unsaved().is_none());+ assert!(has_the_cookie(&client(dir.path())));+ }++ /// A keyring that will not answer yet is not a reset one: the sealed file is left as it is,+ /// and read once it answers.+ #[test]+ fn a_keyring_that_does_not_answer_leaves_the_file_for_later() {+ let dir = tempfile::tempdir().unwrap();+ holding_a_cookie(dir.path()).persist().unwrap();+ let key = dir.path().join("cookie-key");+ let kept = std::fs::read(&key).unwrap();+ std::fs::remove_file(&key).unwrap();+ no_keyring(dir.path());++ let mut c = client(dir.path());+ assert!(!has_the_cookie(&c));+ assert!(cookies_file(dir.path()).exists(), "untouched");+ assert!(c.cookies_set_aside().is_none());++ std::fs::remove_dir(&key).unwrap();+ std::fs::write(&key, kept).unwrap();+ c.read_cookies_again();+ assert!(has_the_cookie(&c));+ }++ /// Signing out takes the key with the cookies.+ #[test]+ fn signing_out_forgets_the_key_too() {+ let dir = tempfile::tempdir().unwrap();+ let mut c = holding_a_cookie(dir.path());+ c.persist().unwrap();+ c.sign_out().unwrap();+ assert!(!cookies_file(dir.path()).exists());+ assert!(!dir.path().join("cookie-key").exists());+ }+}diff --git a/crates/quince-auth/src/sealed.rs b/crates/quince-auth/src/sealed.rsnew file mode 100644index 0000000..8cba762--- /dev/null+++ b/crates/quince-auth/src/sealed.rs@@ -0,0 +1,189 @@+//! The session's cookies, sealed on disk with a key the system keyring keeps.+//!+//! The cookies are as good as the session for as long as they last: anything that could read+//! `cookies.json` could be signed in to the person's iCloud with it. The file was readable by+//! this user alone, which kept other users out and nothing else — a backup, a synced folder, a+//! copy of the data folder carried them in the clear. Now the file holds them sealed with+//! AES-256-GCM, under a key made for this data folder and kept in the keyring beside the+//! session, so the file on its own opens nothing.+//!+//! The file is a header and the sealed jar:+//!+//! ```text+//! "SKCK" version (1) nonce (12 bytes, fresh every write) ciphertext and tag+//! ```+//!+//! The header is bound in as associated data, so a changed version byte fails to open just as+//! a changed byte of the cookies does.++use aes_gcm::aead::{Aead, KeyInit, Payload};+use aes_gcm::{Aes256Gcm, Nonce};+use base64::{engine::general_purpose::STANDARD as B64, Engine};++/// What every sealed file starts with. A jar from before sealing is JSON, which never does.+pub(crate) const MAGIC: &[u8; 4] = b"SKCK";+/// The one layout there is. A file of any other version is not guessed at.+pub(crate) const VERSION: u8 = 1;+const HEADER: usize = MAGIC.len() + 1;+const NONCE: usize = 12;+/// The smallest a sealed file can be: header, nonce and a tag over nothing.+const SMALLEST: usize = HEADER + NONCE + 16;++/// 256 random bits, one per data folder.+pub(crate) type Key = [u8; 32];++/// Why a sealed file did not open. Either way the cookies in it are lost to us: set aside, and+/// the session carries on from the tokens the keyring holds.+#[derive(Debug, PartialEq, Eq)]+pub(crate) enum Unopened {+ /// Written by a layout this build does not know.+ Version(u8),+ /// Cut short, changed, or sealed with another key.+ Damaged,+}++/// Whether `bytes` are a sealed jar, rather than one from before sealing.+pub(crate) fn is_sealed(bytes: &[u8]) -> bool {+ bytes.starts_with(MAGIC)+}++/// A new key, from the operating system's own randomness.+pub(crate) fn new_key() -> std::io::Result<Key> {+ let mut key = [0u8; 32];+ fill(&mut key)?;+ Ok(key)+}++fn fill(bytes: &mut [u8]) -> std::io::Result<()> {+ use rand::TryRngCore;+ rand::rngs::OsRng+ .try_fill_bytes(bytes)+ .map_err(std::io::Error::other)+}++/// The key as the keyring keeps it: text, 44 characters, well inside any platform's limit.+pub(crate) fn encode_key(key: &Key) -> String {+ B64.encode(key)+}++/// A key read back from the keyring; anything that is not exactly one is no key.+pub(crate) fn decode_key(text: &str) -> Option<Key> {+ B64.decode(text.trim()).ok()?.try_into().ok()+}++/// `plain` sealed under `key`, header first, with a nonce of its own.+pub(crate) fn seal(key: &Key, plain: &[u8]) -> std::io::Result<Vec<u8>> {+ let mut nonce = [0u8; NONCE];+ fill(&mut nonce)?;+ let mut out = Vec::with_capacity(SMALLEST + plain.len());+ out.extend_from_slice(MAGIC);+ out.push(VERSION);+ let sealed = Aes256Gcm::new(key.into())+ .encrypt(+ Nonce::from_slice(&nonce),+ Payload {+ msg: plain,+ aad: &out[..HEADER],+ },+ )+ .map_err(|_| std::io::Error::other("couldn't seal the cookies"))?;+ out.extend_from_slice(&nonce);+ out.extend_from_slice(&sealed);+ Ok(out)+}++/// What [`seal`] wrote, opened — only if every byte of it is as it was written.+pub(crate) fn open(key: &Key, bytes: &[u8]) -> Result<Vec<u8>, Unopened> {+ if !is_sealed(bytes) || bytes.len() < HEADER {+ return Err(Unopened::Damaged);+ }+ if bytes[MAGIC.len()] != VERSION {+ return Err(Unopened::Version(bytes[MAGIC.len()]));+ }+ if bytes.len() < SMALLEST {+ return Err(Unopened::Damaged);+ }+ let (header, rest) = bytes.split_at(HEADER);+ let (nonce, sealed) = rest.split_at(NONCE);+ Aes256Gcm::new(key.into())+ .decrypt(+ Nonce::from_slice(nonce),+ Payload {+ msg: sealed,+ aad: header,+ },+ )+ .map_err(|_| Unopened::Damaged)+}++#[cfg(test)]+mod tests {+ use super::*;++ const JAR: &[u8] = br#"[{"raw_cookie":"X-APPLE-WEBAUTH-USER=secret-value"}]"#;++ #[test]+ fn what_is_sealed_opens_with_its_key_and_says_nothing_in_the_clear() {+ let key = new_key().unwrap();+ let sealed = seal(&key, JAR).unwrap();+ assert!(is_sealed(&sealed));+ assert_eq!(sealed[4], VERSION);+ assert!(+ !sealed.windows(12).any(|w| w == b"secret-value"),+ "the cookie is not in the file"+ );+ assert_eq!(open(&key, &sealed).unwrap(), JAR);+ // A fresh nonce every write: the same jar never seals to the same bytes.+ assert_ne!(seal(&key, JAR).unwrap(), sealed);+ }++ /// Any byte changed — header, nonce, cookies or tag — and nothing opens.+ #[test]+ fn a_changed_byte_anywhere_is_caught() {+ let key = new_key().unwrap();+ let sealed = seal(&key, JAR).unwrap();+ for i in MAGIC.len() + 1..sealed.len() {+ let mut bent = sealed.clone();+ bent[i] ^= 0x01;+ assert_eq!(open(&key, &bent), Err(Unopened::Damaged), "byte {i}");+ }+ assert_eq!(+ open(&key, &sealed[..sealed.len() - 1]),+ Err(Unopened::Damaged)+ );+ assert_eq!(open(&key, &sealed[..HEADER]), Err(Unopened::Damaged));+ assert_eq!(+ open(&new_key().unwrap(), &sealed),+ Err(Unopened::Damaged),+ "another folder's key"+ );+ }++ #[test]+ fn a_version_this_build_does_not_know_is_not_guessed_at() {+ let key = new_key().unwrap();+ let mut sealed = seal(&key, JAR).unwrap();+ sealed[4] = 2;+ assert_eq!(open(&key, &sealed), Err(Unopened::Version(2)));+ sealed[4] = 0;+ assert_eq!(open(&key, &sealed), Err(Unopened::Version(0)));+ }++ #[test]+ fn a_jar_from_before_sealing_is_told_apart() {+ assert!(!is_sealed(JAR));+ assert!(!is_sealed(b""));+ assert!(!is_sealed(b"[\n {}\n]"));+ }++ #[test]+ fn a_key_survives_the_keyring_as_text_and_nothing_else_reads_as_one() {+ let key = new_key().unwrap();+ let text = encode_key(&key);+ assert_eq!(text.len(), 44);+ assert_eq!(decode_key(&text), Some(key));+ assert_eq!(decode_key("not a key"), None);+ assert_eq!(decode_key(&B64.encode([7u8; 16])), None, "too short");+ assert_ne!(new_key().unwrap(), key);+ }+}diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex 6301a03..7d4c473 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -5,10 +5,13 @@//! trust token from `/2sv/trust`. We capture it and hand it to the OS keyring, so a restart//! resumes instead of re-prompting.+use crate::sealed::{self, Key};use serde::{Deserialize, Serialize};use std::path::{Path, PathBuf};const KEYRING_ENTRY: &str = "session";+/// The cookie key's entry: the session's name with this after it (`session:cookie-key`).+const COOKIE_KEY: &str = ":cookie-key";/// Identifiers the app was published under before, newest first: the keyring services its/// session may still be under, and the folders `src-tauri/src/migrate.rs` moves. The current@@ -494,6 +497,52 @@ fn read_moving(Ok(Some(old))}+/// The key `cookies.json` is sealed with, under `name` in `k`; made and kept there first when+/// `make` and there is none.+///+/// One small entry: 44 characters, inside even Windows' limit, so it is never split into parts.+/// A new key is read back before it is used, as the trust token is — a keyring that said yes+/// and kept nothing would otherwise leave a file sealed under a key that is gone. An entry that+/// is not a key is no key: replaced when one is being made, and otherwise nothing to open with.+fn cookie_key_in(k: &dyn Secrets, name: &str, make: bool) -> Result<Option<Key>, String> {+ if let Some(key) = k.get(name)?.as_deref().and_then(sealed::decode_key) {+ return Ok(Some(key));+ }+ if !make {+ return Ok(None);+ }+ let key = sealed::new_key().map_err(|e| e.to_string())?;+ let text = sealed::encode_key(&key);+ k.set(name, &text)?;+ if k.get(name)?.as_deref() != Some(text.as_str()) {+ return Err("the system keyring accepted the cookie key but did not keep it".into());+ }+ Ok(Some(key))+}++/// Tests only: the cookie key in a file of its own beside `session.json`, as the session is.+struct KeyFile(PathBuf);++impl Secrets for KeyFile {+ fn get(&self, _: &str) -> Result<Option<String>, String> {+ match std::fs::read_to_string(&self.0) {+ Ok(text) => Ok(Some(text)),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(e) => Err(e.to_string()),+ }+ }+ fn set(&self, _: &str, value: &str) -> Result<(), String> {+ write_whole(&self.0, value.as_bytes(), true).map_err(|e| e.to_string())+ }+ fn delete(&self, _: &str) -> Result<(), String> {+ match std::fs::remove_file(&self.0) {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(e.to_string()),+ }+ }+}+/// Write `bytes` to `path` whole or not at all: to a file beside it, made sure of on disk, then/// renamed over it. Truncated in place, a crash or a full disk part way left an empty or cut-off/// cookie jar, read as no cookies at all: the session checked again from the start, and maybe@@ -590,6 +639,42 @@ impl Store {}}+ /// The cookie key's entry, beside the session's: one per data folder, as the session is.+ fn key_name(&self) -> String {+ format!("{}{COOKIE_KEY}", self.name())+ }++ /// Where the cookie key is kept, asked of `f`.+ fn with_key_store<T>(+ &self,+ f: impl FnOnce(&dyn Secrets, &str) -> Result<T, String>,+ ) -> Result<T, crate::Error> {+ let name = self.key_name();+ match &self.backend {+ Backend::Keyring(_) => {+ let now = current().map_err(crate::Error::Keyring)?;+ f(&now, &name)+ }+ Backend::File(path) => f(&KeyFile(path.with_file_name("cookie-key")), &name),+ }+ .map_err(crate::Error::Keyring)+ }++ /// The key the cookies on disk are sealed with. `Ok(None)`: none is kept — never made, or+ /// the keyring was reset — so a sealed file here can no longer be opened. An error: the+ /// keyring would not answer, which says nothing about whether one is kept.+ pub(crate) fn cookie_key(&self) -> Result<Option<Key>, crate::Error> {+ self.with_key_store(|k, name| cookie_key_in(k, name, false))+ }++ /// [`Self::cookie_key`], made and kept the first time cookies are written. An error is a+ /// keyring that cannot keep one, and then the cookies are not written at all.+ pub(crate) fn cookie_key_or_new(&self) -> Result<Key, crate::Error> {+ self.with_key_store(|k, name| {+ cookie_key_in(k, name, true)?.ok_or_else(|| "no cookie key was made".to_string())+ })+ }+/// Load the stored session. A missing entry is normal (first run), not an error.pub fn load(&self) -> Session {self.try_load().unwrap_or_default()@@ -667,6 +752,8 @@ impl Store {}}}+ // The cookies' key goes with them: the next sign-in seals under a new one.+ self.with_key_store(|k, name| k.delete(name))?;if self.cookie_path.exists() {std::fs::remove_file(&self.cookie_path)?;}@@ -1262,3 +1349,94 @@ mod move_tests {let _ = std::fs::remove_dir_all(&dir);}}++/// The cookie key in the keyring: made once, read back before it is trusted, never in parts.+#[cfg(test)]+mod cookie_key_tests {+ use super::*;+ use std::cell::RefCell;+ use std::collections::BTreeMap;++ /// `forget`: says yes and keeps nothing. `refuse`: no keyring at all.+ #[derive(Default)]+ struct Mock {+ held: RefCell<BTreeMap<String, String>>,+ forget: bool,+ refuse: bool,+ }+ impl Secrets for Mock {+ fn get(&self, name: &str) -> Result<Option<String>, String> {+ if self.refuse {+ return Err("no keyring".into());+ }+ Ok(self.held.borrow().get(name).cloned())+ }+ fn set(&self, name: &str, value: &str) -> Result<(), String> {+ if self.refuse {+ return Err("no keyring".into());+ }+ if !self.forget {+ self.held.borrow_mut().insert(name.into(), value.into());+ }+ Ok(())+ }+ fn delete(&self, name: &str) -> Result<(), String> {+ self.held.borrow_mut().remove(name);+ Ok(())+ }+ }++ #[test]+ fn a_key_is_made_once_and_then_read() {+ let k = Mock::default();+ assert_eq!(+ cookie_key_in(&k, "session:cookie-key", false).unwrap(),+ None+ );+ let made = cookie_key_in(&k, "session:cookie-key", true).unwrap();+ assert!(made.is_some());+ assert_eq!(k.held.borrow().len(), 1, "one small entry");+ assert_eq!(+ k.held.borrow()["session:cookie-key"].chars().count(),+ 44,+ "inside Windows' limit: never in parts"+ );+ assert_eq!(cookie_key_in(&k, "session:cookie-key", true).unwrap(), made);+ assert_eq!(+ cookie_key_in(&k, "session:cookie-key", false).unwrap(),+ made+ );+ }++ #[test]+ fn a_keyring_that_keeps_nothing_gives_no_key() {+ let forgetting = Mock {+ forget: true,+ ..Mock::default()+ };+ assert!(cookie_key_in(&forgetting, "k", true).is_err());+ let none = Mock {+ refuse: true,+ ..Mock::default()+ };+ assert!(cookie_key_in(&none, "k", true).is_err());+ assert!(cookie_key_in(&none, "k", false).is_err(), "not \"no key\"");+ }++ #[test]+ fn an_entry_that_is_not_a_key_is_none_and_replaced() {+ let k = Mock::default();+ k.set("k", "rubbish").unwrap();+ assert_eq!(cookie_key_in(&k, "k", false).unwrap(), None);+ let made = cookie_key_in(&k, "k", true).unwrap().unwrap();+ assert_eq!(sealed::decode_key(&k.held.borrow()["k"]), Some(made));+ }++ #[test]+ fn each_data_folder_has_a_key_of_its_own() {+ let a = Store::keyring(Path::new("/tmp/quince-key-a")).unwrap();+ let b = Store::keyring(Path::new("/tmp/quince-key-b")).unwrap();+ assert_ne!(a.key_name(), b.key_name());+ assert!(a.key_name().ends_with(COOKIE_KEY));+ }+}