Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

fix(frontend:auth): safely replay requests after session refresh

johaven1d96f81e6b1d
diff --git a/frontend/src/app/auth/auth.interceptor.ts b/frontend/src/app/auth/auth.interceptor.ts
index 7027c898..049c43a2 100644
--- a/frontend/src/app/auth/auth.interceptor.ts
+++ b/frontend/src/app/auth/auth.interceptor.ts
@@ -1,9 +1,12 @@
-import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'
+import { PlatformLocation } from '@angular/common'
+import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpXsrfTokenExtractor } from '@angular/common/http'
import { inject, Injectable, Injector } from '@angular/core'
+import { HTTP_CSRF_IGNORED_METHODS } from '@sync-in-server/backend/src/applications/applications.constants'
import { API_ADMIN_IMPERSONATE_LOGOUT } from '@sync-in-server/backend/src/applications/users/constants/routes'
+import { CSRF_KEY } from '@sync-in-server/backend/src/authentication/constants/auth'
import { API_AUTH_LOGIN, API_AUTH_LOGOUT, API_AUTH_REFRESH } from '@sync-in-server/backend/src/authentication/constants/routes'
-import { BehaviorSubject, Observable, retry, throwError, timer } from 'rxjs'
-import { catchError, filter, finalize, switchMap, take } from 'rxjs/operators'
+import { Observable, retry, shareReplay, throwError, timer } from 'rxjs'
+import { catchError, finalize, switchMap } from 'rxjs/operators'
import { SERVICE_UNAVAILABLE_ERROR } from '../app.constants'
import { hasReservedUrlChars } from '../common/utils/functions'
import { AuthService } from './auth.service'
@@ -13,9 +16,10 @@ import { AuthService } from './auth.service'
})
export class AuthInterceptor implements HttpInterceptor {
private readonly injector = inject(Injector)
+ private readonly platformLocation = inject(PlatformLocation)
+ private readonly xsrfTokenExtractor = inject(HttpXsrfTokenExtractor)
private _auth?: AuthService
- private isRefreshingToken = false
- private readonly waitForRefreshToken = new BehaviorSubject<boolean>(false)
+ private refreshToken$?: Observable<boolean>
private readonly retryCount = 3
private readonly retryWaitMilliSeconds = 2000
@@ -24,6 +28,7 @@ export class AuthInterceptor implements HttpInterceptor {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
+ // File API paths may contain raw reserved characters that must be encoded before the request is sent.
const encodedUrl = hasReservedUrlChars(request.url)
if (encodedUrl) {
request = request.clone({ url: encodedUrl })
@@ -40,7 +45,7 @@ export class AuthInterceptor implements HttpInterceptor {
}
}),
catchError((e: HttpErrorResponse) => {
- if (e.status === 401) {
+ if (e.status === 401 && this.isSameOrigin(request.url)) {
return this.handleAuthorizationError(request, next, e)
} else if (e.status === 503) {
return this.handleServiceUnavailable(request, e)
@@ -64,29 +69,48 @@ export class AuthInterceptor implements HttpInterceptor {
return throwError(() => error)
}
- private handleAuthorizationError(request: HttpRequest<any>, next: HttpHandler, error: HttpErrorResponse): Observable<any> {
+ private handleAuthorizationError(request: HttpRequest<any>, next: HttpHandler, error: HttpErrorResponse): Observable<HttpEvent<any>> {
console.debug('AuthInterceptor:', request.url, error.status)
if ([API_AUTH_REFRESH, API_AUTH_LOGIN, API_AUTH_LOGOUT, API_ADMIN_IMPERSONATE_LOGOUT].indexOf(request.url) === -1) {
- if (this.isRefreshingToken) {
- console.debug('AuthInterceptor: wait for refresh token')
- return this.waitForRefreshToken.pipe(
- filter((result) => !result),
- take(1),
- switchMap(() => next.handle(this.auth.checkCSRF(request)))
- )
- } else {
- console.debug('AuthInterceptor: refreshing token')
- this.isRefreshingToken = true
- this.waitForRefreshToken.next(true)
- return this.auth.refreshToken().pipe(
- switchMap(() => {
- this.waitForRefreshToken.next(false)
- return next.handle(this.auth.checkCSRF(request))
- }),
- finalize(() => (this.isRefreshingToken = false))
- )
- }
+ return this.getRefreshToken().pipe(
+ switchMap((authenticated) => (authenticated ? next.handle(this.refreshCSRFHeader(request)) : throwError(() => error)))
+ )
}
return throwError(() => error)
}
+
+ private getRefreshToken(): Observable<boolean> {
+ if (this.refreshToken$) {
+ console.debug('AuthInterceptor: wait for refresh token')
+ return this.refreshToken$
+ }
+
+ console.debug('AuthInterceptor: refreshing token')
+ this.refreshToken$ = this.auth.refreshToken().pipe(
+ finalize(() => (this.refreshToken$ = undefined)),
+ shareReplay({ bufferSize: 1, refCount: false })
+ )
+ return this.refreshToken$
+ }
+
+ private refreshCSRFHeader(request: HttpRequest<any>): HttpRequest<any> {
+ if (HTTP_CSRF_IGNORED_METHODS.has(request.method) || !this.isSameOrigin(request.url)) {
+ return request
+ }
+
+ const csrfToken = this.xsrfTokenExtractor.getToken()
+ if (!csrfToken || request.headers.get(CSRF_KEY) === csrfToken) {
+ return request
+ }
+ return request.clone({ headers: request.headers.set(CSRF_KEY, csrfToken) })
+ }
+
+ private isSameOrigin(url: string): boolean {
+ try {
+ const locationUrl = new URL(this.platformLocation.href)
+ return new URL(url, locationUrl).origin === locationUrl.origin
+ } catch {
+ return false
+ }
+ }
}
diff --git a/frontend/src/app/auth/auth.service.ts b/frontend/src/app/auth/auth.service.ts
index 8cab7628..9d4791fe 100644
--- a/frontend/src/app/auth/auth.service.ts
+++ b/frontend/src/app/auth/auth.service.ts
@@ -1,4 +1,4 @@
-import { HttpClient, HttpErrorResponse, HttpRequest } from '@angular/common/http'
+import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { inject, Injectable } from '@angular/core'
import { Router } from '@angular/router'
import { CLIENT_MISSING_ERROR, CLIENT_TOKEN_EXPIRED_ERROR } from '@sync-in-server/backend/src/applications/sync/constants/auth'
@@ -10,7 +10,6 @@ import type {
SyncClientAuthRegistration
} from '@sync-in-server/backend/src/applications/sync/interfaces/sync-client-auth.interface'
import { API_ADMIN_IMPERSONATE_LOGOUT } from '@sync-in-server/backend/src/applications/users/constants/routes'
-import { CSRF_KEY } from '@sync-in-server/backend/src/authentication/constants/auth'
import {
API_AUTH_LOGIN,
API_AUTH_LOGOUT,
@@ -27,7 +26,6 @@ import { switchMap, tap } from 'rxjs/operators'
import { SERVICE_INTERRUPTION_ERROR } from '../app.constants'
import { USER_PATH } from '../applications/users/user.constants'
import { UserService } from '../applications/users/user.service'
-import { getCookie } from '../common/utils/functions'
import { EVENT } from '../electron/constants/events'
import { Electron } from '../electron/electron.service'
import { LayoutService } from '../layout/layout.service'
@@ -189,14 +187,6 @@ export class AuthService {
return of(true)
}
- checkCSRF(request: HttpRequest<any>): HttpRequest<any> {
- // fix xsrf in header when request is replayed after the refresh token phase
- if (request.headers.has(CSRF_KEY)) {
- return request.clone({ headers: request.headers.set(CSRF_KEY, getCookie(CSRF_KEY)) })
- }
- return request
- }
-
loginWith2Fa(verify: TwoFaVerifyDto): Observable<TwoFaResponseDto> {
return this.http.post<TwoFaResponseDto>(API_TWO_FA_LOGIN_VERIFY, verify)
}