use bytes::Bytes; use std::sync::Arc; use tracing::instrument; use uuid::Uuid; use crate::{ error::Result, types::*, }; use super::{Session, SyncKitClient, TOKEN_EXPIRY_BUFFER_SECS}; use super::helpers::{check_response, jwt_exp}; impl SyncKitClient { /// Authenticate with the MNW server. Returns (user_id, app_id). /// /// `key` is the developer-defined SDK key this session's storage counts /// against. The dev's backend chooses it — typically one key per /// workspace/org/end-user. /// /// Stores the session internally. If called concurrently from multiple /// threads, the last write wins — earlier sessions are silently overwritten. /// /// # Errors /// /// Returns `Server { status: 401, .. }` for wrong credentials. #[instrument(skip(self, email, password))] pub async fn authenticate( &self, email: &str, password: &str, key: &str, ) -> Result<(Uuid, Uuid)> { let body = Bytes::from(serde_json::to_vec(&AuthRequest { email, password, api_key: &self.config.api_key, key, })?); let resp = self .retry_request(|| { let req = self .http .post(&self.endpoints.auth) .header("content-type", "application/json") .body(body.clone()); async move { check_response(req.send().await?).await } }) .await?; let auth: AuthResponse = resp.json().await?; let user_id = auth.user_id; let app_id = auth.app_id; let token_exp = jwt_exp(&auth.token); *self.session.write() = Some(Session { token: Arc::new(auth.token), token_exp, user_id, app_id, }); tracing::info!("Authenticated as user {user_id} for app {app_id}"); Ok((user_id, app_id)) } /// Restore a session from previously stored credentials (e.g. OS keychain). /// /// Sets the internal session state without making any HTTP calls. /// Used on app startup to restore from stored credentials without re-authenticating. pub fn restore_session(&self, token: &str, user_id: Uuid, app_id: Uuid) { let token_exp = jwt_exp(token); *self.session.write() = Some(Session { token: Arc::new(token.to_string()), token_exp, user_id, app_id, }); tracing::info!("Session restored for user {user_id}, app {app_id}"); } /// Clear the in-memory session and master key. /// /// After calling this, the client will need to re-authenticate and set up /// encryption again. Does not affect OS keychain storage — call /// `keystore::delete_master_key` separately if needed. pub fn clear_session(&self) { *self.session.write() = None; *self.master_key.write() = None; tracing::info!("Session and master key cleared"); } /// Check whether the current session token has expired (or will expire /// within a 30-second buffer). Returns `true` if there is no session or /// if the token's `exp` claim is in the past. Returns `false` if the /// token cannot be decoded (assumes not expired — the server will reject /// it with a 401 if it actually is). pub fn is_token_expired(&self) -> bool { let guard = self.session.read(); let Some(session) = guard.as_ref() else { return true; }; match session.token_exp { Some(exp) => { let now = chrono::Utc::now().timestamp(); now >= exp - TOKEN_EXPIRY_BUFFER_SECS } None => false, } } // ── OAuth ── /// Build the authorization URL for the OAuth2 PKCE flow. /// /// The caller is responsible for generating the PKCE verifier/challenge, /// starting the localhost callback server, and opening the browser. pub fn build_authorize_url( &self, redirect_port: u16, state: &str, code_challenge: &str, ) -> String { format!( "{}/oauth/authorize?response_type=code&client_id={}&redirect_uri={}&state={}&code_challenge={}&code_challenge_method=S256", self.config.server_url, urlencoding::encode(&self.config.api_key), urlencoding::encode(&format!("http://127.0.0.1:{}/", redirect_port)), urlencoding::encode(state), urlencoding::encode(code_challenge), ) } /// Exchange an OAuth2 authorization code for a SyncKit JWT. /// /// `key` is the developer-defined SDK key for billing attribution — see /// [`authenticate`](Self::authenticate). /// /// Call this after receiving the code from the localhost callback server. /// On success, stores the session internally (same as `authenticate()`). #[instrument(skip(self, code, code_verifier))] pub async fn authenticate_with_code( &self, code: &str, code_verifier: &str, redirect_port: u16, key: &str, ) -> Result<(Uuid, Uuid)> { let redirect_uri = format!("http://127.0.0.1:{}/", redirect_port); let form_params = [ ("grant_type", "authorization_code"), ("code", code), ("redirect_uri", &redirect_uri), ("code_verifier", code_verifier), ("client_id", &self.config.api_key), ("key", key), ]; // OAuth authorization codes are single-use. Retrying after a // network error would send an already-consumed code, producing a // permanent 400. Send exactly once and let the caller restart the // OAuth flow on failure. let resp = check_response( self.http .post(&self.endpoints.oauth_token) .form(&form_params) .send() .await?, ) .await?; let token_resp: OAuthTokenResponse = resp.json().await?; let user_id = token_resp.user_id; let app_id = token_resp.app_id; let token_exp = jwt_exp(&token_resp.access_token); *self.session.write() = Some(Session { token: Arc::new(token_resp.access_token), token_exp, user_id, app_id, }); tracing::info!("Authenticated via OAuth as user {user_id} for app {app_id}"); Ok((user_id, app_id)) } } #[cfg(test)] mod tests { use super::*; use base64::Engine; use chrono::Utc; use crate::error::SyncKitError; fn test_config() -> super::super::SyncKitConfig { super::super::SyncKitConfig { server_url: "https://example.com".to_string(), api_key: "test-api-key-123".to_string(), } } fn test_ids() -> (Uuid, Uuid) { ( Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(), Uuid::parse_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap(), ) } fn fake_jwt(exp: i64) -> String { let header = base64::engine::general_purpose::URL_SAFE_NO_PAD .encode(r#"{"alg":"HS256","typ":"JWT"}"#); let payload_json = serde_json::json!({ "sub": "550e8400-e29b-41d4-a716-446655440000", "app": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "exp": exp, "iat": exp - 3600, }); let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD .encode(payload_json.to_string().as_bytes()); let signature = base64::engine::general_purpose::URL_SAFE_NO_PAD .encode(b"fake-signature"); format!("{header}.{payload}.{signature}") } // ── restore_session ── #[test] fn restore_session_makes_client_authenticated() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); client.restore_session("fake-token", user_id, app_id); let info = client.session_info().expect("session should exist"); assert_eq!(*info.token, "fake-token"); assert_eq!(info.user_id, user_id); assert_eq!(info.app_id, app_id); } #[test] fn restore_session_overwrites_previous_session() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); client.restore_session("first-token", user_id, app_id); client.restore_session("second-token", user_id, app_id); let info = client.session_info().unwrap(); assert_eq!(*info.token, "second-token"); } // ── build_authorize_url ── #[test] fn build_authorize_url_includes_all_params() { let client = SyncKitClient::new(test_config()); let url = client.build_authorize_url(8080, "random-state", "challenge123"); assert!(url.starts_with("https://example.com/oauth/authorize?")); assert!(url.contains("response_type=code")); assert!(url.contains("client_id=test-api-key-123")); assert!(url.contains("redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2F")); assert!(url.contains("state=random-state")); assert!(url.contains("code_challenge=challenge123")); assert!(url.contains("code_challenge_method=S256")); } #[test] fn build_authorize_url_encodes_special_chars() { let config = super::super::SyncKitConfig { server_url: "https://example.com".to_string(), api_key: "key with spaces&special=chars".to_string(), }; let client = SyncKitClient::new(config); let url = client.build_authorize_url(9090, "state/with/slashes", "ch+all=enge"); assert!(url.contains("key%20with%20spaces%26special%3Dchars")); assert!(url.contains("state%2Fwith%2Fslashes")); assert!(url.contains("ch%2Ball%3Denge")); } #[test] fn build_authorize_url_different_ports() { let client = SyncKitClient::new(test_config()); let url_low = client.build_authorize_url(1234, "s", "c"); assert!(url_low.contains("127.0.0.1%3A1234")); let url_high = client.build_authorize_url(65535, "s", "c"); assert!(url_high.contains("127.0.0.1%3A65535")); } // ── is_token_expired ── #[test] fn is_token_expired_true_without_session() { let client = SyncKitClient::new(test_config()); assert!(client.is_token_expired()); } #[test] fn is_token_expired_true_with_expired_token() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); let token = fake_jwt(Utc::now().timestamp() - 3600); client.restore_session(&token, user_id, app_id); assert!(client.is_token_expired()); } #[test] fn is_token_expired_false_with_fresh_token() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); let token = fake_jwt(Utc::now().timestamp() + 3600); client.restore_session(&token, user_id, app_id); assert!(!client.is_token_expired()); } // ── require_token with expiry ── #[test] fn require_token_returns_token_expired_for_expired_token() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); let token = fake_jwt(Utc::now().timestamp() - 3600); client.restore_session(&token, user_id, app_id); let err = client.require_token().unwrap_err(); assert!(matches!(err, SyncKitError::TokenExpired)); } #[test] fn require_token_succeeds_with_fresh_token() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); let token = fake_jwt(Utc::now().timestamp() + 3600); client.restore_session(&token, user_id, app_id); assert!(client.require_token().is_ok()); } // ── clear_session ── #[test] fn clear_session_clears_master_key() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); client.restore_session("token", user_id, app_id); client.set_master_key_raw([42u8; 32]); assert!(client.session_info().is_some()); assert!(client.has_master_key()); client.clear_session(); assert!(client.session_info().is_none()); assert!(!client.has_master_key()); } // ── OAuth types ── #[test] fn oauth_token_response_deserialization() { let json = r#"{ "access_token": "jwt-access-token", "token_type": "Bearer", "expires_in": 3600, "user_id": "550e8400-e29b-41d4-a716-446655440000", "app_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8" }"#; let resp: OAuthTokenResponse = serde_json::from_str(json).unwrap(); assert_eq!(resp.access_token, "jwt-access-token"); assert_eq!(resp.token_type, "Bearer"); assert_eq!(resp.expires_in, 3600); } // ── Auth types ── #[test] fn auth_request_serialization() { let req = AuthRequest { email: "user@example.com", password: "secret123", api_key: "ak_test", key: "session-key-abc", }; let json = serde_json::to_string(&req).unwrap(); let parsed: serde_json::Value = serde_json::from_str(&json).unwrap(); assert_eq!(parsed["email"], "user@example.com"); assert_eq!(parsed["password"], "secret123"); assert_eq!(parsed["api_key"], "ak_test"); assert_eq!(parsed["key"], "session-key-abc"); } #[test] fn auth_response_deserialization() { let json = r#"{ "token": "jwt.token.here", "user_id": "550e8400-e29b-41d4-a716-446655440000", "app_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8" }"#; let resp: AuthResponse = serde_json::from_str(json).unwrap(); assert_eq!(resp.token, "jwt.token.here"); assert_eq!( resp.user_id, Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap() ); } #[test] fn auth_response_missing_token_fails() { let json = r#"{"user_id": "550e8400-e29b-41d4-a716-446655440000", "app_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8"}"#; let result = serde_json::from_str::(json); assert!(result.is_err()); } }