All files / app/interceptors auth.interceptor.ts

98.71% Statements 77/78
97.22% Branches 35/36
100% Functions 28/28
98.52% Lines 67/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 2121x 1x 1x 1x               1x 1x 1x 1x   1x 1x 1x 1x     1x     1x 37x 37x 37x 37x         21x 20x   21x               37x 1x       36x 3x       33x     33x 9x       24x 5x         19x 22x   19x         24x   23x         23x     7x 7x                     14x 2x 2x         12x               4x 3x     4x         4x   3x             3x     1x       1x         8x       36x             37x 1x     36x 35x   1x       39x             93x   93x 93x                       93x   93x       36x       54x       5x       1x          
import { environment } from '../../environments/environment';
import { AuthService } from '../services/auth/auth.service';
import { CsrfService } from '../services/auth/csrf.service';
import {
    HttpInterceptor,
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse,
    HTTP_INTERCEPTORS,
} from '@angular/common/http';
import { Injectable, inject, Injector } from '@angular/core';
import { LoggerService } from '@drevo-web/core';
import { Observable, throwError } from 'rxjs';
import { catchError, filter, finalize, shareReplay, switchMap, take } from 'rxjs/operators';
 
const STATE_CHANGING_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
const CSRF_ENDPOINTS = ['/api/auth/csrf'];
const AUTH_ENDPOINTS = ['/api/auth/login', '/api/auth/logout'];
const AUTH_CHECK_ENDPOINT = '/api/auth/me';
 
// Custom header to mark requests that have already been retried for CSRF
const CSRF_RETRY_HEADER = 'X-CSRF-Retry';
 
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private readonly apiUrl = environment.apiUrl;
    private readonly injector = inject(Injector);
    private readonly csrfService = inject(CsrfService);
    private readonly logger = inject(LoggerService).withContext('AuthInterceptor');
 
    // Lazy-loaded to avoid circular dependency (AuthService -> HttpClient -> HTTP_INTERCEPTORS)
    private _authService: AuthService | undefined;
    private get authService(): AuthService {
        if (!this._authService) {
            this._authService = this.injector.get(AuthService);
        }
        return this._authService;
    }
 
    // Shared observable for token refresh to handle concurrent CSRF failures
    private refreshingToken$: Observable<string> | undefined;
 
    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        // Only intercept API requests
        if (!this.isApiRequest(request.url)) {
            return next.handle(request);
        }
 
        // Skip CSRF token endpoint
        if (this.isCsrfEndpoint(request.url)) {
            return next.handle(this.addCredentials(request));
        }
 
        // Add credentials to all API requests
        request = this.addCredentials(request);
 
        // For GET requests, just add credentials
        if (!this.isStateChangingMethod(request.method)) {
            return next.handle(request).pipe(catchError(error => this.handleError(error, request, next)));
        }
 
        // For auth endpoints (login/logout), add CSRF directly without waiting
        if (this.isAuthEndpoint(request.url)) {
            return this.addCsrfAndSend(request, next);
        }
 
        // For other state-changing requests, wait for auth operations to complete
        // This prevents race conditions where requests use outdated CSRF tokens
        return this.authService.isAuthOperationInProgress$.pipe(
            filter(inProgress => !inProgress),
            take(1),
            switchMap(() => this.addCsrfAndSend(request, next))
        );
    }
 
    private addCsrfAndSend(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        return this.csrfService.getCsrfToken().pipe(
            switchMap(csrfToken => {
                const csrfRequest = request.clone({
                    setHeaders: {
                        'X-CSRF-Token': csrfToken,
                    },
                });
                return next.handle(csrfRequest).pipe(catchError(error => this.handleError(error, request, next)));
            }),
            catchError(error => {
                this.logger.error('Failed to get CSRF token', error);
                return throwError(() => error);
            })
        );
    }
 
    private handleError(
        error: HttpErrorResponse,
        request: HttpRequest<unknown>,
        next: HttpHandler
    ): Observable<HttpEvent<unknown>> {
        // Handle 401 Unauthorized - redirect to login
        if (error.status === 401 && !this.isAuthCheckOrLoginEndpoint(request.url)) {
            this.authService.handleUnauthorized();
            return throwError(() => error);
        }
 
        // Handle 403 CSRF validation failed - retry with new token (once only)
        // Uses shared observable to coordinate concurrent refresh attempts
        if (
            error.status === 403 &&
            error.error?.errorCode === 'CSRF_VALIDATION_FAILED' &&
            this.isStateChangingMethod(request.method) &&
            !request.headers.has(CSRF_RETRY_HEADER) // Prevent infinite retry loops
        ) {
            // If no refresh is in progress, start one with shareReplay
            // so all concurrent failures share the same token refresh
            if (!this.refreshingToken$) {
                this.refreshingToken$ = this.csrfService.refreshCsrfToken().pipe(
                    shareReplay(1),
                    finalize(() => {
                        this.refreshingToken$ = undefined;
                    })
                );
            }
 
            return this.refreshingToken$.pipe(
                switchMap(newToken => {
                    const retryRequest = request.clone({
                        setHeaders: {
                            'X-CSRF-Token': newToken,
                            [CSRF_RETRY_HEADER]: 'true', // Mark as retried to prevent loops
                        },
                        withCredentials: true,
                    });
                    return next.handle(retryRequest);
                }),
                catchError(retryError => {
                    this.logger.error('CSRF retry request failed', {
                        originalError: error,
                        retryError,
                    });
                    return throwError(() => error); // keep returning original error
                })
            );
        }
 
        return throwError(() => error);
    }
 
    private addCredentials(request: HttpRequest<unknown>): HttpRequest<unknown> {
        return request.clone({
            withCredentials: true,
        });
    }
 
    private isApiRequest(url: string): boolean {
        // Check for relative API paths (works in all environments)
        if (url.startsWith('/api/')) {
            return true;
        }
        // Check for absolute API URL (only if apiUrl is configured)
        if (this.apiUrl && url.startsWith(this.apiUrl)) {
            return true;
        }
        return false;
    }
 
    private isStateChangingMethod(method: string): boolean {
        return STATE_CHANGING_METHODS.includes(method.toUpperCase());
    }
 
    /**
     * Extract URL path without query string and fragment
     */
    private getUrlPath(url: string): string {
        try {
            // Handle both absolute and relative URLs
            const urlObj = new URL(url, 'http://dummy');
            return urlObj.pathname;
        } catch {
            // Fallback: remove query string and fragment manually
            return url.split('?')[0].split('#')[0];
        }
    }
 
    /**
     * Check if URL path matches endpoint exactly or ends with it
     * This prevents false positives like /api/auth/csrf-test matching /api/auth/csrf
     */
    private matchesEndpoint(url: string, endpoint: string): boolean {
        const path = this.getUrlPath(url);
        // Check exact match or if path ends with the endpoint
        return path === endpoint || path.endsWith(endpoint);
    }
 
    private isCsrfEndpoint(url: string): boolean {
        return CSRF_ENDPOINTS.some(endpoint => this.matchesEndpoint(url, endpoint));
    }
 
    private isAuthEndpoint(url: string): boolean {
        return AUTH_ENDPOINTS.some(endpoint => this.matchesEndpoint(url, endpoint));
    }
 
    private isAuthCheckOrLoginEndpoint(url: string): boolean {
        return this.isAuthEndpoint(url) || this.matchesEndpoint(url, AUTH_CHECK_ENDPOINT);
    }
}
 
export const authInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true,
};