From 54d4f2ec57545040b0d982baf33b73139e80b834 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Tue, 11 Jun 2024 22:20:49 +0800 Subject: [PATCH] fix: Cleanup temporary file after feeding auth data Related: #366 --- apps/gpclient/src/launch_gui.rs | 7 +++++- crates/gpapi/src/auth.rs | 1 + .../src/process/browser_authenticator.rs | 25 +++++++++++-------- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/apps/gpclient/src/launch_gui.rs b/apps/gpclient/src/launch_gui.rs index 7c0bcf1..4104d35 100644 --- a/apps/gpclient/src/launch_gui.rs +++ b/apps/gpclient/src/launch_gui.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, fs, path::PathBuf}; +use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf}; use clap::Args; use directories::ProjectDirs; @@ -82,6 +82,11 @@ impl<'a> LaunchGuiHandler<'a> { async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> { let _ = tokio::join!(feed_auth_data_gui(auth_data), feed_auth_data_cli(auth_data)); + + // Cleanup the temporary file + let html_file = temp_dir().join("gpauth.html"); + let _ = std::fs::remove_file(html_file); + Ok(()) } diff --git a/crates/gpapi/src/auth.rs b/crates/gpapi/src/auth.rs index cfaf816..d77e1eb 100644 --- a/crates/gpapi/src/auth.rs +++ b/crates/gpapi/src/auth.rs @@ -70,6 +70,7 @@ impl SamlAuthData { let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data).map_err(|e| { warn!("Failed to parse token auth data: {}", e); + warn!("Auth data: {}", auth_data); AuthDataParseError::Invalid })?; diff --git a/crates/gpapi/src/process/browser_authenticator.rs b/crates/gpapi/src/process/browser_authenticator.rs index ad5fb53..c62e788 100644 --- a/crates/gpapi/src/process/browser_authenticator.rs +++ b/crates/gpapi/src/process/browser_authenticator.rs @@ -1,4 +1,7 @@ -use std::{env::temp_dir, io::Write}; +use std::{env::temp_dir, fs, io::Write, os::unix::fs::PermissionsExt}; + +use anyhow::bail; +use log::warn; pub struct BrowserAuthenticator<'a> { auth_request: &'a str, @@ -14,8 +17,18 @@ impl BrowserAuthenticator<'_> { open::that_detached(self.auth_request)?; } else { let html_file = temp_dir().join("gpauth.html"); - let mut file = std::fs::File::create(&html_file)?; + // Remove the file and error if permission denied + if let Err(err) = fs::remove_file(&html_file) { + if err.kind() != std::io::ErrorKind::NotFound { + warn!("Failed to remove the temporary file: {}", err); + bail!("Please remove the file manually: {:?}", html_file); + } + } + + let mut file = fs::File::create(&html_file)?; + + file.set_permissions(fs::Permissions::from_mode(0o600))?; file.write_all(self.auth_request.as_bytes())?; open::that_detached(html_file)?; @@ -24,11 +37,3 @@ impl BrowserAuthenticator<'_> { Ok(()) } } - -impl Drop for BrowserAuthenticator<'_> { - fn drop(&mut self) { - // Cleanup the temporary file - let html_file = temp_dir().join("gpauth.html"); - let _ = std::fs::remove_file(html_file); - } -}