Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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`

Expand Down
2 changes: 1 addition & 1 deletion docs/guide/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
114 changes: 114 additions & 0 deletions src/app/logout.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
}

impl SessionEnd {
#[must_use]
pub fn warning(&self) -> Option<String> {
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<String> {
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<SessionEnd> {
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::<kiteconnect::Error>() {
Some(kite) if kite.is_session_expired() => Ok(()),
_ => Err(error),
}
}
1 change: 1 addition & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod errors;
pub mod http;
pub mod logout;
pub mod output;
pub mod release;
pub mod render;
Expand Down
25 changes: 21 additions & 4 deletions src/app/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ pub struct ConfigFile {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_id: Option<String>,
pub access_token: Option<String>,
/// Tokens from earlier logouts that Kite has not confirmed as revoked.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub revoke_pending: Vec<String>,
}

pub const SESSION_FIELDS: [&str; 1] = ["access_token"];
Expand All @@ -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()
}
}
Expand Down Expand Up @@ -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<PathBuf> {
pub fn clear_session(&self, revoke_pending: Vec<String>) -> Result<PathBuf> {
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<Option<String>> {
Ok(self.load_config()?.2.access_token)
}

/// # Errors
/// Returns an error if the saved config cannot be loaded.
pub fn resolve_credentials(&self) -> Result<ResolvedCredentials> {
Expand Down Expand Up @@ -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(\"<redacted>\")"));
assert!(out.contains("revoke_pending: 1"), "{out}");
assert!(!out.contains("PENDINGSECRET"), "{out}");
assert!(out.contains("AB1234"));
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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"));
Expand Down
57 changes: 18 additions & 39 deletions src/commands/auth.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -27,52 +27,31 @@ pub async fn handle(rt: &Runtime, command: AuthCommands) -> Result<Output> {
}

async fn logout(rt: &Runtime) -> Result<Output> {
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()]);
}
},
))
}
Expand Down
Loading
Loading