refactor: use different secret keys for each auth provider (#6630)

* refactor: user different secret keys for each auth provider

* Add changeset

* refactor

* refactor: use a constant for the secret key

* refactor: improve fallback handling
This commit is contained in:
Tomás Barreiro authored and GitHub committed 2025-10-08 12:06:38 -07:00
1 parent 8be46f9cfe
commit 0ea263c1b1
12 files changed
+73 -32

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Use different keys for separate auth providers
+1
View File
@@ -176,6 +176,7 @@ export interface Settings {
export interface Secrets {
apiKey: string | undefined
clineAccountId: string | undefined
["cline:clineAccountId"]: string | undefined // Auth_Provider:AccountId
openRouterApiKey: string | undefined
awsAccessKey: string | undefined
awsSecretKey: string | undefined
+5 -1
View File
@@ -1,6 +1,7 @@
import { ANTHROPIC_MIN_THINKING_BUDGET, ApiProvider, fireworksDefaultModelId, type OcaModelInfo } from "@shared/api"
import { ExtensionContext } from "vscode"
import { Controller } from "@/core/controller"
import { ClineAuthProvider } from "@/services/auth/providers/ClineAuthProvider"
import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@/shared/AutoApprovalSettings"
import { DEFAULT_BROWSER_SETTINGS } from "@/shared/BrowserSettings"
import { ClineRulesToggles } from "@/shared/cline-rules"
@@ -14,6 +15,7 @@ export async function readSecretsFromDisk(context: ExtensionContext): Promise<Se
const [
apiKey,
openRouterApiKey,
firebaseClineAccountId,
clineAccountId,
awsAccessKey,
awsSecretKey,
@@ -53,6 +55,7 @@ export async function readSecretsFromDisk(context: ExtensionContext): Promise<Se
context.secrets.get("apiKey") as Promise<Secrets["apiKey"]>,
context.secrets.get("openRouterApiKey") as Promise<Secrets["openRouterApiKey"]>,
context.secrets.get("clineAccountId") as Promise<Secrets["clineAccountId"]>,
context.secrets.get(ClineAuthProvider.secretKeyId) as Promise<Secrets["cline:clineAccountId"]>,
context.secrets.get("awsAccessKey") as Promise<Secrets["awsAccessKey"]>,
context.secrets.get("awsSecretKey") as Promise<Secrets["awsSecretKey"]>,
context.secrets.get("awsSessionToken") as Promise<Secrets["awsSessionToken"]>,
@@ -93,7 +96,8 @@ export async function readSecretsFromDisk(context: ExtensionContext): Promise<Se
authNonce,
apiKey,
openRouterApiKey,
clineAccountId,
clineAccountId: firebaseClineAccountId,
[ClineAuthProvider.secretKeyId]: clineAccountId,
huggingFaceApiKey,
huaweiCloudMaasApiKey,
basetenApiKey,
+3 -2
View File
@@ -34,6 +34,7 @@ import { VscodeDiffViewProvider } from "./hosts/vscode/VscodeDiffViewProvider"
import { VscodeWebviewProvider } from "./hosts/vscode/VscodeWebviewProvider"
import { ExtensionRegistryInfo } from "./registry"
import { AuthService } from "./services/auth/AuthService"
import { ClineAuthProvider } from "./services/auth/providers/ClineAuthProvider"
import { LogoutReason } from "./services/auth/types"
import { telemetryService } from "./services/telemetry"
import { SharedUriHandler } from "./services/uri/SharedUriHandler"
@@ -375,9 +376,9 @@ export async function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
context.secrets.onDidChange(async (event) => {
if (event.key === "clineAccountId") {
if (event.key === "clineAccountId" || event.key === ClineAuthProvider.secretKeyId) {
// Check if the secret was removed (logout) or added/updated (login)
const secretValue = await context.secrets.get("clineAccountId")
const secretValue = await context.secrets.get(event.key)
const activeWebview = WebviewProvider.getVisibleInstance()
const controller = activeWebview?.controller
+43 -15
View File
@@ -32,6 +32,7 @@ export interface ClineAuthInfo {
*/
expiresAt?: number
userInfo: ClineAccountUserInfo
provider: string
}
export interface ClineAccountUserInfo {
@@ -63,6 +64,7 @@ export class AuthService {
protected _authenticated: boolean = false
protected _clineAuthInfo: ClineAuthInfo | null = null
protected _provider: IAuthProvider | null = null
protected _fallbackProvider: IAuthProvider | null = null
protected _activeAuthStatusUpdateHandlers = new Set<StreamingResponseHandler<AuthState>>()
protected _handlerToController = new Map<StreamingResponseHandler<AuthState>, Controller>()
protected _controller: Controller
@@ -108,35 +110,41 @@ export class AuthService {
this._controller = controller
}
get authProvider(): IAuthProvider | null {
return this._provider
}
set authProvider(providerName: string) {
this._setProvider(providerName)
}
/**
* Returns the current authentication token with the appropriate prefix.
* Refreshing it if necessary.
*/
async getAuthToken(): Promise<string | null> {
if (!this._provider) {
throw new Error("Auth provider is not set")
}
const token = await this.internalGetAuthToken(this._provider)
if (!token && this._fallbackProvider) {
return this.internalGetAuthToken(this._fallbackProvider)
}
return token
}
private async internalGetAuthToken(provider: IAuthProvider): Promise<string | null> {
try {
let clineAccountAuthToken = this._clineAuthInfo?.idToken
if (!this._clineAuthInfo || !clineAccountAuthToken) {
if (!this._clineAuthInfo || !clineAccountAuthToken || this._clineAuthInfo.provider !== provider.name) {
// Not authenticated
return null
}
// Check if token has expired
if (await this._provider?.shouldRefreshIdToken(clineAccountAuthToken, this._clineAuthInfo.expiresAt)) {
if (await provider.shouldRefreshIdToken(clineAccountAuthToken, this._clineAuthInfo.expiresAt)) {
console.log("Provider indicates token needs refresh")
const updatedAuthInfo = await this._provider?.retrieveClineAuthInfo(this._controller)
const updatedAuthInfo = await provider.retrieveClineAuthInfo(this._controller)
if (updatedAuthInfo) {
this._clineAuthInfo = updatedAuthInfo
this._authenticated = true
clineAccountAuthToken = updatedAuthInfo.idToken
} else {
} else if (this.shouldClearAuthInfo(provider)) {
this._clineAuthInfo = null
this._authenticated = false
telemetryService.captureAuthLoggedOut(this._provider?.name, LogoutReason.ERROR_RECOVERY)
@@ -145,7 +153,7 @@ export class AuthService {
}
// IMPORTANT: Prefix with 'workos:' so backend can route verification to WorkOS provider
const prefix = this._provider?.name === "cline" ? "workos:" : ""
const prefix = provider.name === "cline" ? "workos:" : ""
return clineAccountAuthToken ? `${prefix}${clineAccountAuthToken}` : null
} catch (error) {
console.error("Error getting auth token:", error)
@@ -153,12 +161,17 @@ export class AuthService {
}
}
private shouldClearAuthInfo(provider: IAuthProvider) {
return this._clineAuthInfo?.provider === provider.name
}
protected _setProvider(providerName: string): void {
// Only ClineAuthProvider is supported going forward
// Keeping the providerName param for forward compatibility/telemetrye
// Keeping the providerName param for forward compatibility/telemetry
switch (providerName) {
case "cline":
this._provider = new ClineAuthProvider(clineEnvConfig)
this._fallbackProvider = new FirebaseAuthProvider(clineEnvConfig)
break
case "firebase":
default:
@@ -254,6 +267,7 @@ export class AuthService {
*/
async clearAuthToken(): Promise<void> {
this._controller.stateManager.setSecret("clineAccountId", undefined)
this._controller.stateManager.setSecret(ClineAuthProvider.secretKeyId, undefined)
}
/**
@@ -266,7 +280,7 @@ export class AuthService {
}
try {
this._clineAuthInfo = await this._provider.retrieveClineAuthInfo(this._controller)
this._clineAuthInfo = await this.retrieveAuthInfo()
if (this._clineAuthInfo) {
this._authenticated = true
await this.sendAuthStatusUpdate()
@@ -285,6 +299,20 @@ export class AuthService {
}
}
private async retrieveAuthInfo(): Promise<ClineAuthInfo | null> {
if (!this._provider) {
throw new Error("Auth provider is not set")
}
const authInfo = await this._provider.retrieveClineAuthInfo(this._controller)
if (!authInfo && this._fallbackProvider) {
return this._fallbackProvider.retrieveClineAuthInfo(this._controller)
}
return authInfo
}
/**
* Subscribe to authStatusUpdate events
* @param controller The controller instance
+1
View File
@@ -97,6 +97,7 @@ export class AuthServiceMock extends AuthService {
appBaseUrl: clineEnvConfig.appBaseUrl,
subject: authData.userInfo.subject,
},
provider: this._provider?.name || "mock",
}
console.log(`Successfully authenticated with mock server as ${authData.userInfo.name} (${authData.userInfo.email})`)
@@ -95,7 +95,7 @@ export class ClineAuthProvider implements IAuthProvider {
async retrieveClineAuthInfo(controller: Controller): Promise<ClineAuthInfo | null> {
try {
// Get the stored auth data from secure storage
const storedAuthDataString = controller.stateManager.getSecretKey("clineAccountId")
const storedAuthDataString = controller.stateManager.getSecretKey(ClineAuthProvider.secretKeyId)
if (!storedAuthDataString) {
Logger.debug("No stored authentication data found")
@@ -108,13 +108,13 @@ export class ClineAuthProvider implements IAuthProvider {
storedAuthData = JSON.parse(storedAuthDataString)
} catch (e) {
console.error("Failed to parse stored auth data:", e)
controller.stateManager.setSecret("clineAccountId", undefined)
controller.stateManager.setSecret(ClineAuthProvider.secretKeyId, undefined)
return null
}
if (!storedAuthData.refreshToken || !storedAuthData?.idToken) {
console.error("No valid token found in stored authentication data")
controller.stateManager.setSecret("clineAccountId", undefined)
controller.stateManager.setSecret(ClineAuthProvider.secretKeyId, undefined)
return null
}
@@ -198,6 +198,7 @@ export class ClineAuthProvider implements IAuthProvider {
appBaseUrl: this._config.appBaseUrl,
subject: data.data.userInfo.subject || "",
},
provider: this.name,
}
} catch (error: any) {
throw error
@@ -300,9 +301,10 @@ export class ClineAuthProvider implements IAuthProvider {
organizations: [],
},
expiresAt: new Date(tokenData.expiresAt).getTime() / 1000, // "2025-09-17T04:32:24.842636548Z"
provider: this.name,
}
controller.stateManager.setSecret("clineAccountId", JSON.stringify(clineAuthInfo))
controller.stateManager.setSecret(ClineAuthProvider.secretKeyId, JSON.stringify(clineAuthInfo))
return clineAuthInfo
} catch (error) {
@@ -310,4 +312,6 @@ export class ClineAuthProvider implements IAuthProvider {
throw error
}
}
static secretKeyId = "cline:clineAccountId" as const // authProvider:clineAccountId
}
@@ -70,7 +70,7 @@ export class FirebaseAuthProvider implements IAuthProvider {
// Store user data
const userInfo: ClineAccountUserInfo = userResponse.data.data
return { idToken, userInfo }
return { idToken, userInfo, provider: this.name }
} catch (error) {
ErrorService.get().logException(error)
throw error
@@ -44,8 +44,8 @@ Patch releases (3.19.1 → 3.19.2) will not trigger new announcements.
const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => {
const minorVersion = version.split(".").slice(0, 2).join(".") // 2.0.0 -> 2.0
const { clineUser } = useClineAuth()
const { apiConfiguration, openRouterModels, setShowChatModelSelector, refreshOpenRouterModels } = useExtensionState()
const user = apiConfiguration?.clineAccountId ? clineUser : undefined
const { openRouterModels, setShowChatModelSelector, refreshOpenRouterModels } = useExtensionState()
const user = clineUser || undefined
const { handleFieldsChange } = useApiConfigurationHandlers()
const [didClickGrokCodeButton, setDidClickGrokCodeButton] = useState(false)
@@ -13,8 +13,8 @@ export const CURRENT_MODEL_BANNER_VERSION = 1
export const NewModelBanner: React.FC = () => {
const { clineUser } = useClineAuth()
const { apiConfiguration, openRouterModels, setShowChatModelSelector, refreshOpenRouterModels } = useExtensionState()
const user = apiConfiguration?.clineAccountId ? clineUser : undefined
const { openRouterModels, setShowChatModelSelector, refreshOpenRouterModels } = useExtensionState()
const user = clineUser || undefined
const { handleFieldsChange } = useApiConfigurationHandlers()
// Need to get latest model list in case user hits shortcut button to set model
@@ -6,9 +6,9 @@ import { AccountServiceClient } from "@/services/grpc-client"
export const ClineAccountInfoCard = () => {
const { clineUser } = useClineAuth()
const { apiConfiguration, navigateToAccount } = useExtensionState()
const { navigateToAccount } = useExtensionState()
const user = apiConfiguration?.clineAccountId ? clineUser : undefined
const user = clineUser || undefined
const handleLogin = () => {
AccountServiceClient.accountLoginClicked(EmptyRequest.create()).catch((err) =>
-3
View File
@@ -71,9 +71,6 @@ export function validateApiConfiguration(currentMode: Mode, apiConfiguration?: A
}
break
case "cline":
if (!apiConfiguration.clineAccountId) {
return "You must provide a valid API key or choose a different provider."
}
break
case "openai":
if (!apiConfiguration.openAiBaseUrl || !apiConfiguration.openAiApiKey || !openAiModelId) {