fix(web): keep session on transient network errors during context init
The web frontend (now maintained in this monorepo under web/) re-establishes the authenticated context on page reload by calling updateContext(), which fetches user data over HTTP. Previously any error thrown there - including transient connectivity failures (ERR_NETWORK, timeouts, fetch TypeErrors) - was treated like an expired or invalid token, forcing a logout and redirect to the access-denied page. This adds an isNetworkError() classifier so connectivity failures preserve the existing session, while genuine auth rejections (carrying an HTTP response such as 401) still trigger the existing logout flow. Applies to the page-reload token-restore path and the addUserLoaded handler. Ports the fix for owncloud/web#12980 (originally owncloud/web#13941; owncloud/web is deprecated and development moved into this repo). Signed-off-by: dj4oC <noreply@github.com>
This commit is contained in:
1 parent
fe6a3f5d0a
commit
ac399eb8d8
3 files changed
+158
-3
No files matched your search
@@ -0,0 +1,11 @@
|
||||
Bugfix: Keep the web session on transient network errors during context init
|
||||
|
||||
We've fixed a bug in the web frontend where a temporary connectivity failure (e.g. a
|
||||
fast page reload cancelling in-flight requests, or a short offline period) while
|
||||
re-establishing the authenticated context on page load was treated like an expired or
|
||||
invalid token. This forced a full logout and redirected the user to the "trouble
|
||||
connecting to the login service" page. Network/connectivity errors now preserve the
|
||||
existing session, while genuine authentication rejections (e.g. a 401) still trigger
|
||||
the regular logout flow as before.
|
||||
|
||||
https://github.com/owncloud/web/issues/12980
|
||||
@@ -26,6 +26,40 @@ import { PublicLinkType } from '@ownclouders/web-client'
|
||||
import { WebWorkersStore } from '@ownclouders/web-pkg'
|
||||
import { isSilentRedirectRoute } from '../../helpers/silentRedirect'
|
||||
|
||||
/**
|
||||
* Distinguishes a transient network/connectivity failure from a genuine
|
||||
* authentication rejection.
|
||||
*
|
||||
* When the context is (re-)established on page reload, user data is fetched over
|
||||
* HTTP. If that request fails because of a temporary connectivity issue (offline,
|
||||
* DNS, a page refresh cancelling in-flight requests, ...) we must NOT treat it like
|
||||
* an expired/invalid token and tear down the session. Only errors that carry an HTTP
|
||||
* response (e.g. a `401`) are real auth rejections.
|
||||
*
|
||||
* Recognised connectivity failures:
|
||||
* - Axios errors without an HTTP `response`, with code `ERR_NETWORK` (connection
|
||||
* refused / DNS / CORS / offline) or `ECONNABORTED` (timeout).
|
||||
* - Browser `fetch` failures, which surface as a `TypeError` (Safari: "Load failed",
|
||||
* Chromium: "Failed to fetch", Firefox: "NetworkError when attempting to fetch ...").
|
||||
*/
|
||||
export const isNetworkError = (e: unknown): boolean => {
|
||||
if (e instanceof TypeError) {
|
||||
return /load failed|failed to fetch|networkerror/i.test(e.message)
|
||||
}
|
||||
|
||||
if (e && typeof e === 'object') {
|
||||
const err = e as { response?: unknown; code?: string }
|
||||
// An error that carries an HTTP response is an answered request, not a
|
||||
// connectivity failure - let the regular auth-error handling deal with it.
|
||||
if (err.response) {
|
||||
return false
|
||||
}
|
||||
return err.code === 'ERR_NETWORK' || err.code === 'ECONNABORTED'
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export class AuthService implements AuthServiceInterface {
|
||||
private clientService: ClientService
|
||||
private configStore: ConfigStore
|
||||
@@ -194,7 +228,11 @@ export class AuthService implements AuthServiceInterface {
|
||||
this.updateMfaExpiryTimer()
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
await this.handleAuthError(unref(this.router.currentRoute))
|
||||
// A transient connectivity failure must not force a logout - keep the
|
||||
// session and let the regular auth flow recover once back online.
|
||||
if (!isNetworkError(e)) {
|
||||
await this.handleAuthError(unref(this.router.currentRoute))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -259,7 +297,11 @@ export class AuthService implements AuthServiceInterface {
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
await this.handleAuthError(unref(this.router.currentRoute))
|
||||
// A transient connectivity failure must not force a logout - keep the
|
||||
// session and let the regular auth flow recover once back online.
|
||||
if (!isNetworkError(e)) {
|
||||
await this.handleAuthError(unref(this.router.currentRoute))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ConfigStore, useAuthStore, useConfigStore } from '@ownclouders/web-pkg'
|
||||
import { mock } from 'vitest-mock-extended'
|
||||
import { Router } from 'vue-router'
|
||||
import { AuthService } from '../../../../src/services/auth/authService'
|
||||
import { AuthService, isNetworkError } from '../../../../src/services/auth/authService'
|
||||
import { UserManager } from '../../../../src/services/auth/userManager'
|
||||
import { RouteLocation, createRouter, createTestingPinia } from '@ownclouders/web-test-helpers'
|
||||
import { User } from 'oidc-client-ts'
|
||||
@@ -224,4 +224,106 @@ describe('AuthService', () => {
|
||||
expect(mockSignInRedirect).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isNetworkError', () => {
|
||||
it.each([
|
||||
['axios ERR_NETWORK (offline / connection refused)', { code: 'ERR_NETWORK' }, true],
|
||||
['axios ECONNABORTED (timeout)', { code: 'ECONNABORTED' }, true],
|
||||
['fetch TypeError - Safari "Load failed"', new TypeError('Load failed'), true],
|
||||
['fetch TypeError - Chromium "Failed to fetch"', new TypeError('Failed to fetch'), true],
|
||||
[
|
||||
'fetch TypeError - Firefox "NetworkError ..."',
|
||||
new TypeError('NetworkError when attempting to fetch resource.'),
|
||||
true
|
||||
],
|
||||
['an answered request carrying an HTTP response (401)', { response: { status: 401 } }, false],
|
||||
[
|
||||
'an ERR_NETWORK code that nonetheless carries a response',
|
||||
{ code: 'ERR_NETWORK', response: { status: 500 } },
|
||||
false
|
||||
],
|
||||
['an unrelated TypeError (real bug)', new TypeError('foo is not a function'), false],
|
||||
['an error with an unknown code', { code: 'ERR_BAD_REQUEST' }, false],
|
||||
['a null error', null, false],
|
||||
['a plain string error', 'boom', false]
|
||||
])('returns %s => %s', (_desc, error, expected) => {
|
||||
expect(isNetworkError(error)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('initializeContext auth-error classification', () => {
|
||||
const buildAuthService = (rejection: unknown) => {
|
||||
const authService = new AuthService()
|
||||
Object.defineProperty(authService, 'userManager', {
|
||||
value: mock<UserManager>({
|
||||
getAccessToken: vi.fn().mockResolvedValue('access-token'),
|
||||
getUser: vi.fn().mockResolvedValue(mock<User>({ expires_in: 3600 })),
|
||||
updateContext: vi.fn().mockRejectedValue(rejection)
|
||||
})
|
||||
})
|
||||
const router = createRouter()
|
||||
initAuthService({ authService, router })
|
||||
const handleAuthErrorSpy = vi
|
||||
.spyOn(authService, 'handleAuthError')
|
||||
.mockResolvedValue(undefined)
|
||||
return { authService, handleAuthErrorSpy }
|
||||
}
|
||||
|
||||
it('preserves the session (no handleAuthError) when updateContext fails with a network error on reload', async () => {
|
||||
const { authService, handleAuthErrorSpy } = buildAuthService({ code: 'ERR_NETWORK' })
|
||||
|
||||
await authService.initializeContext(mock<RouteLocation>({}))
|
||||
|
||||
expect(handleAuthErrorSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('triggers handleAuthError when updateContext fails with a 401 on reload', async () => {
|
||||
const { authService, handleAuthErrorSpy } = buildAuthService({ response: { status: 401 } })
|
||||
|
||||
await authService.initializeContext(mock<RouteLocation>({}))
|
||||
|
||||
expect(handleAuthErrorSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('addUserLoaded handler preserves the session on a network error but logs out on an auth rejection', async () => {
|
||||
const authService = new AuthService()
|
||||
let userLoadedCb: (user: User) => Promise<void>
|
||||
const updateContext = vi.fn()
|
||||
Object.defineProperty(authService, 'userManager', {
|
||||
value: mock<UserManager>({
|
||||
// skip the reload branch, we drive the addUserLoaded handler directly
|
||||
getAccessToken: vi.fn().mockResolvedValue(null),
|
||||
// force event-handler registration (mock<> would otherwise make this truthy)
|
||||
areEventHandlersRegistered: false,
|
||||
updateContext,
|
||||
events: {
|
||||
addAccessTokenExpired: vi.fn(),
|
||||
addAccessTokenExpiring: vi.fn(),
|
||||
addUserLoaded: vi.fn().mockImplementation((cb) => {
|
||||
userLoadedCb = cb
|
||||
}),
|
||||
addUserUnloaded: vi.fn(),
|
||||
addSilentRenewError: vi.fn()
|
||||
} as unknown as UserManager['events']
|
||||
})
|
||||
})
|
||||
const router = createRouter()
|
||||
initAuthService({ authService, router })
|
||||
const handleAuthErrorSpy = vi
|
||||
.spyOn(authService, 'handleAuthError')
|
||||
.mockResolvedValue(undefined)
|
||||
|
||||
await authService.initializeContext(mock<RouteLocation>({}))
|
||||
|
||||
// network error -> session preserved
|
||||
updateContext.mockRejectedValueOnce({ code: 'ERR_NETWORK' })
|
||||
await userLoadedCb(mock<User>({ access_token: 'tok', expires_in: 3600 }))
|
||||
expect(handleAuthErrorSpy).not.toHaveBeenCalled()
|
||||
|
||||
// auth rejection -> existing logout flow
|
||||
updateContext.mockRejectedValueOnce({ response: { status: 401 } })
|
||||
await userLoadedCb(mock<User>({ access_token: 'tok', expires_in: 3600 }))
|
||||
expect(handleAuthErrorSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user