Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop-app): release auth owner during same-team requests (R12-M5)

Josuéd8d2a3dea2c8
diff --git a/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts b/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts
index 90915a09b..fea3e65ab 100644
--- a/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts
+++ b/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts
@@ -8,6 +8,101 @@ import {
afterEach(cleanupNativeCommitTestHarness)
describe('AppService deliberate team transition ownership', () => {
+ it('does not let REST discovery block logout or overwrite a later session revision', async () => {
+ const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()
+ await runtimeConfig.saveDesktopRuntimeConfig({
+ externalRestApiBaseUrl: restA,
+ rpcProxyBaseUrl: '',
+ appName: 'Environment A',
+ })
+ const discovery = deferred<{
+ externalRestApiBaseUrl: string
+ rpcProxyBaseUrl: string
+ appName: string
+ }>()
+ const discoveryStarted = deferred<void>()
+ const app = service as unknown as {
+ sessionToken: string | null
+ me: { id: string; email: string; name: string; picture: null; teamId: string; role: string }
+ authClient: unknown
+ rpcClient: unknown
+ suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void>
+ getDependenciesHealth(): Promise<unknown>
+ }
+ app.sessionToken = 'session-a'
+ app.me = {
+ id: 'user-a',
+ email: '[email protected]',
+ name: 'User A',
+ picture: null,
+ teamId: 'team-a',
+ role: 'member',
+ }
+ app.authClient = {
+ getDesktopEnvironment: vi.fn(() => {
+ discoveryStarted.resolve()
+ return discovery.promise
+ }),
+ health: vi.fn().mockResolvedValue({ status: 'ok' }),
+ }
+ app.rpcClient = { health: vi.fn().mockResolvedValue({ status: 'ok' }) }
+ app.suspendDesktopGfsUploadsForAuthBoundary = vi.fn().mockResolvedValue(undefined)
+
+ const healthRequest = app.getDependenciesHealth()
+ await discoveryStarted.promise
+ await expect(service.logout()).resolves.toBeTypeOf('number')
+ discovery.resolve({
+ externalRestApiBaseUrl: restA,
+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',
+ appName: 'Environment A',
+ })
+ await healthRequest
+
+ expect(runtimeConfig.getDesktopRuntimeConfigState().currentConfig.rpcProxyBaseUrl).toBe('')
+ })
+
+ it('lets logout commit while a same-team request is pending and rejects its stale result', async () => {
+ const { service } = await createNativeCommitTestHarness()
+ const request = deferred<string>()
+ const requestStarted = deferred<void>()
+ const app = service as unknown as {
+ sessionToken: string | null
+ me: {
+ id: string
+ email: string
+ name: string
+ picture: null
+ teamId: string
+ teamName: string
+ role: string
+ } | null
+ runWithTeamContext<T>(teamId: string, operation: (token: string) => Promise<T>): Promise<T>
+ suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void>
+ }
+ app.sessionToken = 'session-a'
+ app.me = {
+ id: 'user-a',
+ email: '[email protected]',
+ name: 'User A',
+ picture: null,
+ teamId: 'team-a',
+ teamName: 'Team A',
+ role: 'member',
+ }
+ app.suspendDesktopGfsUploadsForAuthBoundary = vi.fn().mockResolvedValue(undefined)
+ const operation = app.runWithTeamContext('team-a', async () => {
+ requestStarted.resolve()
+ return request.promise
+ })
+ await requestStarted.promise
+
+ await expect(service.logout()).resolves.toBeTypeOf('number')
+ request.resolve('old-session-result')
+
+ await expect(operation).rejects.toThrow(/stale_(auth_epoch|session_generation)/)
+ expect(app.sessionToken).toBeNull()
+ })
+
it('finishes GFS activation before a queued workflow read borrows another team', async () => {
const { service, restA } = await createNativeCommitTestHarness()
const teamBResponse = deferred<{
diff --git a/desktop-app/src/__tests__/rpcTokenManager.test.ts b/desktop-app/src/__tests__/rpcTokenManager.test.ts
new file mode 100644
index 000000000..1ec7fa6e8
--- /dev/null
+++ b/desktop-app/src/__tests__/rpcTokenManager.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { AuthClient } from '../authClient.js'
+import { RpcTokenManager } from '../rpcTokenManager.js'
+import type { RpcTokenResult } from '../types.js'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(done => {
+ resolve = done
+ })
+ return { promise, resolve }
+}
+
+const issuedToken = (token: string): RpcTokenResult => ({
+ token,
+ accessScope: 'team',
+ teamId: 'team-a',
+ scopes: ['host:activity:read'],
+ hostRefs: ['chatllm'],
+ expiresInSeconds: 300,
+})
+
+describe('RpcTokenManager', () => {
+ it('does not cache a token whose request completed after the cache was cleared', async () => {
+ const pending = deferred<RpcTokenResult>()
+ const issueRpcToken = vi
+ .fn()
+ .mockReturnValueOnce(pending.promise)
+ .mockResolvedValueOnce(issuedToken('new-session-token'))
+ const manager = new RpcTokenManager({ issueRpcToken } as unknown as AuthClient)
+
+ const oldSessionRequest = manager.getOrIssue('old-session', ['host:activity:read'], ['chatllm'])
+ manager.clear()
+ pending.resolve(issuedToken('old-session-token'))
+ await expect(oldSessionRequest).resolves.toMatchObject({ token: 'old-session-token' })
+
+ expect(manager.getMetadata()).toEqual({ expiresAtMs: null, scopes: [], hostRefs: [] })
+ await expect(
+ manager.getOrIssue('new-session', ['host:activity:read'], ['chatllm'])
+ ).resolves.toMatchObject({ token: 'new-session-token' })
+ expect(issueRpcToken).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 73292ef0e..958fd7bfc 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -1255,7 +1255,7 @@ export class AppService {
): Promise<T> {
const targetTeamId = String(teamId || '').trim()
const run = () => this.runWithTeamContextInTeamQueue(targetTeamId, operation)
- return targetTeamId ? this.withNativeAuthEnvironmentCommit(run) : run()
+ return run()
}
private async runWithTeamContextInTeamQueue<T>(
@@ -1280,82 +1280,110 @@ export class AppService {
await previousQueue.catch(() => undefined)
- let operationError: unknown
try {
- const originalToken = this.requireSessionToken()
- const originalTeamId = await this.getCurrentSessionTeamId(originalToken)
- let activeToken = originalToken
- const shouldSwitch = originalTeamId !== targetTeamId
- const shouldRestore = Boolean(originalTeamId && shouldSwitch)
- let restoredOriginalTeam = false
- const releaseTransientHop = shouldSwitch ? this.enterGfsTransientTeamHop() : undefined
- if (shouldRestore) this.chatStoreHomeTeamId = originalTeamId
+ const context = await this.withNativeAuthEnvironmentCommit(async () => {
+ const sessionToken = this.requireSessionToken()
+ const teamId = await this.getCurrentSessionTeamId(sessionToken)
+ return {
+ sessionToken,
+ teamId,
+ sessionGeneration: this.sessionGeneration,
+ environmentBinding: this.captureAuthEnvironmentBinding(),
+ }
+ })
- try {
- if (shouldSwitch) {
- activeToken = await this.switchSessionToTeam(targetTeamId, originalToken, {
- commitOwnerHeld: true,
- })
+ const assertContextIsCurrent = () => {
+ this.assertSessionGeneration(context.sessionGeneration)
+ if (this.sessionToken !== context.sessionToken || this.me?.teamId !== context.teamId) {
+ throw new Error('stale_auth_epoch: authenticated team scope changed during operation')
}
+ this.assertAuthEnvironmentBinding(context.environmentBinding)
+ }
+
+ if (context.teamId === targetTeamId) {
+ const { request } = await this.withNativeAuthEnvironmentCommit(async () => {
+ assertContextIsCurrent()
+ return { request: operation(context.sessionToken) }
+ })
+ const result = await request
+ return this.withNativeAuthEnvironmentCommit(async () => {
+ assertContextIsCurrent()
+ return result
+ })
+ }
+
+ return await this.withNativeAuthEnvironmentCommit(async () => {
+ assertContextIsCurrent()
+ const originalToken = context.sessionToken
+ const originalTeamId = context.teamId
+ const shouldRestore = Boolean(originalTeamId)
+ let restoredOriginalTeam = false
+ let operationError: unknown
+ const releaseTransientHop = this.enterGfsTransientTeamHop()
+ if (shouldRestore) this.chatStoreHomeTeamId = originalTeamId
try {
- return await operation(activeToken)
- } catch (error) {
- operationError = error
- throw error
- } finally {
- if (shouldRestore) {
- try {
- await this.switchSessionToTeam(originalTeamId, this.requireSessionToken(), {
- commitOwnerHeld: true,
- })
- restoredOriginalTeam = true
- } catch (restoreError) {
- if (!operationError) throw restoreError
- console.warn(
- '[AppService] Failed to restore team context after operation:',
- restoreError
- )
+ const activeToken = await this.switchSessionToTeam(targetTeamId, originalToken, {
+ commitOwnerHeld: true,
+ })
+
+ try {
+ return await operation(activeToken)
+ } catch (error) {
+ operationError = error
+ throw error
+ } finally {
+ if (shouldRestore) {
+ try {
+ await this.switchSessionToTeam(originalTeamId, this.requireSessionToken(), {
+ commitOwnerHeld: true,
+ })
+ restoredOriginalTeam = true
+ } catch (restoreError) {
+ if (!operationError) throw restoreError
+ console.warn(
+ '[AppService] Failed to restore team context after operation:',
+ restoreError
+ )
+ }
+ }
+ if (restoredOriginalTeam && this.sessionToken) {
+ this.updateEntityChangeSessionToken(this.sessionToken)
+ this.restartEntityChangeStreamForSessionReplacement()
+ } else if (
+ shouldRestore &&
+ this.sessionToken &&
+ this.me &&
+ this.me.teamId !== originalTeamId
+ ) {
+ // A failed restore leaves the hop team as the actual committed
+ // session. Rebind the stream to the token that remains active.
+ this.updateEntityChangeSessionToken(this.sessionToken)
+ this.restartEntityChangeStreamForSessionReplacement()
}
}
- if (restoredOriginalTeam && this.sessionToken) {
- this.updateEntityChangeSessionToken(this.sessionToken)
- this.restartEntityChangeStreamForSessionReplacement()
- } else if (
- shouldRestore &&
- this.sessionToken &&
- this.me &&
- this.me.teamId !== originalTeamId
- ) {
- // A failed restore leaves the hop team as the actual committed
- // session. Rebind now that the restore attempt is over; the stream
- // must not remain attached to the replaced pre-hop token.
- this.updateEntityChangeSessionToken(this.sessionToken)
- this.restartEntityChangeStreamForSessionReplacement()
- }
- }
- } finally {
- if (shouldRestore) {
- this.chatStoreHomeTeamId = null
- // A failed switch back leaves the session on the hop team while the
- // store is still bound to the pinned home team. Rebind so the store
- // scope and the delete-fence authority (both derived from
- // chatStoreTeamId) agree again. A rebind failure is logged and never
- // replaces the error of the operation or of the failed restore.
- const sessionUserId = this.me?.id
- if (sessionUserId && this.me?.teamId !== originalTeamId) {
- try {
- await this.bindCurrentChatStore(sessionUserId)
- } catch (rebindError) {
- console.error(
- '[AppService] Failed to rebind the chat store after a failed team restore:',
- rebindError
- )
+ } finally {
+ if (shouldRestore) {
+ this.chatStoreHomeTeamId = null
+ // A failed switch back leaves the session on the hop team while the
+ // store is still bound to the pinned home team. Rebind so the store
+ // scope and delete-fence authority agree again. A rebind failure is
+ // logged and never replaces the operation or restore error.
+ const sessionUserId = this.me?.id
+ if (sessionUserId && this.me?.teamId !== originalTeamId) {
+ try {
+ await this.bindCurrentChatStore(sessionUserId)
+ } catch (rebindError) {
+ console.error(
+ '[AppService] Failed to rebind the chat store after a failed team restore:',
+ rebindError
+ )
+ }
}
}
+ releaseTransientHop()
}
- releaseTransientHop?.()
- }
+ })
} finally {
releaseQueue()
}
@@ -1777,9 +1805,7 @@ export class AppService {
}
async getDependenciesHealth(): Promise<DependencyHealth> {
- await this.withNativeAuthEnvironmentCommit(() =>
- this.resolveRuntimeConfigIfNeeded().catch(() => undefined)
- )
+ await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)
const [externalHealth, rpcHealth] = await Promise.allSettled([
this.authClient.health(),
this.rpcClient.health(),
@@ -1966,7 +1992,7 @@ export class AppService {
}
async saveRuntimeConfig(next: DesktopRuntimeConfig) {
- return this.withNativeAuthEnvironmentCommit(async () => {
+ await this.withNativeAuthEnvironmentCommit(async () => {
const nextEnvKey = resolveEnvKey(next.externalRestApiBaseUrl, next.rpcProxyBaseUrl || '')
const sameUploadBoundary =
nextEnvKey === getActiveEnvKey() &&
@@ -1974,9 +2000,9 @@ export class AppService {
normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl)
if (sameUploadBoundary) await saveDesktopRuntimeConfig(next)
else await this.applyRuntimeEnvironmentChange(() => saveDesktopRuntimeConfig(next))
- await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)
- return getDesktopRuntimeConfigState()
})
+ await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)
+ return getDesktopRuntimeConfigState()
}
async deleteRuntimeConfig(optionId: string) {
@@ -2171,11 +2197,10 @@ export class AppService {
this.sessionGeneration += 1
return this.sessionGeneration
})
- await this.withNativeAuthEnvironmentCommit(async () => {
- if (this.sessionGeneration === committedGeneration) {
- await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)
- }
- })
+ const shouldResolve = await this.withNativeAuthEnvironmentCommit(
+ async () => this.sessionGeneration === committedGeneration
+ )
+ if (shouldResolve) await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)
return getDesktopRuntimeConfigState()
} catch (error) {
if (error instanceof ApiError && error.status === 404) {
@@ -2201,8 +2226,8 @@ export class AppService {
})
await this.withNativeAuthEnvironmentCommit(async () => {
this.assertSessionGeneration(loginGeneration)
- await this.resolveRuntimeConfigIfNeeded()
})
+ await this.resolveRuntimeConfigIfNeeded()
this.assertSessionGeneration(loginGeneration)
const normalizedEmail = email.trim().toLowerCase()
return await this.completePasswordLogin(normalizedEmail, password, loginGeneration)
@@ -2307,20 +2332,36 @@ export class AppService {
}
private async resolveRuntimeConfigIfNeeded(): Promise<void> {
- hydrateDesktopRuntimeConfig()
- if (!isDesktopRuntimeConfigured()) return
- if (config.rpcProxyBaseUrl?.trim()) return
- const externalRestApiBaseUrl = canonicalizeDesktopRestEndpoint(config.externalRestApiBaseUrl)
+ const request = await this.withNativeAuthEnvironmentCommit(async () => {
+ hydrateDesktopRuntimeConfig()
+ if (!isDesktopRuntimeConfigured() || config.rpcProxyBaseUrl?.trim()) return null
+ return {
+ externalRestApiBaseUrl: canonicalizeDesktopRestEndpoint(config.externalRestApiBaseUrl),
+ appName: config.appName,
+ sessionGeneration: this.sessionGeneration,
+ environmentBinding: this.captureAuthEnvironmentBinding(),
+ }
+ })
+ if (!request) return
+
const discovered = await this.authClient.getDesktopEnvironment()
- if (!sameDesktopRestEndpoint(discovered.externalRestApiBaseUrl, externalRestApiBaseUrl)) {
+ if (
+ !sameDesktopRestEndpoint(discovered.externalRestApiBaseUrl, request.externalRestApiBaseUrl)
+ ) {
throw new Error('Desktop environment discovery returned a different REST endpoint')
}
- await saveDesktopRuntimeConfig({
- // Discovery is scoped to the configured REST endpoint; it may provide
- // RPC details but must never switch or overwrite another REST profile.
- externalRestApiBaseUrl,
- rpcProxyBaseUrl: discovered.rpcProxyBaseUrl,
- appName: discovered.appName || config.appName,
+ await this.withNativeAuthEnvironmentCommit(async () => {
+ this.assertSessionGeneration(request.sessionGeneration)
+ this.assertAuthEnvironmentBinding(request.environmentBinding)
+ hydrateDesktopRuntimeConfig()
+ if (!isDesktopRuntimeConfigured() || config.rpcProxyBaseUrl?.trim()) return
+ await saveDesktopRuntimeConfig({
+ // Discovery is scoped to the configured REST endpoint; it may provide
+ // RPC details but must never switch or overwrite another REST profile.
+ externalRestApiBaseUrl: request.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: discovered.rpcProxyBaseUrl,
+ appName: discovered.appName || request.appName,
+ })
})
}
diff --git a/desktop-app/src/rpcTokenManager.ts b/desktop-app/src/rpcTokenManager.ts
index 421c2a29d..4c3550847 100644
--- a/desktop-app/src/rpcTokenManager.ts
+++ b/desktop-app/src/rpcTokenManager.ts
@@ -12,10 +12,12 @@ type RpcCache = {
export class RpcTokenManager {
private cache: RpcCache | null = null
+ private cacheGeneration = 0
constructor(private readonly authClient: AuthClient) {}
clear(): void {
+ this.cacheGeneration += 1
this.cache = null
}
@@ -57,18 +59,21 @@ export class RpcTokenManager {
}
}
+ const generation = this.cacheGeneration
const issued = await this.authClient.issueRpcToken(
sessionToken,
requiredScopes,
requestedHostRefs
)
- this.cache = {
- token: issued.token,
- accessScope: issued.accessScope,
- teamId: issued.teamId,
- scopes: issued.scopes,
- hostRefs: issued.hostRefs,
- expiresAtMs: Date.now() + issued.expiresInSeconds * 1000,
+ if (generation === this.cacheGeneration) {
+ this.cache = {
+ token: issued.token,
+ accessScope: issued.accessScope,
+ teamId: issued.teamId,
+ scopes: issued.scopes,
+ hostRefs: issued.hostRefs,
+ expiresAtMs: Date.now() + issued.expiresInSeconds * 1000,
+ }
}
return issued
}