diff --git a/CHANGELOG.md b/CHANGELOG.md index 3093533..5347c95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - SSE IPO rows show Applied only when an application is live. Any order object in Kite's reply used to mark the issue applied, even after every application had failed or been cancelled. - The IPO & Bids sections use Kite web's labels: Place bid for GSecs and corporate actions without an order, Give back or Pre-apply for open SSE issues, and order statuses in capitals. - `kite stream ticks` always suggests `kite auth login` when Kite rejects the session. If the rejection arrived before the subscription went out, the hint was left off. +- `kite auth logout` keeps a token it could not revoke on Kite and retries it on the next logout, reporting the result. It previously discarded the token, so a second logout printed "nothing to revoke" while the session was still active on Kite. +- A running TUI returns to the sign-in screen within a few seconds of `kite auth logout`, and restarts on the new session after a login in another terminal. It previously kept using the token it started with. +- Logging out from the TUI revokes the session on Kite. It previously only removed the local token. ## [0.2.3] - 2026-11-12 diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 0ff486f..355a7af 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -30,6 +30,7 @@ Run `kite config path` to print the active configuration path. The file does not | :--- | :--- | :--- | | `user_id` | `kite auth login` | Your Kite user ID (offered as the default on subsequent logins) | | `access_token` | `kite auth login` | Active session token (removed by `kite auth logout`) | +| `revoke_pending` | `kite auth logout` | Tokens from earlier logouts that Kite has not confirmed as revoked; the next `kite auth logout` retries them | | `app_uuid` | `kite auth login` | Random v4 UUID sent as the app identity (`kite` generates an in-memory identity for read commands if none is saved) | | `api_key` | User | Kite API key (required only when running a source build without a built-in key) | | `api_root` | User | Base REST API URL (required only when running a source build without a built-in URL) | @@ -97,7 +98,7 @@ When compiling from source with `cargo build` or `cargo install`, these environm `kite auth login` writes `user_id`, `access_token`, and `app_uuid` to `config.json`. It never stores your password or 2FA code. - **Daily expiry** — Kite access tokens expire daily around **06:00 IST**. `kite` never renews tokens automatically. When Kite rejects an expired token with `TokenException`, CLI commands exit with an error prompting you to run `kite auth login`, and the TUI returns to its sign-in screen. -- **Logout** — `kite auth logout` revokes the saved token on Kite's servers and removes `access_token` from `config.json`, while preserving `user_id`, `app_uuid`, and endpoint settings. If remote revocation fails, `kite` warns you and still deletes the local token; sign in to Kite Web and log out there to ensure server-side revocation. +- **Logout** — `kite auth logout` revokes the saved token on Kite's servers and removes `access_token` from `config.json`, while preserving `user_id`, `app_uuid`, and endpoint settings. If remote revocation fails, `kite` warns you, still deletes the local token, and keeps it in `revoke_pending` so the next `kite auth logout` retries the revocation and reports the result. A TUI that is already running notices the cleared session within a few seconds and returns to the sign-in screen. Logging out from the TUI revokes the token the same way. ### `KITE_ACCESS_TOKEN` diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index b952e9d..38cee18 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -80,7 +80,7 @@ kite auth logout `kite auth logout` revokes the saved access token on Kite's servers and removes `access_token` from `config.json` while retaining your `user_id` for the next login. It takes effect immediately and does not require `--confirm`. -- If remote revocation fails (for example, due to a network error), `kite` warns you and still removes the local token. To ensure the session is terminated on Kite's side, sign in to Kite Web and log out there. +- If remote revocation fails (for example, due to a network error), `kite` warns you and still removes the local token. It remembers the token, so running `kite auth logout` again once you are online revokes it and says so. A running TUI returns to the sign-in screen once the saved session is gone. - If you override your session with the `KITE_ACCESS_TOKEN` environment variable, see [`KITE_ACCESS_TOKEN` logout rules](configuration.md#kite_access_token) — `kite auth logout` only revokes the token stored in `config.json`. ## Session expiry diff --git a/src/app/logout.rs b/src/app/logout.rs new file mode 100644 index 0000000..041b8bb --- /dev/null +++ b/src/app/logout.rs @@ -0,0 +1,114 @@ +use crate::app::runtime::Runtime; +use crate::app_api::trusted::TrustedAuth; +use anyhow::Result; +use kiteconnect::error::sanitize_error; +use std::path::PathBuf; + +/// What ending the saved session did on Kite. +#[derive(Debug)] +pub struct SessionEnd { + pub path: PathBuf, + pub had_session: bool, + /// Kite confirmed the current session ended. + pub revoked: bool, + /// Sessions from earlier logouts that Kite has now confirmed ended. + pub earlier_revoked: usize, + /// Sessions Kite has not confirmed ended, kept for the next logout. + pub pending: usize, + pub error: Option, +} + +impl SessionEnd { + #[must_use] + pub fn warning(&self) -> Option { + let error = self.error.as_deref()?; + Some(format!( + "could not revoke {} on Kite: {error}. A session stays active until 6 AM IST unless revoked; run `kite auth logout` again when Kite is reachable, or log out on Kite", + sessions(self.pending) + )) + } + + #[must_use] + pub fn details(&self) -> Vec { + let path = self.path.display(); + let mut details = vec![if self.revoked { + format!("Session revoked on Kite and removed from {path}") + } else if self.had_session { + format!("Session removed from {path}; it is not yet revoked on Kite") + } else if self.earlier_revoked == 0 && self.pending == 0 { + "No saved session; nothing to revoke.".to_string() + } else { + "No saved session.".to_string() + }]; + if self.earlier_revoked > 0 { + details.push(format!( + "Revoked {} on Kite from an earlier logout", + sessions(self.earlier_revoked) + )); + } + details + } +} + +fn sessions(count: usize) -> String { + if count == 1 { + "1 session".to_string() + } else { + format!("{count} sessions") + } +} + +/// Revokes the saved session and any left over from earlier logouts, then +/// clears the saved session. A token is dropped only once Kite confirms it +/// ended, so a logout that cannot reach Kite is retried by the next one. +/// +/// # Errors +/// Returns an error if the config cannot be read or written. +pub async fn end_session(rt: &Runtime) -> Result { + let (_, _, config) = rt.load_config()?; + let had_session = config.access_token.is_some(); + let mut tokens = config.revoke_pending; + tokens.retain(|token| Some(token) != config.access_token.as_ref()); + let earlier = tokens.len(); + tokens.extend(config.access_token); + + let mut end = SessionEnd { + path: PathBuf::new(), + had_session, + revoked: false, + earlier_revoked: 0, + pending: 0, + error: None, + }; + let mut pending = Vec::new(); + if !tokens.is_empty() { + let auth = rt.resolve_credentials().and_then(|creds| { + TrustedAuth::new(creds.api_root()?, creds.api_key()?, &rt.app_uuid()?) + }); + for (index, token) in tokens.into_iter().enumerate() { + let outcome = match &auth { + Ok(auth) => auth.invalidate(&token).await.or_else(already_ended), + Err(error) => Err(anyhow::anyhow!("{error}")), + }; + match outcome { + Ok(()) if index < earlier => end.earlier_revoked += 1, + Ok(()) => end.revoked = true, + Err(error) => { + end.error = Some(sanitize_error(&error.to_string())); + pending.push(token); + } + } + } + } + end.pending = pending.len(); + end.path = rt.clear_session(pending)?; + Ok(end) +} + +/// Kite rejecting the token itself means the session has already ended. +fn already_ended(error: anyhow::Error) -> Result<()> { + match error.downcast_ref::() { + Some(kite) if kite.is_session_expired() => Ok(()), + _ => Err(error), + } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index e7dafb8..9325cd5 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1,5 +1,6 @@ pub mod errors; pub mod http; +pub mod logout; pub mod output; pub mod release; pub mod render; diff --git a/src/app/runtime.rs b/src/app/runtime.rs index 1466edf..5193f51 100644 --- a/src/app/runtime.rs +++ b/src/app/runtime.rs @@ -33,6 +33,9 @@ pub struct ConfigFile { #[serde(skip_serializing_if = "Option::is_none")] pub user_id: Option, pub access_token: Option, + /// Tokens from earlier logouts that Kite has not confirmed as revoked. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub revoke_pending: Vec, } pub const SESSION_FIELDS: [&str; 1] = ["access_token"]; @@ -52,6 +55,7 @@ impl std::fmt::Debug for ConfigFile { .field("api_key", &self.api_key) .field("user_id", &self.user_id) .field("access_token", &redacted_option(self.access_token.as_ref())) + .field("revoke_pending", &self.revoke_pending.len()) .finish() } } @@ -210,16 +214,26 @@ impl Runtime { .clone()) } - /// Clears [`SESSION_FIELDS`] from the saved config. + /// Clears [`SESSION_FIELDS`] from the saved config and records the tokens + /// that still need revoking on Kite. /// /// # Errors /// Returns an error if the config cannot be loaded or saved. - pub fn clear_session(&self) -> Result { + pub fn clear_session(&self, revoke_pending: Vec) -> Result { let (_, _, mut config) = self.load_config()?; config.clear_session(); + config.revoke_pending = revoke_pending; self.save_config(&config) } + /// The access token saved in the config file, ignoring `KITE_ACCESS_TOKEN`. + /// + /// # Errors + /// Returns an error if the config cannot be loaded. + pub fn saved_access_token(&self) -> Result> { + Ok(self.load_config()?.2.access_token) + } + /// # Errors /// Returns an error if the saved config cannot be loaded. pub fn resolve_credentials(&self) -> Result { @@ -429,10 +443,13 @@ mod tests { api_root: Some("https://example.invalid".to_string()), app_uuid: None, ticker_url: None, + revoke_pending: vec!["PENDINGSECRET".to_string()], }; let out = format!("{cfg:?}"); assert!(!out.contains("SECRETVAL123"), "access_token leaked: {out}"); assert!(out.contains("access_token: Some(\"\")")); + assert!(out.contains("revoke_pending: 1"), "{out}"); + assert!(!out.contains("PENDINGSECRET"), "{out}"); assert!(out.contains("AB1234")); } @@ -542,7 +559,7 @@ mod tests { assert_eq!(mode, 0o600); } - rt.clear_session().unwrap(); + rt.clear_session(Vec::new()).unwrap(); let cleared: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); for field in SESSION_FIELDS { @@ -649,7 +666,7 @@ mod tests { .map(String::as_str) .collect(); assert_eq!(keys, ["access_token", "app_uuid", "user_id"]); - rt.clear_session().unwrap(); + rt.clear_session(Vec::new()).unwrap(); let config = rt.load_config().unwrap().2; assert_eq!(config.access_token, None); assert_eq!(config.user_id.as_deref(), Some("AB1234")); diff --git a/src/commands/auth.rs b/src/commands/auth.rs index 1d0511a..631878c 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -1,10 +1,10 @@ +use crate::app::logout::end_session; use crate::app::output::Output; use crate::app::render::{self, Doc, Term}; use crate::app::runtime::{Runtime, SESSION_FIELDS}; use crate::app_api::trusted::TrustedAuth; use crate::cli::AuthCommands; use anyhow::{Context, Result, bail}; -use kiteconnect::error::sanitize_error; use serde_json::json; use std::io::{self, IsTerminal, Write}; @@ -27,52 +27,31 @@ pub async fn handle(rt: &Runtime, command: AuthCommands) -> Result { } async fn logout(rt: &Runtime) -> Result { - let (_, _, config) = rt.load_config()?; - let mut revoked = false; - let had_session = config.access_token.is_some(); - let mut warning = None; - if let Some(access_token) = config.access_token { - let revoke = async { - let creds = rt.resolve_credentials()?; - TrustedAuth::new(creds.api_root()?, creds.api_key()?, &rt.app_uuid()?)? - .invalidate(&access_token) - .await - }; - match revoke.await { - Ok(()) => revoked = true, - Err(err) => { - let message = sanitize_error(&err.to_string()); - if rt.json { - eprintln!( - "warning: could not revoke session: {message}; the token may remain active until expiry. Sign in on Kite and log out there to revoke it" - ); - } - warning = Some(message); - } - } + let end = end_session(rt).await?; + let warning = end.warning(); + if rt.json + && let Some(warning) = &warning + { + eprintln!("warning: {warning}"); } - let path = rt.clear_session()?; + let details = end.details(); Ok(Output::view( json!({ "logged_out": true, - "revoked": revoked, + "revoked": end.revoked, + "earlier_revoked": end.earlier_revoked, + "revoke_pending": end.pending, "cleared_config_fields": SESSION_FIELDS, - "path": path, + "path": end.path, }), - move |value, doc| { - if let Some(message) = warning.as_deref() { - doc.warn(&format!("could not revoke the session on Kite: {message}; the token may remain active until expiry. Sign in on Kite and log out there to revoke it")); + move |_, doc| { + if let Some(warning) = warning.as_deref() { + doc.warn(warning); } doc.success("Logged out"); - let path = render::s(value, "path"); - let detail = if revoked { - format!("Session revoked on Kite and removed from {path}") - } else if had_session { - format!("Session removed from {path}; the token expires at 6 AM IST") - } else { - "No saved session; nothing to revoke.".into() - }; - doc.line(vec![format!(" {detail}").into()]); + for detail in &details { + doc.line(vec![format!(" {detail}").into()]); + } }, )) } diff --git a/src/tui.rs b/src/tui.rs index c71861c..563fdb1 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -25,7 +25,7 @@ mod workspace; use crate::app::runtime::Runtime; use crate::cli::TuiArgs; use crate::tui::app::App; -use crate::tui::event::AppEvent; +use crate::tui::event::{AppEvent, SessionChange}; use crate::tui::login::LoginReason; use crate::tui::marketwatch::{WatchId, WatchItem}; use crate::tui::notes::Pad; @@ -47,6 +47,8 @@ enum SessionExit { Quit, Relogin, Logout, + SignedOut, + Restart, } /// # Errors @@ -64,9 +66,17 @@ pub async fn run(rt: &Runtime, args: TuiArgs) -> Result<()> { login::run_login(rt, LoginReason::Expired).await?; } SessionExit::Logout => { - rt.clear_session()?; + let end = crate::app::logout::end_session(rt).await?; + if let Some(warning) = end.warning() { + eprintln!("kite: warning: {warning}"); + } + for detail in end.details() { + eprintln!("kite: {detail}"); + } return Ok(()); } + SessionExit::SignedOut => login::run_login(rt, LoginReason::SignedOut).await?, + SessionExit::Restart => {} } } } @@ -110,7 +120,20 @@ async fn run_session(rt: &Runtime, args: &TuiArgs) -> Result { app.uuid = rt.app_uuid()?; let ticker_url = url::Url::parse(rt.resolve_credentials()?.ticker_url()?).context("invalid ticker URL")?; - let tasks = spawn_session_tasks(client, ticker_url, events_tx, &mut app, &settings)?; + let in_use = rt.resolve_credentials()?.access_token; + let saved = rt + .saved_access_token()? + .filter(|saved| in_use.as_ref() == Some(saved)); + let mut tasks = + spawn_session_tasks(client, ticker_url, events_tx.clone(), &mut app, &settings)?; + if let Some(token) = saved { + tasks.push(event::spawn_session_watch( + rt.clone(), + token, + std::time::Duration::from_secs(2), + events_tx, + )); + } let mut terminal = match setup_terminal() { Ok(terminal) => terminal, @@ -253,6 +276,11 @@ where if app.ws_fatal.as_deref() == Some(app::SESSION_EXPIRED) { return Ok(SessionExit::Relogin); } + match app.session_change { + Some(SessionChange::SignedOut) => return Ok(SessionExit::SignedOut), + Some(SessionChange::Replaced) => return Ok(SessionExit::Restart), + None => {} + } } } @@ -471,6 +499,25 @@ mod tests { std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); } + #[tokio::test] + async fn a_saved_session_change_ends_the_tui_session() { + for (change, name) in [ + (SessionChange::SignedOut, "signed-out"), + (SessionChange::Replaced, "replaced"), + ] { + let (mut app, mut terminal, events_tx, mut events_rx, path) = session(name); + events_tx.try_send(AppEvent::Session(change)).unwrap(); + let exit = event_loop(&mut terminal, &mut app, &mut events_rx) + .await + .unwrap(); + match change { + SessionChange::SignedOut => assert!(matches!(exit, SessionExit::SignedOut)), + SessionChange::Replaced => assert!(matches!(exit, SessionExit::Restart)), + } + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + } + #[tokio::test] async fn a_ticker_auth_rejection_ends_the_session_for_recovery() { let (mut app, mut terminal, events_tx, mut events_rx, path) = session("ws-auth"); diff --git a/src/tui/app/events/mod.rs b/src/tui/app/events/mod.rs index 88e018c..cb21600 100644 --- a/src/tui/app/events/mod.rs +++ b/src/tui/app/events/mod.rs @@ -33,6 +33,7 @@ impl App { } AppEvent::Ws(event) => self.on_ws(event), AppEvent::Data(event) => self.on_data(event), + AppEvent::Session(change) => self.session_change = Some(change), } } diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs index c7d108e..8ab4392 100644 --- a/src/tui/app/mod.rs +++ b/src/tui/app/mod.rs @@ -211,6 +211,8 @@ pub struct App { pub should_logout: bool, + pub session_change: Option, + exit_notice: Option, pub ws_state: WsState, diff --git a/src/tui/app/palette/execute.rs b/src/tui/app/palette/execute.rs index 106abfb..a6fbe2c 100644 --- a/src/tui/app/palette/execute.rs +++ b/src/tui/app/palette/execute.rs @@ -126,7 +126,7 @@ impl App { "LOGOUT".to_string(), vec![( "Session".to_string(), - "clear saved Kite credentials and exit".to_string(), + "revoke on Kite, clear saved credentials and exit".to_string(), )], PendingAction::Logout, )))), diff --git a/src/tui/app/state.rs b/src/tui/app/state.rs index a00747b..1ebe6c4 100644 --- a/src/tui/app/state.rs +++ b/src/tui/app/state.rs @@ -64,6 +64,7 @@ impl App { chart_panel: None, should_quit: false, should_logout: false, + session_change: None, exit_notice: None, ws_state: WsState::Connecting, ws_fatal: None, diff --git a/src/tui/event.rs b/src/tui/event.rs index 7c6b591..eebb5ad 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -1,3 +1,4 @@ +use crate::app::runtime::Runtime; use crate::tui::data::DataEvent; use crossterm::event::{ Event, EventStream, KeyEvent, KeyEventKind, MouseButton, MouseEvent, MouseEventKind, @@ -18,6 +19,40 @@ pub enum AppEvent { Ws(TickerEvent), Data(DataEvent), Timer, + Session(SessionChange), +} + +/// How the saved session changed under a running TUI. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionChange { + /// `kite auth logout` cleared it. + SignedOut, + /// A new login replaced it. + Replaced, +} + +/// Reports the first change to the saved access token the TUI started with, +/// checking every `every`. +pub fn spawn_session_watch( + rt: Runtime, + token: String, + every: Duration, + tx: mpsc::Sender, +) -> JoinHandle<()> { + tokio::spawn(async move { + let mut interval = tokio::time::interval(every); + loop { + interval.tick().await; + let change = match rt.saved_access_token() { + Ok(Some(saved)) if saved == token => continue, + Ok(Some(_)) => SessionChange::Replaced, + Ok(None) => SessionChange::SignedOut, + Err(_) => continue, + }; + let _ = tx.send(AppEvent::Session(change)).await; + return; + } + }) } pub fn spawn_terminal_events(tx: mpsc::Sender) -> JoinHandle<()> { @@ -125,3 +160,54 @@ pub enum WsState { Reconnecting, Closed, } + +#[cfg(test)] +mod tests { + use super::{AppEvent, SessionChange, spawn_session_watch}; + use crate::app::runtime::Runtime; + use crate::cli::Cli; + use clap::Parser; + use std::time::Duration; + + #[tokio::test] + async fn the_session_watch_reports_a_cleared_or_replaced_token() { + for (saved_after, expected) in [ + (None, SessionChange::SignedOut), + (Some("new-token"), SessionChange::Replaced), + ] { + let dir = std::env::temp_dir().join(format!( + "kite-session-watch-{}-{expected:?}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("config.json"); + let write = |token: Option<&str>| { + std::fs::write( + &path, + serde_json::json!({ "access_token": token }).to_string(), + ) + .unwrap(); + }; + write(Some("old-token")); + let rt = Runtime::from_cli( + &Cli::try_parse_from(["kite", "--config", path.to_str().unwrap()]).unwrap(), + ); + let (tx, mut rx) = tokio::sync::mpsc::channel(1); + let watch = spawn_session_watch(rt, "old-token".into(), Duration::from_millis(10), tx); + + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + rx.try_recv().is_err(), + "an unchanged session is not reported" + ); + write(saved_after); + let event = rx.recv().await.expect("the change is reported"); + assert!( + matches!(event, AppEvent::Session(change) if change == expected), + "{event:?}" + ); + watch.await.unwrap(); + std::fs::remove_dir_all(&dir).ok(); + } + } +} diff --git a/src/tui/login.rs b/src/tui/login.rs index e987cfb..d76e5e8 100644 --- a/src/tui/login.rs +++ b/src/tui/login.rs @@ -22,6 +22,7 @@ const CARD_HEIGHT: u16 = 12; pub enum LoginReason { FirstRun, Expired, + SignedOut, } impl LoginReason { @@ -29,6 +30,7 @@ impl LoginReason { match self { LoginReason::FirstRun => "Sign in to Kite", LoginReason::Expired => "Session expired, please sign in again.", + LoginReason::SignedOut => "Signed out with `kite auth logout`, please sign in again.", } } } diff --git a/src/tui/ui/modals/confirm.rs b/src/tui/ui/modals/confirm.rs index 9c1f100..1528419 100644 --- a/src/tui/ui/modals/confirm.rs +++ b/src/tui/ui/modals/confirm.rs @@ -224,7 +224,9 @@ fn confirm_copy(state: &ConfirmState) -> ConfirmCopy { title: confirm(), subtitle: "Clear stored session and exit", section: "Session", - impact: &["Clears the saved session and exits the terminal."], + impact: &[ + "Revokes the session on Kite, clears the saved session and exits the terminal.", + ], wide_note: None, }, } @@ -727,13 +729,14 @@ mod render_tests { "LOGOUT".to_string(), vec![( "Session".to_string(), - "clear saved Kite credentials and exit".to_string(), + "revoke on Kite, clear saved credentials and exit".to_string(), )], PendingAction::Logout, ); let text = modal_ascii(80, 24, |frame| draw_confirm(frame, &state, &app)); assert!(text.contains("Clear stored session and exit"), "{text}"); assert!(text.contains("[y/Enter Clear session and exit]"), "{text}"); + assert!(text.contains("Revokes the session on Kite"), "{text}"); } #[test] diff --git a/tests/cli_output.rs b/tests/cli_output.rs index 91a7a39..4cfc258 100644 --- a/tests/cli_output.rs +++ b/tests/cli_output.rs @@ -442,6 +442,98 @@ fn logout_is_immediate_and_preserves_live_json_on_both_outcomes() { } } +#[test] +fn a_logout_that_cannot_revoke_is_retried_by_the_next_one() { + let setup = Setup::new(); + let binary = Path::new(env!("CARGO_BIN_EXE_kite")); + let config = || -> Value { serde_json::from_slice(&fs::read(&setup.config).unwrap()).unwrap() }; + let logout = || { + let output = setup.run(binary, &["auth", "logout"], true); + assert_eq!(output.status.code(), Some(0)); + let body: Value = serde_json::from_slice(&output.stdout).unwrap(); + (body, String::from_utf8(output.stderr).unwrap()) + }; + + let mut down = setup.server.mock(|when, then| { + when.method(DELETE).path("/session/token"); + then.status(503).json_body( + json!({"status":"error","error_type":"NetworkException","message":"unavailable"}), + ); + }); + let (body, stderr) = logout(); + assert_eq!( + (body["revoked"].clone(), body["revoke_pending"].clone()), + (json!(false), json!(1)) + ); + assert!( + stderr.contains("could not revoke 1 session on Kite"), + "{stderr}" + ); + assert_eq!(config()["access_token"], Value::Null); + assert_eq!(config()["revoke_pending"], json!(["test-token"])); + down.assert_calls(1); + down.delete(); + + let up = setup.server.mock(|when, then| { + when.method(DELETE) + .path("/session/token") + .query_param("access_token", "test-token"); + then.status(200) + .json_body(json!({"status":"success","data":true})); + }); + let (body, stderr) = logout(); + assert_eq!( + ( + body["revoked"].clone(), + body["earlier_revoked"].clone(), + body["revoke_pending"].clone() + ), + (json!(false), json!(1), json!(0)) + ); + assert_eq!(stderr, ""); + assert_eq!(config().get("revoke_pending"), None); + up.assert_calls(1); + + let human = setup.run(binary, &["auth", "logout"], false); + assert_eq!( + String::from_utf8(human.stdout).unwrap(), + "✓ Logged out\n No saved session; nothing to revoke.\n" + ); + up.assert_calls(1); +} + +#[test] +fn a_pending_token_kite_already_ended_is_dropped() { + let setup = Setup::new(); + let mut saved: Value = { + setup.save_session(); + serde_json::from_slice(&fs::read(&setup.config).unwrap()).unwrap() + }; + saved["access_token"] = Value::Null; + saved["revoke_pending"] = json!(["expired-token"]); + fs::write(&setup.config, serde_json::to_vec(&saved).unwrap()).unwrap(); + let mock = setup.server.mock(|when, then| { + when.method(DELETE).path("/session/token"); + then.status(403).json_body( + json!({"status":"error","error_type":"TokenException","message":"Invalid session"}), + ); + }); + let output = setup.run( + Path::new(env!("CARGO_BIN_EXE_kite")), + &["auth", "logout"], + false, + ); + assert_eq!(output.status.code(), Some(0)); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + "✓ Logged out\n No saved session.\n Revoked 1 session on Kite from an earlier logout\n" + ); + assert_eq!(output.stderr, b""); + let config: Value = serde_json::from_slice(&fs::read(&setup.config).unwrap()).unwrap(); + assert_eq!(config.get("revoke_pending"), None); + mock.assert_calls(1); +} + #[test] fn doctor_and_paths_are_human_and_json_stays_unchanged() { let setup = Setup::new(); diff --git a/tests/fixtures/cli-output/json-logout-failed.stderr b/tests/fixtures/cli-output/json-logout-failed.stderr index dc42053..5afe1be 100644 --- a/tests/fixtures/cli-output/json-logout-failed.stderr +++ b/tests/fixtures/cli-output/json-logout-failed.stderr @@ -1 +1 @@ -warning: could not revoke session: kite API error InputException (HTTP 403): revoke failed; the token may remain active until expiry. Sign in on Kite and log out there to revoke it +warning: could not revoke 1 session on Kite: kite API error InputException (HTTP 403): revoke failed. A session stays active until 6 AM IST unless revoked; run `kite auth logout` again when Kite is reachable, or log out on Kite diff --git a/tests/fixtures/cli-output/json-logout-failed.stdout b/tests/fixtures/cli-output/json-logout-failed.stdout index e86bacb..45b9f94 100644 --- a/tests/fixtures/cli-output/json-logout-failed.stdout +++ b/tests/fixtures/cli-output/json-logout-failed.stdout @@ -2,7 +2,9 @@ "cleared_config_fields": [ "access_token" ], + "earlier_revoked": 0, "logged_out": true, "path": "/home/user/config.json", + "revoke_pending": 1, "revoked": false } diff --git a/tests/fixtures/cli-output/json-logout.stdout b/tests/fixtures/cli-output/json-logout.stdout index e235818..08989c5 100644 --- a/tests/fixtures/cli-output/json-logout.stdout +++ b/tests/fixtures/cli-output/json-logout.stdout @@ -2,7 +2,9 @@ "cleared_config_fields": [ "access_token" ], + "earlier_revoked": 0, "logged_out": true, "path": "/home/user/config.json", + "revoke_pending": 0, "revoked": true } diff --git a/tests/fixtures/cli-output/logout-failed.stderr b/tests/fixtures/cli-output/logout-failed.stderr index 110dcbf..5afe1be 100644 --- a/tests/fixtures/cli-output/logout-failed.stderr +++ b/tests/fixtures/cli-output/logout-failed.stderr @@ -1 +1 @@ -warning: could not revoke the session on Kite: kite API error InputException (HTTP 403): revoke failed; the token may remain active until expiry. Sign in on Kite and log out there to revoke it +warning: could not revoke 1 session on Kite: kite API error InputException (HTTP 403): revoke failed. A session stays active until 6 AM IST unless revoked; run `kite auth logout` again when Kite is reachable, or log out on Kite diff --git a/tests/fixtures/cli-output/logout-failed.stdout b/tests/fixtures/cli-output/logout-failed.stdout index 15a612d..d7f94cc 100644 --- a/tests/fixtures/cli-output/logout-failed.stdout +++ b/tests/fixtures/cli-output/logout-failed.stdout @@ -1,2 +1,2 @@ ✓ Logged out - Session removed from /home/user/config.json; the token expires at 6 AM IST + Session removed from /home/user/config.json; it is not yet revoked on Kite diff --git a/tests/kiteconnect_mocks.rs b/tests/kiteconnect_mocks.rs index 4038c4e..6ede637 100644 --- a/tests/kiteconnect_mocks.rs +++ b/tests/kiteconnect_mocks.rs @@ -639,7 +639,7 @@ fn mf_instrument_commands_reach_network_without_config() { } #[test] -fn logout_revokes_saved_tokens_and_clears_local_fields_even_on_failure() { +fn logout_revokes_saved_tokens_and_counts_an_already_invalid_token_as_ended() { for status in [200, 403] { let server = MockServer::start(); let mock = server.mock(|when, then| { @@ -691,7 +691,7 @@ fn logout_revokes_saved_tokens_and_clears_local_fields_even_on_failure() { assert_eq!( serde_json::from_slice::(&output.stdout).unwrap(), serde_json::json!({ - "logged_out":true, "revoked":status == 200, + "logged_out":true, "revoked":true, "earlier_revoked":0, "revoke_pending":0, "cleared_config_fields":["access_token"], "path":path, }) ); @@ -708,7 +708,7 @@ fn logout_revokes_saved_tokens_and_clears_local_fields_even_on_failure() { } #[test] -fn logout_clears_saved_session_when_api_values_are_missing() { +fn logout_clears_saved_session_and_keeps_it_pending_when_api_values_are_missing() { let path = env::temp_dir().join(format!("kite-logout-missing-{}.json", std::process::id())); for (build_value, mut config, warning) in [ ( @@ -753,7 +753,7 @@ fn logout_clears_saved_session_when_api_values_are_missing() { assert_eq!( serde_json::from_slice::(&output.stdout).unwrap(), serde_json::json!({ - "logged_out":true, "revoked":false, + "logged_out":true, "revoked":false, "earlier_revoked":0, "revoke_pending":1, "cleared_config_fields":["access_token"], "path":path, }) ); @@ -765,6 +765,7 @@ fn logout_clears_saved_session_when_api_values_are_missing() { .unwrap() .retain(|_, value| !value.is_null()); config["access_token"] = Value::Null; + config["revoke_pending"] = serde_json::json!(["SENTINEL-TOKEN"]); assert_eq!( serde_json::from_str::(&fs::read_to_string(&path).unwrap()).unwrap(), config