From a68b804d707ae50ddf8529f3591d70894988584e Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Tue, 7 Oct 2025 15:23:01 -0700 Subject: [PATCH 1/2] fix: handle corrupted VSCode auth cache with automatic cleanup and recovery --- extensions/vscode/src/stubs/SecretStorage.ts | 89 ++++++++++++++----- .../vscode/src/stubs/WorkOsAuthProvider.ts | 18 ++-- gui/src/context/Auth.tsx | 36 ++++---- 3 files changed, 93 insertions(+), 50 deletions(-) diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 202713cbd..029ad1e5b 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -59,31 +59,50 @@ export class SecretStorage { } async decrypt(filePath: string): Promise { - const key = await this.getOrCreateEncryptionKey(); - const data = fs.readFileSync(filePath); + try { + const key = await this.getOrCreateEncryptionKey(); + const data = fs.readFileSync(filePath); - const salt = data.subarray(0, this.saltLength); - const iv = data.subarray(this.saltLength, this.saltLength + this.ivLength); - const tag = data.subarray( - this.saltLength + this.ivLength, - this.saltLength + this.ivLength + this.tagLength, - ); - const encrypted = data.subarray( - this.saltLength + this.ivLength + this.tagLength, - ); + // Validate minimum data size to detect corruption early + const minSize = this.saltLength + this.ivLength + this.tagLength; + if (data.length < minSize) { + throw new Error( + `Corrupted cache file: insufficient data (${data.length} bytes, expected at least ${minSize})`, + ); + } - const decipher: crypto.DecipherGCM = crypto.createDecipheriv( - this.algorithm, - key, - iv, - ) as crypto.DecipherGCM; - decipher.setAuthTag(tag); + const salt = data.subarray(0, this.saltLength); + const iv = data.subarray( + this.saltLength, + this.saltLength + this.ivLength, + ); + const tag = data.subarray( + this.saltLength + this.ivLength, + this.saltLength + this.ivLength + this.tagLength, + ); + const encrypted = data.subarray( + this.saltLength + this.ivLength + this.tagLength, + ); - const decrypted = Buffer.concat([ - decipher.update(encrypted), - decipher.final(), - ]); - return decrypted.toString("utf8"); + const decipher: crypto.DecipherGCM = crypto.createDecipheriv( + this.algorithm, + key, + iv, + ) as crypto.DecipherGCM; + decipher.setAuthTag(tag); + + const decrypted = Buffer.concat([ + decipher.update(encrypted), + decipher.final(), + ]); + return decrypted.toString("utf8"); + } catch (error: any) { + // Log the error with context for debugging + console.error(`Failed to decrypt cache file ${filePath}:`, error.message); + throw new Error( + `Cache decryption failed: ${error.message}. The cache file may be corrupted.`, + ); + } } private keyToFilepath(key: string): string { @@ -100,8 +119,30 @@ export class SecretStorage { async get(key: string): Promise { const filePath = this.keyToFilepath(key); if (fs.existsSync(filePath)) { - const value = await this.decrypt(filePath); - return value; + try { + const value = await this.decrypt(filePath); + return value; + } catch (error: any) { + // Corrupted cache file - delete it and return undefined + // This allows the auth flow to continue with a fresh start + console.error( + `Corrupted cache file detected for key "${key}". Deleting file and returning undefined.`, + error.message, + ); + + try { + fs.unlinkSync(filePath); + console.log(`Successfully deleted corrupted cache file: ${filePath}`); + } catch (deleteError: any) { + console.error( + `Failed to delete corrupted cache file ${filePath}:`, + deleteError.message, + ); + } + + // Return undefined to signal missing data (same as if file didn't exist) + return undefined; + } } return undefined; } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index f0af9770d..99d697d65 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -161,22 +161,22 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { scopes?: string[], ): Promise { // await this.hasAttemptedRefresh; - const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); - if (!data) { - return []; - } - try { + const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); + if (!data) { + return []; + } + const value = JSON.parse(data) as ContinueAuthenticationSession[]; return value; } catch (e: any) { - // Capture session file parsing errors to Sentry + // Capture session decrypt and parsing errors to Sentry Logger.error(e, { - context: "workOS_sessions_json_parse", - dataLength: data.length, + context: "workOS_sessions_retrieval", + errorMessage: e.message, }); - console.warn(`Error parsing sessions.json: ${e}`); + console.warn(`Error retrieving or parsing sessions: ${e.message}`); return []; } } diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 12eebae1c..ee262d782 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -50,25 +50,27 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); - const login: AuthContextType["login"] = (useOnboarding: boolean) => { - return new Promise(async (resolve) => { - await ideMessenger - .request("getControlPlaneSessionInfo", { - silent: false, - useOnboarding, - }) - .then((result) => { - if (result.status === "error") { - resolve(false); - return; - } + const login: AuthContextType["login"] = async (useOnboarding: boolean) => { + try { + const result = await ideMessenger.request("getControlPlaneSessionInfo", { + silent: false, + useOnboarding, + }); - const session = result.content; - setSession(session); + if (result.status === "error") { + console.error("Login failed:", result.error); + return false; + } - resolve(true); - }); - }); + const session = result.content; + setSession(session); + + return true; + } catch (error: any) { + console.error("Login request failed:", error); + // Let the error propagate so the caller can handle it + throw error; + } }; const logout = () => { From a58149c6d62faf08ece2d234401e8e6c8fb977c8 Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Wed, 8 Oct 2025 15:26:40 -0700 Subject: [PATCH 2/2] move corrupted cache cleanup from SecretStorage to WorkOsAuthProvider --- extensions/vscode/src/stubs/SecretStorage.ts | 103 +++++++----------- .../vscode/src/stubs/WorkOsAuthProvider.ts | 12 ++ 2 files changed, 51 insertions(+), 64 deletions(-) diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 029ad1e5b..12cc98c35 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -59,50 +59,39 @@ export class SecretStorage { } async decrypt(filePath: string): Promise { - try { - const key = await this.getOrCreateEncryptionKey(); - const data = fs.readFileSync(filePath); + const key = await this.getOrCreateEncryptionKey(); + const data = fs.readFileSync(filePath); - // Validate minimum data size to detect corruption early - const minSize = this.saltLength + this.ivLength + this.tagLength; - if (data.length < minSize) { - throw new Error( - `Corrupted cache file: insufficient data (${data.length} bytes, expected at least ${minSize})`, - ); - } - - const salt = data.subarray(0, this.saltLength); - const iv = data.subarray( - this.saltLength, - this.saltLength + this.ivLength, - ); - const tag = data.subarray( - this.saltLength + this.ivLength, - this.saltLength + this.ivLength + this.tagLength, - ); - const encrypted = data.subarray( - this.saltLength + this.ivLength + this.tagLength, - ); - - const decipher: crypto.DecipherGCM = crypto.createDecipheriv( - this.algorithm, - key, - iv, - ) as crypto.DecipherGCM; - decipher.setAuthTag(tag); - - const decrypted = Buffer.concat([ - decipher.update(encrypted), - decipher.final(), - ]); - return decrypted.toString("utf8"); - } catch (error: any) { - // Log the error with context for debugging - console.error(`Failed to decrypt cache file ${filePath}:`, error.message); + // Validate minimum data size to detect corruption early + const minSize = this.saltLength + this.ivLength + this.tagLength; + if (data.length < minSize) { throw new Error( - `Cache decryption failed: ${error.message}. The cache file may be corrupted.`, + `Corrupted cache file: insufficient data (${data.length} bytes, expected at least ${minSize})`, ); } + + const salt = data.subarray(0, this.saltLength); + const iv = data.subarray(this.saltLength, this.saltLength + this.ivLength); + const tag = data.subarray( + this.saltLength + this.ivLength, + this.saltLength + this.ivLength + this.tagLength, + ); + const encrypted = data.subarray( + this.saltLength + this.ivLength + this.tagLength, + ); + + const decipher: crypto.DecipherGCM = crypto.createDecipheriv( + this.algorithm, + key, + iv, + ) as crypto.DecipherGCM; + decipher.setAuthTag(tag); + + const decrypted = Buffer.concat([ + decipher.update(encrypted), + decipher.final(), + ]); + return decrypted.toString("utf8"); } private keyToFilepath(key: string): string { @@ -119,31 +108,17 @@ export class SecretStorage { async get(key: string): Promise { const filePath = this.keyToFilepath(key); if (fs.existsSync(filePath)) { - try { - const value = await this.decrypt(filePath); - return value; - } catch (error: any) { - // Corrupted cache file - delete it and return undefined - // This allows the auth flow to continue with a fresh start - console.error( - `Corrupted cache file detected for key "${key}". Deleting file and returning undefined.`, - error.message, - ); - - try { - fs.unlinkSync(filePath); - console.log(`Successfully deleted corrupted cache file: ${filePath}`); - } catch (deleteError: any) { - console.error( - `Failed to delete corrupted cache file ${filePath}:`, - deleteError.message, - ); - } - - // Return undefined to signal missing data (same as if file didn't exist) - return undefined; - } + const value = await this.decrypt(filePath); + return value; } return undefined; } + + async delete(key: string): Promise { + const filePath = this.keyToFilepath(key); + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + console.log(`Successfully deleted cache file: ${filePath}`); + } + } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 99d697d65..1c0e60bba 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -177,6 +177,18 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { }); console.warn(`Error retrieving or parsing sessions: ${e.message}`); + + // Delete the corrupted cache file to allow fresh start on next attempt + // This handles cases where decryption succeeded but JSON parsing failed + try { + await this.secretStorage.delete(SESSIONS_SECRET_KEY); + } catch (deleteError: any) { + console.error( + `Failed to delete corrupted sessions cache:`, + deleteError.message, + ); + } + return []; } }