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
Cover the sign-in conversation with tests, and name Apple's 450
Yashwanth Kamireddicadab05a2ee1
diff --git a/Cargo.lock b/Cargo.lockindex e691b2c..88d4510 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -47,6 +47,16 @@ version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+[[package]]+name = "assert-json-diff"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "async-compression"version = "0.4.46"@@ -606,6 +616,24 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "deadpool"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b"+dependencies = [+ "deadpool-runtime",+ "lazy_static",+ "num_cpus",+ "tokio",+]++[[package]]+name = "deadpool-runtime"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"+[[package]]name = "defmt"version = "1.1.1"@@ -857,6 +885,16 @@ dependencies = ["typeid",]+[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "fastrand"version = "2.5.0"@@ -947,6 +985,21 @@ dependencies = ["percent-encoding",]+[[package]]+name = "futures"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]+[[package]]name = "futures-channel"version = "0.3.34"@@ -954,6 +1007,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"dependencies = ["futures-core",+ "futures-sink",][[package]]@@ -1008,6 +1062,7 @@ version = "0.3.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"dependencies = [+ "futures-channel","futures-core","futures-io","futures-macro",@@ -1314,6 +1369,25 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "h2"+version = "0.4.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap 2.14.2",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]+[[package]]name = "hashbrown"version = "0.12.3"@@ -1338,6 +1412,12 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"+[[package]]name = "hex"version = "0.4.3"@@ -1402,6 +1482,12 @@ version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]name = "hyper"version = "1.11.1"@@ -1412,9 +1498,11 @@ dependencies = ["bytes","futures-channel","futures-core",+ "h2","http","http-body","httparse",+ "httpdate","itoa","pin-project-lite","smallvec",@@ -1825,6 +1913,12 @@ dependencies = ["zeroize",]+[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"+[[package]]name = "libappindicator"version = "0.9.0"@@ -1893,6 +1987,12 @@ dependencies = ["libc",]+[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"+[[package]]name = "litemap"version = "0.8.3"@@ -2074,6 +2174,16 @@ dependencies = ["autocfg",]+[[package]]+name = "num_cpus"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"+dependencies = [+ "hermit-abi",+ "libc",+]+[[package]]name = "num_enum"version = "0.7.6"@@ -2632,9 +2742,11 @@ dependencies = ["serde","serde_json","sha2",+ "tempfile","thiserror 2.0.20","tokio","uuid",+ "wiremock",][[package]]@@ -2991,6 +3103,19 @@ dependencies = ["semver",]+[[package]]+name = "rustix"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]+[[package]]name = "rustls"version = "0.23.44"@@ -3791,6 +3916,19 @@ dependencies = ["toml 1.1.6+spec-1.1.0",]+[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "tendril"version = "0.5.1"@@ -3940,6 +4078,7 @@ dependencies = ["bytes","futures-core","futures-sink",+ "libc","pin-project-lite","tokio",]@@ -4924,6 +5063,29 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "wiremock"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031"+dependencies = [+ "assert-json-diff",+ "base64 0.22.1",+ "deadpool",+ "futures",+ "http",+ "http-body-util",+ "hyper",+ "hyper-util",+ "log",+ "once_cell",+ "regex",+ "serde",+ "serde_json",+ "tokio",+ "url",+]+[[package]]name = "wit-bindgen"version = "0.57.1"diff --git a/crates/quince-auth/Cargo.toml b/crates/quince-auth/Cargo.tomlindex 099576b..8c7937f 100644--- a/crates/quince-auth/Cargo.toml+++ b/crates/quince-auth/Cargo.toml@@ -24,3 +24,5 @@ thiserror = "2"[dev-dependencies]tokio = { workspace = true }+wiremock = "0.6"+tempfile = "3"diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 16463f9..9e9992c 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -18,7 +18,8 @@ use reqwest::header::{HeaderMap, HeaderName, HeaderValue};use reqwest::{Client as HttpClient, Response, StatusCode};use reqwest_cookie_store::CookieStoreMutex;use serde_json::{json, Value};-use session::{Session, Store, CAPTURED_HEADERS};+pub use session::Store;+use session::{Session, CAPTURED_HEADERS};use std::path::Path;use std::sync::Arc;@@ -91,6 +92,8 @@ pub enum Error {Network(#[from] reqwest::Error),#[error("Apple sent back something unexpected: {0}")]Protocol(String),+ #[error("this needs a fresh sign-in — Apple won't accept a resumed session for it")]+ ReauthRequired,#[error("Apple is rate-limiting this account. Wait a few minutes before trying again — \repeated attempts risk a temporary lock")]RateLimited,@@ -110,6 +113,10 @@ fn apple_error(context: &str, status: StatusCode, body: &str) -> Error {if status == StatusCode::TOO_MANY_REQUESTS || status == StatusCode::SERVICE_UNAVAILABLE {return Error::RateLimited;}+ // 450 is Apple's "re-authenticate for this service": a resumed session is not enough.+ if status.as_u16() == 450 {+ return Error::ReauthRequired;+ }let parsed: Option<Value> = serde_json::from_str(body).ok();if let Some(v) = &parsed {if let Some(errs) = v["serviceErrors"].as_array().filter(|a| !a.is_empty()) {@@ -427,7 +434,7 @@ impl Client {return Err(Error::BadCredentials);}if !status.is_success() {- return Err(Error::Protocol(format!("sign-in start failed ({status})")));+ return Err(apple_error("starting sign-in", status, &text));}let init: Value = serde_json::from_str(&text)?;@@ -495,7 +502,7 @@ impl Client {StatusCode::PRECONDITION_FAILED => {Err(Error::UnsupportedAccount("two-factor auth isn't switched on".into()))}- s => Err(Error::Protocol(format!("sign-in finish failed ({s})"))),+ s => Err(apple_error("finishing sign-in", s, &text)),}}@@ -772,6 +779,12 @@ mod tests {Error::RateLimited));+ // Find My answers 450 on a resumed session; that is "sign in again", not a failure.+ assert!(matches!(+ apple_error("x", StatusCode::from_u16(450).unwrap(), ""),+ Error::ReauthRequired+ ));+// Anything unrecognised must keep Apple's own words rather than flatten to a status.let other = r#"{"serviceErrors":[{"code":"-20101","message":"Account locked."}]}"#;match apple_error("signing in", StatusCode::CONFLICT, other) {diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rsnew file mode 100644index 0000000..3e9a5f2--- /dev/null+++ b/crates/quince-auth/tests/auth_flow.rs@@ -0,0 +1,306 @@+//! The sign-in flow against a mock Apple, so regressions surface in CI rather than on a+//! real account. Two shipped bugs motivated this file:+//!+//! * the idmsa Origin was sent to endpoints that expect icloud.com, earning a 409;+//! * an abandoned two-factor attempt left `scnt` behind, and replaying it into the next+//! `/signin/init` made Apple reject a sign-in that should have succeeded.+//!+//! Both are asserted here. The SRP maths itself is covered by vectors in `srp.rs`; this file+//! is about the HTTP conversation.++use quince_auth::{Client, Endpoints, SignInOutcome, Store};+use serde_json::json;+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, Request, ResponseTemplate};++/// Distinct from the mock's own URL so an Origin assertion means something.+const SRP_ORIGIN: &str = "https://idmsa.test.invalid";+const WEB_ORIGIN: &str = "https://web.test.invalid";++fn endpoints_for(server: &MockServer) -> Endpoints {+ let base = server.uri();+ Endpoints {+ // Origins are header values only; pointing them elsewhere lets us prove which+ // origin each endpoint received.+ auth_root: SRP_ORIGIN.into(),+ home: WEB_ORIGIN.into(),+ auth: format!("{base}/appleauth/auth"),+ setup: format!("{base}/setup/ws/1"),+ }+}++fn b64(bytes: &[u8]) -> String {+ use base64::{engine::general_purpose::STANDARD as E, Engine};+ E.encode(bytes)+}++/// `/signin/init` answering with a well-formed SRP challenge.+async fn mount_init(server: &MockServer, status: u16) {+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/init"))+ .respond_with(+ ResponseTemplate::new(status)+ .insert_header("scnt", "scnt-from-init")+ .insert_header("X-Apple-ID-Session-Id", "session-from-init")+ .set_body_json(json!({+ "salt": b64(&[0x77; 16]),+ "b": b64(&[0x5e; 256]),+ "c": "challenge-c",+ "iteration": 20173,+ "protocol": "s2k",+ })),+ )+ .mount(server)+ .await;+}++async fn mount_complete(server: &MockServer, status: u16) {+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/complete"))+ .respond_with(+ ResponseTemplate::new(status)+ .insert_header("X-Apple-Session-Token", "session-token-abc")+ .insert_header("X-Apple-ID-Account-Country", "IND")+ .set_body_json(json!({})),+ )+ .mount(server)+ .await;+}++async fn mount_trust_and_login(server: &MockServer) {+ Mock::given(method("GET"))+ .and(path("/appleauth/auth/2sv/trust"))+ .respond_with(+ ResponseTemplate::new(204)+ .insert_header("X-Apple-TwoSV-Trust-Token", "trust-token-xyz")+ .insert_header("X-Apple-Session-Token", "session-token-def"),+ )+ .mount(server)+ .await;++ Mock::given(method("POST"))+ .and(path("/setup/ws/1/accountLogin"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "dsInfo": { "dsid": "1234567890" },+ "webservices": {+ "calendar": { "url": "https://p00-calendarws.test.invalid:443", "status": "active" },+ "ckdatabasews": { "url": "https://p00-ckdatabasews.test.invalid:443", "status": "active" }+ }+ })))+ .mount(server)+ .await;+}++fn client_for(server: &MockServer, dir: &std::path::Path) -> Client {+ Client::with(dir, endpoints_for(server), Store::file(dir).unwrap()).unwrap()+}++fn requests_to<'a>(reqs: &'a [Request], suffix: &str) -> Vec<&'a Request> {+ reqs.iter().filter(|r| r.url.path().ends_with(suffix)).collect()+}++#[tokio::test]+async fn two_factor_sign_in_stores_the_trust_token() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await; // 409 => two-factor required+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());++ let outcome = client.sign_in("[email protected]", "hunter2").await.unwrap();+ assert_eq!(outcome, SignInOutcome::NeedsTwoFactor);++ client.submit_two_factor("123456").await.unwrap();++ let session = client.session();+ assert_eq!(session.trust_token.as_deref(), Some("trust-token-xyz"));+ assert_eq!(session.dsid.as_deref(), Some("1234567890"));+ assert_eq!(+ session.service_url("calendar").as_deref(),+ Some("https://p00-calendarws.test.invalid:443"),+ "the service map should be usable without a trailing slash"+ );++ // A fresh client over the same store must resume without a password.+ let reloaded = client_for(&server, dir.path());+ assert!(reloaded.has_stored_session(), "the trust token must outlive the process");+}++/// The regression: an abandoned attempt left `scnt` behind, and replaying it into a new+/// `/signin/init` made Apple answer 409.+#[tokio::test]+async fn sign_in_never_replays_a_previous_challenge() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());++ // First attempt: abandoned after Apple asks for a code, leaving scnt/session id stored.+ client.sign_in("[email protected]", "hunter2").await.unwrap();+ assert_eq!(client.session().scnt.as_deref(), Some("scnt-from-init"));++ // Second attempt from the same session must start clean.+ client.sign_in("[email protected]", "hunter2").await.unwrap();++ let reqs = server.received_requests().await.unwrap();+ let inits = requests_to(&reqs, "/signin/init");+ assert_eq!(inits.len(), 2, "expected two sign-in attempts");+ for (i, req) in inits.iter().enumerate() {+ assert!(+ req.headers.get("scnt").is_none(),+ "/signin/init #{i} leaked scnt from an earlier challenge"+ );+ assert!(+ req.headers.get("x-apple-id-session-id").is_none(),+ "/signin/init #{i} leaked a session id from an earlier challenge"+ );+ }+}++/// The other regression: only the two SRP calls may carry the idmsa Origin.+#[tokio::test]+async fn idmsa_origin_is_used_only_for_sign_in() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client.sign_in("[email protected]", "hunter2").await.unwrap();+ client.submit_two_factor("123456").await.unwrap();++ let reqs = server.received_requests().await.unwrap();+ let origin_of = |r: &Request| {+ r.headers.get("origin").and_then(|v| v.to_str().ok()).unwrap_or("<none>").to_string()+ };++ for suffix in ["/signin/init", "/signin/complete"] {+ let found = requests_to(&reqs, suffix);+ assert!(!found.is_empty(), "no request reached {suffix}");+ for r in found {+ assert_eq!(origin_of(r), SRP_ORIGIN, "{suffix} must use the idmsa origin");+ }+ }++ for suffix in ["/verify/trusteddevice/securitycode", "/2sv/trust", "/accountLogin"] {+ let found = requests_to(&reqs, suffix);+ assert!(!found.is_empty(), "no request reached {suffix}");+ for r in found {+ assert_eq!(+ origin_of(r),+ WEB_ORIGIN,+ "{suffix} must use the icloud.com origin — the idmsa one earns a 409"+ );+ }+ }+}++#[tokio::test]+async fn a_wrong_code_is_reported_as_a_wrong_code() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(409).set_body_json(json!({+ "serviceErrors": [{ "code": "-21669", "message": "Incorrect verification code." }]+ })))+ .mount(&server)+ .await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client.sign_in("[email protected]", "hunter2").await.unwrap();++ let err = client.submit_two_factor("000000").await.unwrap_err();+ assert!(+ matches!(err, quince_auth::Error::BadCode),+ "a wrong code must not surface as a protocol failure: {err}"+ );+}++/// Apple answers 409 on this endpoint in flows where the code was in fact accepted. The+/// status alone is not evidence, so completion is what decides.+#[tokio::test]+async fn a_409_that_still_completes_is_treated_as_success() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(409).set_body_json(json!({+ "serviceErrors": [{ "code": "-20209", "message": "Unexpected." }]+ })))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client.sign_in("[email protected]", "hunter2").await.unwrap();++ client+ .submit_two_factor("123456")+ .await+ .expect("the session became usable, so the code was accepted");+ assert_eq!(client.session().trust_token.as_deref(), Some("trust-token-xyz"));+}++#[tokio::test]+async fn throttling_is_named_so_the_fix_is_to_wait() {+ let server = MockServer::start().await;+ mount_init(&server, 429).await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());++ let err = client.sign_in("[email protected]", "hunter2").await.unwrap_err();+ assert!(+ matches!(err, quince_auth::Error::RateLimited),+ "throttling must be distinguishable from a real failure: {err}"+ );+}++/// A dead stored session must not block a fresh sign-in.+#[tokio::test]+async fn a_rejected_session_falls_back_cleanly() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/validate"))+ .respond_with(ResponseTemplate::new(421))+ .mount(&server)+ .await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;++ let dir = tempfile::tempdir().unwrap();+ {+ // Seed a stored session that Apple will reject.+ let mut seed = client_for(&server, dir.path());+ seed.sign_in("[email protected]", "hunter2").await.unwrap();+ }++ let mut client = client_for(&server, dir.path());+ assert!(client.has_stored_session());+ assert!(!client.resume().await.unwrap(), "a 421 means the session is dead");+ assert!(client.session().scnt.is_none(), "a dead session must not keep its challenge state");++ // And signing in again still works.+ let outcome = client.sign_in("[email protected]", "hunter2").await.unwrap();+ assert_eq!(outcome, SignInOutcome::NeedsTwoFactor);+}diff --git a/probe/src/main.rs b/probe/src/main.rsindex c19f014..f4aec53 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -133,6 +133,10 @@ async fn probe_get(let detail = match (&parsed, status.is_success()) {(Some(v), true) => summarise(v),(_, true) => format!("{} bytes, non-JSON", body.len()),+ // 450 means Apple wants a fresh sign-in for this service specifically.+ _ if status.as_u16() == 450 => {+ "needs a fresh sign-in (a resumed session isn't accepted here)".to_string()+ }_ => body.chars().take(160).collect::<String>().replace('\n', " "),};Outcome { label, ok: status.is_success(), status: status.as_u16(), detail }