Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Sign-in: a locked or late keyring is asked again, not read as signed out

Yashwanth Kamireddi8413f0a15282
diff --git a/.uiverify/signin-keyring.mjs b/.uiverify/signin-keyring.mjs
new file mode 100644
index 0000000..d8ccfaf
--- /dev/null
+++ b/.uiverify/signin-keyring.mjs
@@ -0,0 +1,54 @@
+// A saved session the keyring would not give back (locked at login, or not started yet): the
+// sign-in screen says so and what to do, rather than a bare form that reads as signed out.
+// A session Apple simply ended says nothing extra.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+const BASE = process.env.BASE ?? process.env.URL ?? "http://localhost:4173";
+const KEYRING =
+ "Your system keyring is locked or not running. Unlock or start GNOME Keyring or KWallet, then try again.";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+async function open(resumeFails) {
+ const ctx = await b.newContext({ viewport: { width: 1040, height: 720 } });
+ await ctx.addInitScript(installStub, { screen: "signin", services: SERVICES, twoFactor: null });
+ await ctx.addInitScript(({ resumeFails, KEYRING }) => {
+ const inner = window.__TAURI_INTERNALS__.invoke;
+ window.__TAURI_INTERNALS__.invoke = async (cmd, args) => {
+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: false, libraryReady: false, notKept: false };
+ if (cmd === "auth_resume") {
+ if (resumeFails) throw KEYRING;
+ return "signin";
+ }
+ return inner(cmd, args);
+ };
+ }, { resumeFails, KEYRING });
+ const page = await ctx.newPage();
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await page.waitForSelector("input[type='password']");
+ await page.waitForTimeout(200);
+ return { ctx, page };
+}
+
+{
+ const { ctx, page } = await open(true);
+ const line = page.locator("#signin-error");
+ ok(await line.isVisible(), "the sign-in screen says why the saved session wasn't opened");
+ const said = (await line.innerText()).trim();
+ ok(said === KEYRING, `in one line that says what to do [${said}]`);
+ const focused = await page.evaluate(() => document.activeElement?.getAttribute("type"));
+ ok(focused !== "password", "the cursor is not put in the password before an address");
+ await page.locator("input[type='email'], input[autocomplete='username']").first().fill("a");
+ ok(!(await line.count()), "and it goes once the person starts typing");
+ await ctx.close();
+}
+{
+ const { ctx, page } = await open(false);
+ ok(!(await page.locator("#signin-error").count()), "a session Apple ended shows no error");
+ ok(await page.locator(".assurance").isVisible(), "just the usual assurance");
+ await ctx.close();
+}
+await b.close();
+console.log(failures ? `\n${failures} FAILED` : "\nall passed");
+process.exit(failures ? 1 : 0);
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index a96196e..3c3648c 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -118,7 +118,9 @@ pub enum Error {
repeated attempts risk a temporary lock"
)]
RateLimited,
- #[error("couldn't use the system keyring: {0}")]
+ /// Said as what to do: the keyring's own words (a D-Bus error name, a Win32 code) are for
+ /// the log, and stay in the value.
+ #[error("{}", KEYRING_WORDS)]
Keyring(String),
#[error(transparent)]
Io(#[from] std::io::Error),
@@ -128,6 +130,13 @@ pub enum Error {
type Result<T> = std::result::Result<T, Error>;
+/// What a keyring that would not answer means to the person in front of it.
+#[cfg(windows)]
+pub const KEYRING_WORDS: &str = "Windows Credential Manager didn’t answer. Try again in a moment.";
+#[cfg(not(windows))]
+pub const KEYRING_WORDS: &str =
+ "Your system keyring is locked or not running. Unlock or start GNOME Keyring or KWallet, then try again.";
+
/// A reply that says "not now" rather than "no": Apple's servers failing or overloaded.
fn transient(status: reqwest::StatusCode) -> Option<Error> {
(status.is_server_error() || status.as_u16() == 429)
@@ -463,8 +472,14 @@ impl Client {
}
/// True when a stored session exists and is worth trying.
+ ///
+ /// A keyring that would not answer at the start (locked, or not up yet at login) may well
+ /// hold one: sealed cookies on disk say a keyring kept a session here before. Then it is
+ /// worth a resume, which asks the keyring again — and where it is locked, that is what
+ /// brings up its unlock prompt — rather than a sign-in screen that would replace it.
pub fn has_stored_session(&self) -> bool {
self.session.is_resumable()
+ || (self.keyring_error.is_some() && self.store.cookie_path().exists())
}
// ---- persistence ----------------------------------------------------------------
@@ -532,7 +547,7 @@ impl Client {
match self.persist() {
Ok(()) => self.unsaved = None,
Err(e) => {
- quiet!("quince: the session is kept in memory only: {e}");
+ quiet!("quince: the session is kept in memory only: {e:?}");
self.unsaved = Some(e.to_string());
}
}
@@ -631,7 +646,10 @@ impl Client {
self.session = session;
self.keyring_error = None;
}
- Err(e) => return Err(e),
+ Err(e) => {
+ quiet!("quince: keyring: still not answering: {e:?}");
+ return Err(e);
+ }
}
}
self.read_cookies_again();
@@ -1912,6 +1930,39 @@ mod sealed_jar_tests {
assert!(has_the_cookie(&c));
}
+ /// A keyring locked at login, or not up yet when Skykeep starts with the desktop: the
+ /// session it holds is still there. Read as nothing stored, the launch went to the sign-in
+ /// screen — never asking the keyring again, so its unlock prompt never came — and signing
+ /// in replaced the session and its trust token, with a code to type.
+ #[tokio::test]
+ async fn a_keyring_that_does_not_answer_is_asked_again_not_read_as_signed_out() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut c = holding_a_cookie(dir.path());
+ c.session.session_token = Some("token".into());
+ c.persist().unwrap();
+ assert!(cookies_file(dir.path()).exists());
+ // Where the session is kept will not answer.
+ let session = dir.path().join("session.json");
+ std::fs::remove_file(&session).unwrap();
+ std::fs::create_dir(&session).unwrap();
+
+ let mut c = client(dir.path());
+ assert!(c.has_stored_session(), "worth a resume, which asks again");
+ let said = c.resume().await.unwrap_err();
+ assert!(matches!(said, Error::Keyring(_)), "got {said:?}");
+ let words = said.to_string();
+ assert!(words.contains("keyring") || words.contains("Credential Manager"));
+ assert!(
+ !words.contains("Is a directory"),
+ "no raw OS words: {words}"
+ );
+
+ // A first run with no keyring kept nothing: the sign-in screen is right then.
+ let fresh = tempfile::tempdir().unwrap();
+ std::fs::create_dir(fresh.path().join("session.json")).unwrap();
+ assert!(!client(fresh.path()).has_stored_session());
+ }
+
/// Signing out takes the key with the cookies.
#[test]
fn signing_out_forgets_the_key_too() {
diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rs
index 7d4c473..193ac73 100644
--- a/crates/quince-auth/src/session.rs
+++ b/crates/quince-auth/src/session.rs
@@ -694,9 +694,12 @@ impl Store {
Ok(None) => return Ok(Session::default()),
Err(e) => return Err(crate::Error::Keyring(e)),
},
+ // Absent is nothing stored; anything else stands in, in tests, for a keyring that
+ // would not answer.
Backend::File(path) => match std::fs::read_to_string(path) {
Ok(j) => j,
- Err(_) => return Ok(Session::default()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Session::default()),
+ Err(e) => return Err(crate::Error::Keyring(e.to_string())),
},
};
Ok(serde_json::from_str(&json).unwrap_or_default())
diff --git a/src/App.tsx b/src/App.tsx
index bd8dd68..cacddd3 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -7,12 +7,14 @@ import { StatusLine } from "./components/StatusLine";
import { dismissToast, toast } from "./components/Toast";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
-import { api, NEEDS_CODE, NEEDS_SIGNIN } from "./lib/ipc";
+import { api, messageOf, NEEDS_CODE, NEEDS_SIGNIN } from "./lib/ipc";
type Phase = "checking" | "signin" | "code" | "library";
export default function App() {
const [phase, setPhase] = useState<Phase>("checking");
+ // Why the stored session could not be taken up, said once on the sign-in screen.
+ const [why, setWhy] = useState<string | null>(null);
// The window is shown once the first real screen (the library, or sign-in) is in the page:
// never the session check before it (see window_ready, main.rs). Said as soon as React has
// put it there, not after an animation frame: the window is hidden until then, and a hidden
@@ -63,7 +65,12 @@ export default function App() {
return;
}
if (status.hasStoredSession) {
- const next = await api.resume();
+ // A resume that could not be made says why on the sign-in screen — a keyring that
+ // is locked, most often — rather than a bare form that reads as signed out.
+ const next = await api.resume().catch((err) => {
+ if (!cancelled) setWhy(messageOf(err));
+ return "signin" as const;
+ });
if (next !== "signin") return !cancelled && setPhase(next);
}
} catch {
@@ -134,6 +141,7 @@ export default function App() {
{phase === "signin" && (
<SignIn
onCancel={lapsed ? () => setPhase("library") : undefined}
+ notice={why}
onResult={(r) => {
setLapsed(false);
setPhase(r === "complete" ? "library" : "code");
diff --git a/src/screens/SignIn.tsx b/src/screens/SignIn.tsx
index 400dfba..29816e8 100644
--- a/src/screens/SignIn.tsx
+++ b/src/screens/SignIn.tsx
@@ -22,15 +22,18 @@ export function sentence(message: string) {
export function SignIn({
onResult,
onCancel,
+ notice,
}: {
onResult: (r: SignInResult) => void;
/** Back to the library: offered when signing in again after Apple signed the session out. */
onCancel?: () => void;
+ /** Why the saved session could not be taken up, said in the error's place until a try. */
+ notice?: string | null;
}) {
const [appleId, setAppleId] = useState("");
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(notice ? sentence(notice) : null);
const passwordRef = useRef<HTMLInputElement>(null);
// A wait Apple's limits ask for, counted down where it is said, and the button held until
// it is over — not a number frozen at the moment it was said.
@@ -46,8 +49,8 @@ export function SignIn({
// Back to the password once a try has come back, so the next one is a type and an Enter.
// After the fields are enabled again: a disabled field cannot take focus.
useEffect(() => {
- if (!busy && error) passwordRef.current?.focus();
- }, [busy, error]);
+ if (!busy && error && appleId) passwordRef.current?.focus();
+ }, [busy, error, appleId]);
async function submit(e: React.FormEvent) {
e.preventDefault();