All files / app/interceptors auth.interceptor.ts

98.73% Statements 78/79
97.22% Branches 35/36
100% Functions 29/29
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 212 2131x 1x 1x 1x                 1x 1x 1x 1x   1x 1x 1x 1x     4x     1x 38x 38x 38x 38x         22x 21x   22x               38x 1x       37x 3x       34x     34x 9x       25x 5x         20x 23x   20x         25x   1x 1x     24x         24x                     15x 2x 2x         13x               4x 3x     4x         4x   3x             3x     1x       1x         9x       37x             38x 1x     37x 36x   1x       40x             96x   96x 96x                       96x   96x       37x       56x       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,
    HttpContextToken,
    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';
 
// Internal request marker to prevent infinite CSRF retry loops without affecting CORS preflight
export const CSRF_ALREADY_RETRIED = new HttpContextToken<boolean>(() => false);
 
@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(
            catchError(error => {
                this.logger.error('Failed to get CSRF token', error);
                return throwError(() => error);
            }),
            switchMap(csrfToken => {
                const csrfRequest = request.clone({
                    setHeaders: {
                        'X-CSRF-Token': csrfToken,
                    },
                });
                return next.handle(csrfRequest).pipe(catchError(error => this.handleError(error, request, next)));
            })
        );
    }
 
    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.context.get(CSRF_ALREADY_RETRIED) // 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({
                        context: request.context.set(CSRF_ALREADY_RETRIED, true),
                        setHeaders: {
                            'X-CSRF-Token': newToken,
                        },
                        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,
};