Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(mcp): invalidate stale OAuth dialog requests (#4531)
Luciene0c28bef3562
diff --git a/frontend/src/views/settings/components/McpServiceDialog.test.ts b/frontend/src/views/settings/components/McpServiceDialog.test.tsindex 1563a68d9..35bdf7ceb 100644--- a/frontend/src/views/settings/components/McpServiceDialog.test.ts+++ b/frontend/src/views/settings/components/McpServiceDialog.test.ts@@ -16,27 +16,48 @@ const script = compileScript(descriptor, { id: 'mcp-dialog-test' }).content.replace('return __returned__', '__expose(__returned__); return __returned__')const compiled = ts.transpileModule(script, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText-function fixture(generate: () => Promise<string> = async () => 'Query logs by module and time.', initialStep: 0 | 1 = 0) {+function fixture(generate: () => Promise<string> = async () => 'Query logs by module and time.', initialStep: 0 | 1 = 0, oauthApi: Record<string, unknown> = {}, authType = '') {const updates: Array<{ id: string; data: Record<string, unknown> }> = []const warnings: string[] = []- const props = reactive({ visible: true, service: { id: 'one', name: 'Logs', description: 'Legacy usage', transport_type: 'sse', url: 'https://example.com/mcp' }, mode: 'edit', initialStep })+ const successes: string[] = []+ const errors: string[] = []+ const timers = new Map<number, () => Promise<void>>()+ const popups: Array<{ closed: boolean; close: () => void }> = []+ let nextTimer = 0+ const props = reactive({ visible: true, service: { id: 'one', name: 'Logs', description: 'Legacy usage', transport_type: 'sse', url: 'https://example.com/mcp', auth_config: { auth_type: authType } }, mode: 'edit', initialStep })const exports: any = {}runInNewContext(compiled, {exports,require(name: string) {if (name === 'vue') return require('vue')if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key, locale: ref('zh-CN') }) }- if (name === 'tdesign-vue-next') return { MessagePlugin: { warning: (text: string) => warnings.push(text), success() {}, error() {} } }+ if (name === 'tdesign-vue-next') return { MessagePlugin: { warning: (text: string) => warnings.push(text), success: (text: string) => successes.push(text), error: (text: string) => errors.push(text) } }if (name === '@/api/mcp-service') return {+ MCP_OAUTH_CALLBACK_PATH: '/callback',+ getMCPOAuthAuthorizationStatus: async () => ({ authorized: false, state: 'reauth_required' }),+ getMCPOAuthAuthorizeURL: async () => ({ authorizationUrl: 'https://auth.example/consent', authorizationAttempt: 'attempt' }),+ getMCPOAuthStatus: async () => false,+ revokeMCPOAuthToken: async () => {},generateMCPUsageInstructions: generate,updateMCPService: async (id: string, data: Record<string, unknown>) => {updates.push({ id, data })return { ...props.service, ...data }},+ ...oauthApi,}return { default: {} }},URL, console,+ window: {+ location: { origin: 'https://weknora.example' },+ setInterval: (callback: () => Promise<void>) => { timers.set(++nextTimer, callback); return nextTimer },+ clearInterval: (id: number) => timers.delete(id),+ open: () => {+ const popup = { closed: false, close() { this.closed = true } }+ popups.push(popup)+ return popup+ },+ },})const component = exports.defaultcomponent.render = () => null@@ -48,7 +69,26 @@ function fixture(generate: () => Promise<string> = async () => 'Query logs by moconst instance = ref<any>()const app = renderer.createApp({ render: () => h(component, { ...props, ref: instance }) })app.mount({})- return { vm: instance.value, props, updates, warnings, close: () => app.unmount() }+ let mounted = true+ return { vm: instance.value, props, updates, warnings, successes, errors, timers, popups, close: () => { if (mounted) { mounted = false; app.unmount() } } }+}++function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason: Error) => void+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail })+ return { promise, resolve, reject }+}++async function oauthFixture(api: Record<string, unknown> = {}) {+ const f = fixture(undefined, 0, api, 'oauth')+ await nextTick()+ return f+}++function poll(f: Awaited<ReturnType<typeof oauthFixture>>) {+ assert.equal(f.timers.size, 1)+ return Array.from(f.timers.values())[0]!()}test('tool shortcut opens the saved service directly without resaving its connection', () => {@@ -175,3 +215,190 @@ test('API key payload never carries OAuth client fields', () => {assert.equal('client_secret' in body.auth_config, false)} finally { f.close() }})++test('closing and reopening another service discards an in-flight OAuth poll', async () => {+ const status = deferred<boolean>()+ const calls: string[] = []+ const f = await oauthFixture({ getMCPOAuthStatus: (id: string) => { calls.push(id); return status.promise } })+ try {+ await f.vm.startAuthorize('one')+ const pending = poll(f)+ f.props.visible = false+ await nextTick()+ assert.equal(f.timers.size, 0)+ assert.equal(f.vm.oauthAuthorizing, false)+ f.props.service = { ...f.props.service, id: 'two' }+ f.props.visible = true+ await nextTick()+ status.resolve(true)+ await pending+ assert.deepEqual(calls, ['one'])+ assert.equal(f.vm.currentService.id, 'two')+ assert.equal(f.vm.oauthAuthorized, false)+ assert.equal(f.vm.oauthTokenState, 'reauth_required')+ assert.deepEqual(f.successes, [])+ assert.equal(f.popups[0]?.closed, false)+ } finally { f.close() }+})++test('saving and rebinding the same service preserves its active OAuth attempt', async () => {+ const f = await oauthFixture({ getMCPOAuthStatus: async () => true })+ try {+ f.vm.formRef = { validate: async () => true }+ await f.vm.handleAuthorize()+ assert.equal(f.updates.length, 1)+ f.props.service = { ...f.props.service, name: 'Saved service' }+ await nextTick()+ assert.equal(f.vm.oauthAuthorizing, true)+ await poll(f)+ assert.equal(f.vm.oauthTokenState, 'authorized')+ assert.equal(f.timers.size, 0)+ } finally { f.close() }+})++test('switching services discards a late OAuth status refresh', async () => {+ const status = deferred<{ authorized: boolean; state: string }>()+ const f = await oauthFixture({ getMCPOAuthAuthorizationStatus: (id: string) => id === 'one' ? status.promise : Promise.resolve({ authorized: false, state: 'reauth_required' }) })+ try {+ assert.equal(f.vm.oauthChecking, true)+ f.props.service = { ...f.props.service, id: 'two' }+ await nextTick()+ status.resolve({ authorized: true, state: 'authorized' })+ await status.promise+ await nextTick()+ assert.equal(f.vm.currentService.id, 'two')+ assert.equal(f.vm.oauthAuthorized, false)+ assert.equal(f.vm.oauthTokenState, 'reauth_required')+ assert.equal(f.vm.oauthChecking, false)+ } finally { f.close() }+})++test('a new authorization replaces the old poll and ignores its late completion', async () => {+ const oldStatus = deferred<boolean>()+ let attempt = 0+ const calls: string[] = []+ const f = await oauthFixture({+ getMCPOAuthAuthorizeURL: async () => ({ authorizationUrl: 'https://auth.example/consent', authorizationAttempt: `attempt-${++attempt}` }),+ getMCPOAuthStatus: (_id: string, current: string) => { calls.push(current); return current === 'attempt-1' ? oldStatus.promise : Promise.resolve(true) },+ })+ try {+ await f.vm.startAuthorize('one')+ const pending = poll(f)+ await f.vm.startAuthorize('one')+ assert.equal(f.timers.size, 1)+ oldStatus.resolve(true)+ await pending+ assert.equal(f.vm.oauthAuthorized, false)+ assert.equal(f.vm.oauthAuthorizing, true)+ assert.deepEqual(f.successes, [])+ await poll(f)+ assert.deepEqual(calls, ['attempt-1', 'attempt-2'])+ assert.equal(f.vm.oauthAuthorized, true)+ assert.equal(f.vm.oauthTokenState, 'authorized')+ assert.equal(f.vm.oauthAuthorizing, false)+ assert.equal(f.timers.size, 0)+ assert.deepEqual(f.successes, ['mcpServiceDialog.toasts.authorized'])+ assert.equal(f.popups[1]?.closed, true)+ } finally { f.close() }+})++test('late authorization URL responses are ignored after close, service switch, unmount or a new attempt', async () => {+ for (const scenario of ['close', 'switch', 'unmount', 'retry'].flatMap(action => [+ { action, fail: false }, { action, fail: true },+ ])) {+ const { action, fail } = scenario+ const authorization = deferred<{ authorizationUrl: string; authorizationAttempt: string }>()+ let calls = 0+ const f = await oauthFixture({ getMCPOAuthAuthorizeURL: () => ++calls === 1 ? authorization.promise : Promise.resolve({ authorizationUrl: 'https://auth.example/new', authorizationAttempt: 'new' }) })+ try {+ const pending = f.vm.startAuthorize('one')+ if (action === 'close') f.props.visible = false+ if (action === 'switch') f.props.service = { ...f.props.service, id: 'two' }+ if (action === 'unmount') f.close()+ if (action === 'retry') await f.vm.startAuthorize('one')+ await nextTick()+ if (fail) authorization.reject(new Error('old authorization failed'))+ else authorization.resolve({ authorizationUrl: 'https://auth.example/old', authorizationAttempt: 'old' })+ await pending+ assert.equal(f.popups.length, action === 'retry' ? 1 : 0, action)+ assert.equal(f.timers.size, action === 'retry' ? 1 : 0, action)+ assert.equal(f.vm.oauthAuthorizing, action === 'retry', action)+ assert.deepEqual(f.errors, [], action)+ } finally { f.close() }+ }+})++test('unmount clears the OAuth poll and ignores its in-flight result', async () => {+ const status = deferred<boolean>()+ const f = await oauthFixture({ getMCPOAuthStatus: () => status.promise })+ await f.vm.startAuthorize('one')+ const pending = poll(f)+ f.close()+ assert.equal(f.timers.size, 0)+ status.resolve(true)+ await pending+ assert.equal(f.vm.oauthAuthorized, false)+ assert.equal(f.vm.oauthAuthorizing, false)+ assert.deepEqual(f.successes, [])+})++test('OAuth success invalidates overlapping polls from the completed attempt', async () => {+ const lateStatus = deferred<boolean>()+ let calls = 0+ const f = await oauthFixture({ getMCPOAuthStatus: () => ++calls === 1 ? lateStatus.promise : Promise.resolve(true) })+ try {+ await f.vm.startAuthorize('one')+ const pending = poll(f)+ await poll(f)+ lateStatus.resolve(false)+ await pending+ assert.equal(f.vm.oauthAuthorized, true)+ assert.equal(f.vm.oauthTokenState, 'authorized')+ assert.equal(f.timers.size, 0)+ assert.deepEqual(f.successes, ['mcpServiceDialog.toasts.authorized'])+ } finally { f.close() }+})++test('transient poll errors cannot report an existing token as a new authorization', async () => {+ const f = await oauthFixture({ getMCPOAuthStatus: async () => { throw new Error('offline') } })+ try {+ f.vm.oauthAuthorized = true+ f.vm.oauthTokenState = 'authorized'+ await f.vm.startAuthorize('one')+ await poll(f)+ assert.equal(f.timers.size, 1)+ assert.equal(f.vm.oauthAuthorizing, true)+ assert.deepEqual(f.successes, [])+ f.popups[0]!.closed = true+ await poll(f)+ assert.equal(f.timers.size, 0)+ assert.equal(f.vm.oauthAuthorizing, false)+ assert.deepEqual(f.successes, [])+ } finally { f.close() }+})++test('revoking OAuth invalidates an old poll and ignores a revoke response for another service', async () => {+ const status = deferred<boolean>()+ const revoke = deferred<void>()+ const revoked: string[] = []+ const f = await oauthFixture({+ getMCPOAuthStatus: () => status.promise,+ getMCPOAuthAuthorizationStatus: async (id: string) => ({ authorized: id === 'two', state: id === 'two' ? 'authorized' : 'reauth_required' }),+ revokeMCPOAuthToken: (id: string) => { revoked.push(id); return revoke.promise },+ })+ try {+ await f.vm.startAuthorize('one')+ const pending = poll(f)+ const revoking = f.vm.handleRevokeOAuth()+ assert.equal(f.timers.size, 0)+ f.props.service = { ...f.props.service, id: 'two' }+ await nextTick()+ status.resolve(false)+ revoke.resolve()+ await Promise.all([pending, revoking])+ assert.deepEqual(revoked, ['one'])+ assert.equal(f.vm.oauthAuthorized, true)+ assert.equal(f.vm.oauthTokenState, 'authorized')+ assert.deepEqual(f.successes, [])+ } finally { f.close() }+})diff --git a/frontend/src/views/settings/components/McpServiceDialog.vue b/frontend/src/views/settings/components/McpServiceDialog.vueindex befed4068..285f89f7f 100644--- a/frontend/src/views/settings/components/McpServiceDialog.vue+++ b/frontend/src/views/settings/components/McpServiceDialog.vue@@ -642,18 +642,38 @@ const oauthAuthorized = ref(false)const oauthTokenState = ref<MCPOAuthTokenState>('reauth_required')const oauthChecking = ref(false)const oauthAuthorizing = ref(false)+let oauthGeneration = 0+let oauthPollTimer: number | null = null++// The drawer is reused; cancellation must also invalidate requests already in flight.+function cancelOAuthRequests() {+ oauthGeneration+++ if (oauthPollTimer !== null) window.clearInterval(oauthPollTimer)+ oauthPollTimer = null+ oauthChecking.value = false+ oauthAuthorizing.value = false+}++function isCurrentOAuthRequest(generation: number, serviceId: string) {+ return generation === oauthGeneration && props.visible && isOAuth.value+ && currentService.value?.id === serviceId+}async function refreshOAuthStatus() {- if (props.mode !== 'edit' || !currentService.value?.id || !isOAuth.value) return+ if (props.mode !== 'edit' || !currentService.value?.id || !isOAuth.value || !props.visible) return+ const serviceId = currentService.value.id+ const generation = oauthGenerationoauthChecking.value = truetry {const status = await getMCPOAuthAuthorizationStatus(currentService.value.id)+ if (!isCurrentOAuthRequest(generation, serviceId)) returnoauthAuthorized.value = status.authorizedoauthTokenState.value = status.state} catch (e) {+ if (!isCurrentOAuthRequest(generation, serviceId)) returnconsole.error('Failed to query MCP OAuth status:', e)} finally {- oauthChecking.value = false+ if (isCurrentOAuthRequest(generation, serviceId)) oauthChecking.value = false}}@@ -661,7 +681,9 @@ async function refreshOAuthStatus() {// completion against that service id (independent of props, which may be// re-bound by the parent after a save).async function startAuthorize(serviceId: string) {- if (!serviceId) return+ if (!serviceId || !isCurrentOAuthRequest(oauthGeneration, serviceId)) return+ cancelOAuthRequests()+ const generation = oauthGenerationoauthAuthorizing.value = truetry {const redirectUri = window.location.origin + MCP_OAUTH_CALLBACK_PATH@@ -673,6 +695,7 @@ async function startAuthorize(serviceId: string) {redirect_uri: redirectUri,frontend_redirect: frontendRedirect,})+ if (!isCurrentOAuthRequest(generation, serviceId)) returnif (!authorization.authorizationUrl || !authorization.authorizationAttempt) {MessagePlugin.error(t('mcpServiceDialog.toasts.authorizeFailed', '发起授权失败') as string)oauthAuthorizing.value = false@@ -680,22 +703,28 @@ async function startAuthorize(serviceId: string) {}const popup = window.open(authorization.authorizationUrl, 'mcp_oauth', 'width=600,height=720')// Poll for completion: either the popup closes or the status flips.- const timer = window.setInterval(async () => {+ oauthPollTimer = window.setInterval(async () => {+ if (!isCurrentOAuthRequest(generation, serviceId)) returnconst closed = !popup || popup.closed+ let authorized: boolean | undefinedtry {- oauthAuthorized.value = await getMCPOAuthStatus(serviceId, authorization.authorizationAttempt)- if (oauthAuthorized.value) oauthTokenState.value = 'authorized'+ authorized = await getMCPOAuthStatus(serviceId, authorization.authorizationAttempt)} catch { /* keep polling */ }- if (oauthAuthorized.value || closed) {- window.clearInterval(timer)- oauthAuthorizing.value = false- if (oauthAuthorized.value) {+ if (!isCurrentOAuthRequest(generation, serviceId)) return+ if (authorized !== undefined) {+ oauthAuthorized.value = authorized+ if (authorized) oauthTokenState.value = 'authorized'+ }+ if (authorized || closed) {+ cancelOAuthRequests()+ if (authorized) {try { popup?.close() } catch { /* cross-origin close may throw */ }MessagePlugin.success(t('mcpServiceDialog.toasts.authorized', '授权成功') as string)}}}, 1500)} catch (e) {+ if (!isCurrentOAuthRequest(generation, serviceId)) returnconsole.error('Failed to start MCP OAuth authorization:', e)MessagePlugin.error(t('mcpServiceDialog.toasts.authorizeFailed', '发起授权失败') as string)oauthAuthorizing.value = false@@ -708,18 +737,24 @@ async function startAuthorize(serviceId: string) {// "MCP service is not configured to use OAuth". The drawer stays open the whole// time — the parent re-binds the (now saved) service via the `created` event.async function handleAuthorize() {+ const generation = oauthGenerationconst saved = await saveConnection()- if (saved) await startAuthorize(saved.id)+ if (saved && generation === oauthGeneration) await startAuthorize(saved.id)}async function handleRevokeOAuth() {if (!currentService.value?.id) return+ const serviceId = currentService.value.id+ cancelOAuthRequests()+ const generation = oauthGenerationtry {- await revokeMCPOAuthToken(currentService.value.id)+ await revokeMCPOAuthToken(serviceId)+ if (!isCurrentOAuthRequest(generation, serviceId)) returnoauthAuthorized.value = falseoauthTokenState.value = 'reauth_required'MessagePlugin.success(t('mcpServiceDialog.toasts.revoked', '已撤销授权') as string)} catch (e) {+ if (!isCurrentOAuthRequest(generation, serviceId)) returnconsole.error('Failed to revoke MCP OAuth token:', e)MessagePlugin.error(t('mcpServiceDialog.toasts.revokeFailed', '撤销失败') as string)}@@ -863,12 +898,13 @@ const resetForm = () => {watch(() => [props.visible, props.service] as const,([visible, service], previous) => {- if (!visible) { usageGeneration++; generatingUsage.value = false; return }+ if (!visible) { cancelOAuthRequests(); usageGeneration++; generatingUsage.value = false; return }const opening = !previous?.[0]if (!opening && service?.id && savedService.value?.id === service.id) {savedService.value = servicereturn}+ cancelOAuthRequests()usageGeneration++generatingUsage.value = falsesavedService.value = service@@ -1012,7 +1048,9 @@ async function handleGenerateUsage() {}}-onBeforeUnmount(() => { usageGeneration++ })+watch(isOAuth, (enabled) => { if (!enabled) cancelOAuthRequests() })++onBeforeUnmount(() => { cancelOAuthRequests(); usageGeneration++ })const handleSubmit = async () => {const id = currentService.value?.id